Serializing a private struct - Can it be done?

I have a public class that contains a private struct. The struct contains properties (mostly string) that I want to serialize. When I attempt to serialize the struct and stream it to disk, using XmlSerializer, I get an error saying only public types can be serialized. I don't need, and don't want, this struct to be public. Is there a way I can serialize it and keep it private?


How do I prevent floated-right content from overlapping main content?

I have the following HTML:

<td class='a'>
  <img src='/images/some_icon.png' alt='Some Icon' />
  <span>Some content that's waaaaaaaaay too long to fit in the allotted space, but which can get cut off.</span>
</td>

It should display as follows:

[Some content that's wa [ICON]]

I have the following CSS:

td.a span {
  overflow: hidden;
  white-space: nowrap;
  z-index: 1;
}

td.a img {
  display: block;
  float: right;
  z-index: 2;
}

When I resize the browser to cut off the text, it cuts off at the edge of the <td> rather than before the <img>, which leaves the <img> overlapping the <span> content. I've tried various padding and margins, but nothing seemed to work. Is this possible?

NB: It's very difficult to add a <td> that just contains the <img> here. If it were easy, I'd just do that :)


Gradle command line

I'm trying to run a shell script with gradle. I currently have something like this

def test = project.tasks.create("test", Exec) {
    commandLine 'bash', '-c', 'bash C:/my file dir/script.sh'
}

The problem is that I cannot run this script because i have spaces in my dir name. I have tried everything e.g:

commandLine 'bash', '-c', 'bash C:/my file dir/script.sh'.tokenize()
commandLine 'bash', '-c', ['bash', 'C:/my file dir/script.sh']
commandLine 'bash', '-c', new StringBuilder().append('bash').append('C:/my file dir/script.sh')
commandLine 'bash', '-c', 'bash "C:/my file dir/script.sh"'
File dir = file('C:/my file dir/script.sh')
commandLine 'bash', '-c', 'bash ' + dir.getAbsolutePath();

Im using windows7 64bit and if I use a path without spaces the script runs perfectly, therefore the only issue as I can see is how gradle handles spaces.


Loop variable as parameter in asynchronous function call

I have an object with the following form.

sortedFilters:
  {
    task:{...},
    appointment:{...},
    email:{...}
  }

Now i want to use a for-in loop, to build my tasks array for async.parallel, which contains the functions to be executed asynchronously:

var tasks = [];
for (var entity in sortedFilters) {
  tasks.push(function(callback) {
    var entityResult = fetchRecordsForEntity(entity, businessUnits, sortedFilters);
    var formattedEntityResults = formatResults(entity, entityResult);
    callback(null, formattedEntityResults);
  });
}

The problem is, that at the moment the functions are called, entity points at the last value of the loop (in this case it would be email).

How can i nail the exact value at the moment the function is added to the array?


Canot get the href value

Hi I need to valid the href is empty or not on my page using javascript. I searched the site and found some example, but it didn't worked for me. I must miss something that I didn't notice. Would someone point me the good direction and my mistake. I got the error" Unable to get property 'getattribute' of undefined or null reference. The <a> element is like that <a name="playback" href=""> on html file.

Thanks in advance.

There is my code which is run on load event:

var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++)
{
     anchors[i].onclick = function() {
         if (anchors == null) {
             alert('null');
         }
         else {
             var link = anchors[i].getAttribute("href");
            //var link= anchors[i].attributes['href']  this line doesn't work too.
             }
        }
    }
}


How to send values to from android to a html page in webview

I need to pass a value from java to the html in android.
i am having a list view, from which i am selecting a particular item,
the selected item should appear on the html page in a webview
is there any way to do it in android, kindly help me please,
i have searched many websites but all got in vain,

Thanks and Regards

rajesh


Why is Python's weekday() different from tm_wday in C?

Python documentation defines datetime.weekday() as an integer, where Monday is 0 and Sunday is 6, while C's tm.tm_wday is defined as days since Sunday. Therefore tm_wday is (datetime.weekday() + 1) % 7, which is quite inconvenient. Given that Python generally sticks close to C equivalents, why was this made this way?


get new inserted ID in MVC Controller to jQuery

I am updating an entity normally inside a controller as follows :-

[HttpPost]
public ActionResult Create(Project project)
{
  //var model = new CompositeImageModel(0);
  if (ModelState.IsValid)
  {
    //var model = new CompositeImageModel(project.ProjectID);
    db.Projects.Add(project);
    db.SaveChanges();
    ViewBag.ProjectID = project.ProjectID;

    return RedirectToAction("Index");
  }

  return View();
}

And I wish to grab this new id "ViewBag.ProjectID" inside my Jquery AJAX code :-

onSaveBegin: function () {
  //CODE FOR SAVE BEGIN
  $('#imageList').fadeIn('slow');
  $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/222"); });

},

instead of the hardcoded "222".

How can I get it?

Thanks for your help and time

**********UPDATE****************************
So I have updated my Jquery as follows :-

<script type="text/javascript">
$(document).ready(function () {

    var imageList = $('#imageList'),
        submitButt = $('#submitButt');

    //hide the imageList initially
    imageList.hide(); //hide all but the first paragraph

    });

    var Project = {
        save: function () {
            var projectForm = $("#projectForm");
            if (projectForm.valid()) {
                projectForm.submit();
            }
            else {
                Project.onInvalidForm();
            }
        },
        onInvalidForm: function () {
            //CODE FOR INVALID FORM
        },
        onSaveBegin: function () {
            //CODE FOR SAVE BEGIN
            $('#imageList').fadeIn('slow');
        },
        onSaveSuccess: function () {
            //CODE FOR SAVE SUCCESS
        },
        onSaveFailure: function () {
            //CODE FOR SAVE FAILURE
            alert(ViewBag.ProjectID);
        },
        onSaveComplete: function () {
            //CODE FOR SAVE COMPLETE
            //var hfProjectId = $("#hfProjectId").val();
            //$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/" + hfProjectId); });
            $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(ViewBag.ProjectID) ); });
        }
    };

I have moved the code to onSaveComplete, since I should have the ProjectID then, but still am not able to get it yet.
however both options will not work.

**********UPDATE 2 ***************************

@model MvcCommons.Models.Project

@{
ViewBag.Title = "Create";

}

<h2>Create</h2>

@{
Layout = "~/Views/Shared/_Layout.cshtml";
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();

}

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>

<script type="text/javascript">
        $(document).ready(function () {

    var imageList = $('#imageList'),
        submitButt = $('#submitButt');

        //hide the imageList initially
    imageList.hide(); //hide all but the first paragraph

    });

    var Project = {
        save: function () {
            var projectForm = $("#projectForm");
            if (projectForm.valid()) {
                projectForm.submit();
            }
            else {
                Project.onInvalidForm();
            }
        },
        onInvalidForm: function () {
            //CODE FOR INVALID FORM
        },
        onSaveBegin: function () {
            //CODE FOR SAVE BEGIN
            $('#imageList').fadeIn('slow');
        },
        onSaveSuccess: function () {
            //CODE FOR SAVE SUCCESS
        },
        onSaveFailure: function () {
            //CODE FOR SAVE FAILURE
            alert(ViewBag.ProjectID);
        },
        onSaveComplete: function () {
            //CODE FOR SAVE COMPLETE
            //var hfProjectId = $("#hfProjectId").val();
            //$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/" + hfProjectId); });

            $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(ViewBag.ProjectID) ); });
        }
    };

@{
    var projectID = int.Parse(ViewBag.ProjectID);

 }

@using (Ajax.BeginForm(

    "/Create",

    new { },

    new AjaxOptions

    {

        InsertionMode = InsertionMode.Replace,

        UpdateTargetId = "projectFormContainer",

        OnComplete = "Project.onSaveComplete",

        OnFailure = "Project.onSaveFailure",
        OnSuccess = "Project.onSaveSuccess",
        OnBegin = "Project.onSaveBegin"

    },

    new { id = "projectForm", name = "projectForm" }))

    {

         @Html.Hidden("hfProjectId", ViewBag.ProjectID)

        <div class="editor-label">
            @Html.LabelFor(m => m.ProjectTitle)
         </div>
         <div class="editor-field">
            @Html.TextBoxFor(m => m.ProjectTitle)
            @Html.ValidationMessageFor(m => m.ProjectTitle)
         </div>
         <div class="editor-label">
            @Html.LabelFor(m => m.ProjectText)
         </div>
         <div class="editor-field">
            @Html.TextBoxFor(m => m.ProjectText)
            @Html.ValidationMessageFor(m => m.ProjectText)
         </div>
         <p>
            <input type="submit" value="Submit" onclick="Project.save();" />
         </p>
      </div>
}

<div id='imageList'>
    <h2>Upload Image(s)</h2>
    @{
        Html.RenderPartial("~/Views/File/ImageUpload.cshtml", new MvcCommons.ViewModels.ImageModel((int)ViewBag.ProjectID));
     }
</div>

    @Html.ActionLink("Back to List", "Index")

Code updated with latest changes

***********UPDATED*************************

Mode updates :-
Change the @Html.Hidden to this now :-

            @if(Model != null)
        {
             @Html.Hidden("hfProjectId", Model.ProjectID)
        }

The Javascript is still the same :=

            onSaveComplete: function () {
            //CODE FOR SAVE COMPLETE
            var hfProjectId = $("#hfProjectId").val();
            alert(hfProjectId);
            $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/" + hfProjectId); });
            //$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(ViewBag.ProjectID) ); });
        }

change the var projectID

@{
if (Model != null)
{
    var projectID = Model.ProjectID;
}

}

in the controller, returning a "View", with the model

        [HttpPost]
    public ActionResult Create(Project project)
    {
        if (ModelState.IsValid)
        {
            db.Projects.Add(project);
            db.SaveChanges();
            ViewBag.ProjectID = project.ProjectID;
            //return RedirectToAction("Index");
            return View("Create", project);
        }

        return View();
    }

Still no luck though!

********** FINAL UPDATE ****************************
I have decided to create a Project View Model and try to pass variables through it, since the ViewBag was not working in my case.  So I changed the HttpPost Create function in the Controller to look as follows :-

        [HttpPost]
    public ActionResult Create(Project project)
    {
        ProjectModel viewModel = new ProjectModel();

        if (ModelState.IsValid)
        {
            db.Projects.Add(project);
            db.SaveChanges();
            viewModel.Project = project;
            return View("Index", viewModel);
        }

        return View();
    }

However this still did not refresh the ProjectID, and so I have decided to abandon this for the time being and try to come up with a better design.  However if you could see soemthign wrong that I am doing please comment on this.

This is my final Create View :-

@model MvcCommons.ViewModels.ProjectModel
@{
var projectID = Model.Project.ProjectID;

}

@{
    ViewBag.Title = "Create";
}

Create

@{
Layout = "~/Views/Shared/_Layout.cshtml";
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();

}

`

`
    $(document).ready(function () {

    var imageList = $('#imageList'),
        submitButt = $('#submitButt');

    //hide the imageList initially
    imageList.hide(); //hide all but the first paragraph

    });

    var Project = {
        save: function () {
            var projectForm = $("#projectForm");
            if (projectForm.valid()) {
                projectForm.submit();
            }
            else {
                Project.onInvalidForm();
            }
        },
        onInvalidForm: function () {
            //CODE FOR INVALID FORM
        },
        onSaveBegin: function () {
            //CODE FOR SAVE BEGIN
            alert('onSaveBegin ' + @(projectID));
            $('#imageList').fadeIn('slow');
        },
        onSaveSuccess: function () {
            //CODE FOR SAVE SUCCESS
            //alert('onSaveSuccess')
        },
        onSaveFailure: function () {
            //CODE FOR SAVE FAILURE
            //alert('onSaveFailure ' + @(projectID));
        },
        onSaveComplete: function () {
            //CODE FOR SAVE COMPLETE
            //alert('onSaveComplete ' + @(projectID))
            //$("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/"+@(projectID)); });
            $("#imageList").click(function () { $("#imageList").load("/File/ImageUpload/" + hfProjectId); });
        }
    };

@using (Ajax.BeginForm(
"/Create",
new { },
new AjaxOptions
{
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "projectFormContainer",
    OnComplete = "Project.onSaveComplete",
    OnFailure = "Project.onSaveFailure",
    OnSuccess = "Project.onSaveSuccess",
    OnBegin = "Project.onSaveBegin"
},
new { id = "projectForm", name = "projectForm" }))
{
    <div>

        @*@Html.Hidden("hfProjectId", projectID)*@
        @Html.Hidden("hfProjectId", Model.Project.ProjectID)

        <div class="editor-label">
            @Html.LabelFor(m => m.Project.ProjectTitle)
         </div>
         <div class="editor-field">
            @Html.TextBoxFor(m => m.Project.ProjectTitle)
            @Html.ValidationMessageFor(m => m.Project.ProjectTitle)
         </div>
         <div class="editor-label">
            @Html.LabelFor(m => m.Project.ProjectText)
         </div>
         <div class="editor-field">
            @Html.TextBoxFor(m => m.Project.ProjectText)
            @Html.ValidationMessageFor(m => m.Project.ProjectText)
         </div>
         <p>

@*               *@

    }

<div id='imageList'>
    <h2>Upload Image(s)</h2>
    @{
        //Html.RenderPartial("~/Views/File/ImageUpload.cshtml", new MvcCommons.ViewModels.ImageModel((int)ViewBag.ProjectID));
        Html.RenderPartial("~/Views/File/ImageUpload.cshtml", new MvcCommons.ViewModels.ImageModel(projectID));
     }
</div>

    @Html.ActionLink("Back to List", "Index")


Datagridview not showing up in webpage

I'm using MS Visual Studio 2010 (ASP.NET - C#) and MS SQL Server 2005, and I'm trying to retrieve all the records in my table tblEmployee from my database EMPLOYEES. There's no error when I debug my program in Visual Studio but when the localhost webpage opens, the datagridview dgvEmployee is not there. There are no retrieved records as well. Here's my code:

SqlConnection sConn;
SqlDataAdapter daEmp;
DataSet dsEmp;

const string sStr = "Server = Server-PC\\SQLEXPRESS; Database = EMPLOYEES; Integrated Security = SSPI";

protected void Page_Load(object sender, EventArgs e)
{
    sConn = new SqlConnection(sStr);
    daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
    dsEmp = new DataSet();

    daEmp.Fill(dsEmp, "tblEmployee");

    dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };

    dgvEmployee.DataSource = dsEmp.Tables["tblEmployee"];
}

This is the code in my Defaultpage.aspx:

<asp:GridView ID="dgvEmployee" runat="server">
</asp:GridView>

The database and table name is correct, the table have records, and I'm running both programs as Admin. I just can't figure out what's wrong... Is this regarding with the permissions?


dnn linqtosql Object reference not set to an instance of an object exception

I have such a code that tries to save some informations to database but my datacontext cannot be created. And it gives such an exception "Object reference not set to an instance of an object."     When i debugged,  it jumps form "DataContext1 db = new DataContext1();" line to catch block and gives that exception. Is there any solution to this?

public class AuthorPaperDetails
{
    public void SaveAuthorPaperDetails(string pTitle, string confMakerId,
                                                string additionalPaperTitle,string mainAuthor,
                                                int regFeeForFirstAuthor,int regFeeForAdditionalPaper, int RegFeeForCoAuthors)
    {

        try
        {
            DataContext1 db = new DataContext1();
            AuthorPaperDetail authorPaperDetail = new AuthorPaperDetail();

            authorPaperDetail.paper_title = pTitle;
            authorPaperDetail.conference_maker_id = confMakerId;
            authorPaperDetail.additional_paper_title = additionalPaperTitle;
            authorPaperDetail.areYouMainAuthor = mainAuthor;
            authorPaperDetail.feeForFirstAuthorPaper = regFeeForFirstAuthor;
            authorPaperDetail.feeForAdditionalPaper = regFeeForAdditionalPaper;
            authorPaperDetail.feeForParticipCoAuthors = RegFeeForCoAuthors;

            db.AuthorPaperDetails.InsertOnSubmit(authorPaperDetail);
            db.SubmitChanges();
        }
        catch (Exception)
        {
        }
    }
}


Cannot assign a value on a integer in bash Linux

I asked A few days ago about an error in a bash script. In the meantime I had rebuilded the code and now I still have 1 problem. I want to assign the value of "waarde to "vorigewaarde" in the if loop that looks how much your score is. while I tried to find the problem with bash -x (filename),it says that the value of "vorigewaarde" empty is, but I don't see how that can happen.

The code (I have marked the line where the fault is, it is after the until code line)

#!/bin/bash
score=0
uitkomst=juist
waardegok=0

Number=$(($RANDOM % 52))

KAARTEN=(Harten1 Harten2 Harten3 Harten4 Harten5 Harten6 Harten7 Harten8
Harten9 Harten10 Harten11 Harten12 Harten13 Klaver1 Klaver2 Klaver3
Klaver4 Klaver5 Klaver6 Klaver7 Klaver8 Klaver9 Klaver10 Klaver11 Klaver12
Klaver13 Schop1 Schop2 Schop3 Schop4 Schop5 Schop6 Schop7 Schop8 Schop9
Schop10 Schop11 Schop12 Schop13 Ruit1 Ruit2 Ruit3 Ruit4 Ruit5 Ruit6 Ruit7
Ruit8 Ruit9 Ruit10 Ruit11 Ruit12 Ruit13)

Gokkaart=${KAARTEN[$Number]}
echo " "
if (( "$Number" >= 0 )) && (( "$Number" <= 12 ));then
  case $Gokkaart in
  Harten1) waarde=1;;
  Harten2) waarde=2;;
  Harten3) waarde=3;;
  Harten4) waarde=4;;
  Harten5) waarde=5;;
  Harten6) waarde=6;;
  Harten7) waarde=7;;
  Harten8) waarde=8;;
  Harten9) waarde=9;;
  Harten10) waarde=10;;
  Harten11) waarde=11;;
  Harten12) waarde=12;;
  Harten13) waarde=13;;
esac

elif (( "$Number" >= 13 )) && (( "$Number" <= 25 ));then
case $Gokkaart in
  ##same for Harten only now for Klaveren
esac

elif (( "$Number" >= 26 )) && (( "$Number" <= 38 ));then
case $Gokkaart in
  ##same for Klaveren only now for Schoppen
esac

elif (( "$Number" >= 39 )) && (( "$Number" <= 52 ));then
case $Gokkaart in
  ##Same for Schoppen only now for Ruiten
esac
fi
echo "De eerste kaart is een $Gokkaart"
echo " "
echo "$waarde"
until [ $uitkomst != juist ]
do
  echo " "
  echo -n "hoger of lager? type [H of L] > "
  read gok
  echo "gok: $gok"

  if [ "$gok" = "H" ];then

    echo "Uw gok is hoger"
    waardegok=14

  elif [ "$gok" = "L" ];then
    echo "Uw gok is lager"
    waardegok=0
  fi

  if (( "$score" >= 1 ));then

    vorigekaart=$Gokkaart2
    vorigewaarde=$waarde2
    echo "De vorige kaart was een $Gokkaart2"
    echo " "
  elif (( "$score" == 0 ));then **#Here is the error**

    vorigekaart=$Gokkaart
    vorigewaarde=$waarde
    echo "Laten we beginnen"
    echo " "
  fi

  Number2=$(($RANDOM % 52))

  KAARTEN2=(#same that of array as KAARTEN but now for KAARTEN2 and Gokkaart2)

  Gokkaart2=${KAARTEN2[$Number2]}

  if (( "$Number2"=="$Number" ));then

    Number2=$(($RANDOM % 52))
    Gokkaart2=${KAARTEN2[$Number2]}

  elif (( "$Number2" >= 0 )) && (( "$Number2" <= 12 ));then

    echo "De volgende kaart is een harten, namelijk $Gokkaart2"
    case $Gokkaart2 in
    Harten1) waarde2=1;;
    Harten2) waarde2=2;;
    Harten3) waarde2=3;;
    Harten4) waarde2=4;;
    Harten5) waarde2=5;;
    Harten6) waarde2=6;;
    Harten7) waarde2=7;;
    Harten8) waarde2=8;;
    Harten9) waarde2=9;;
    Harten10) waarde2=10;;
    Harten11) waarde2=11;;
    Harten12) waarde2=12;;
    Harten13) waarde2=13;;
    esac

  if (( "$waardegok" > "$waarde2" )) && (( "$waarde2" > "$vorigewaarde" ));then

    echo "$Gokkaart2"
    echo "Goed gegokt!"
    score=$((score+1))
    echo "Uw score is nu : "$score""
    echo " "

  elif (( "$waardegok" < "$waarde2" )) && (( "$waarde2" < "$vorigewaarde" ));then

    echo "$Gokkaart2"
    echo "Goed gegokt!"
    score=$((score+1))
    echo "Uw score is nu : "$score""
    echo " "

  else
    echo "Fout, maar goed geprobeert!"
    uitkomst=false
  fi

##this is also the same way for number higher than 12 all the way to 52
done
echo " uw score was $score"

I have also edited the code a bit more, now I check everything at the end but it still gives the same error.

elif (( "$Number2" >= 39 )) && (( "$Number2" <= 52 ));then
case $Gokkaart2 in
##same as harten but now for Ruiten
esac
controlewaarde=$waarde2

fi

echo " "
echo -n "hoger of lager? type [H of L] > "
read -r gok
echo "gok: $gok"

if (( "$score" >= 1 ));then

  vorigewaarde=$waarde2

  echo "De vorige kaart was een $Gokkaart2"
  echo " "
elif (( "$score" == 0 ));then

  vorigewaarde=$waarde
  echo "Laten we beginnen"
  echo "De eerste kaart is een $Gokkaart"
  echo " "
fi

if [ "$gok" = "H" ];then

  echo "Uw gok is hoger"
  waardegok=14

elif [ "$gok" = "L" ];then
  echo "Uw gok is lager"
  waardegok=0
fi

if (( "$Number2" >= 0 )) && (( "$Number2" <= 12 ));then

  echo "De volgende kaart is een harten, namelijk $Gokkaart2"

elif (( "$Number2" >= 13 )) && (( "$Number2" <= 25 ));then
  echo "De volgende kaart is een klaver, namelijk $Gokkaart2"

elif (( "$Number2" >= 26 )) &&  (( "$Number2" <= 38 ));then
  echo "De volgende kaart is een Schoppen, namelijk $Gokkaart2"

elif (( "$Number2" >= 39 )) && (( "$Number2" <= 52 ));then
  echo "De volgende kaart is een Ruiten, namelijk $Gokkaart2"
fi

if (( "$waardegok" > "$waarde2" )) && (( "$controlewaarde" > "$vorigewaarde" ));then

  echo "$Gokkaart2"
  echo "Goed gegokt!"
  score=$((score+1))
  echo "Uw score is nu : $score"
  echo " "

elif (( "$waardegok" < "$waarde2" )) && (( "$controlewaarde" < "$vorigewaarde"   ));then

  echo "$Gokkaart2"
  echo "Goed gegokt!"
  score=$((score+1))
  echo "Uw score is nu : $score"
  echo " "

else
  echo "Fout, maar goed geprobeert!"
  uitkomst=false
  fi
done
echo " uw score was $score"


C# Package Relationship Id

I'm experimenting with the System.IO.Packaging namespace to store some custom files and then read them out later back into code.

I'm having difficulty finding a definitive example on how to use/set the ID property of a PackagePartRelationship.

For example if I have the following:

var relationship = packagePart.CreateRelationship(documentPart.Uri, TargetMode.Internal, relationshipType, relationshipId);

What format should the parameter 'relationshipId' have? All that is stated in the MSDN documentation is that it should adhere to the rules for a valid xsd:Id value from the XML scheme datatype definitions. But searching through that, I can't find a set answer either.

Also, in case anyone asks, the reason I want to specify the Id rather than letting it be auto generated is because the will be some relationship chains in the package that only have on "child" or "relationship" associated with it. So rather than looping over

packagePart.GetRelationships()

Or

packagePart.GetRelationshipByType(relationshipType)

I want to be able to do

packagePart.GetRelationship(relationshipId)

Many thanks.


wsdl2java Error: Emitter failure. Invalid endpoint address in port

I am trying to run the wsdl2java command on a WSDL file that was given to me from another group in my company.  I know wsdl2java works because I can run the examples but when I try it on the wsdl given to me it fails.  The one big difference is that the WSDL given to me uses SSL.

I’m using Java 1.4 (checked it a few time) and made sure all the correct jars are in my class path, jsse.jar is there.

COMMAND: java org.apache.axis.wsdl.WSDL2Java --server-side GenericWebService.wsdl

ERROR:

log4j:WARN No appenders could be found for logger (org.apache.axis.i18n.ProjectResourceBundle).
log4j:WARN Please initialize the log4j system properly.
**java.io.IOException: Emitter failure.  Invalid endpoint address in port AC_x0020_Generic_x0020_Web_0020_ServiceSoap in service AC_x0020_Generic_x0020_Web_x0020_ServiceLocator: **
        at org.apache.axis.wsdl.toJava.JavaServiceImplWriter.writeFileBody(JavaServiceImplWriter.ja
a:242)
        at org.apache.axis.wsdl.toJava.JavaWriter.generate(JavaWriter.java:127)
        at org.apache.axis.wsdl.toJava.JavaServiceWriter.generate(JavaServiceWriter.java:112)
        at org.apache.axis.wsdl.toJava.JavaGeneratorFactory$Writers.generate(JavaGeneratorFactory.j
va:421)
        at org.apache.axis.wsdl.gen.Parser.generate(Parser.java:476)
        at org.apache.axis.wsdl.gen.Parser.access$000(Parser.java:45)
        at org.apache.axis.wsdl.gen.Parser$WSDLRunnable.run(Parser.java:362)
        at java.lang.Thread.run(Thread.java:534)

asdf

<wsdl:portType name="AC_x0020_Generic_x0020_Web_x0020_ServiceSoap">
  <wsdl:operation name="Provision">
    <wsdl:input message="tns:ProvisionSoapIn" />
    <wsdl:output message="tns:ProvisionSoapOut" />
  </wsdl:operation>
</wsdl:portType>

<wsdl:binding name="AC_x0020_Generic_x0020_Web_x0020_ServiceSoap" type="tns:AC_x0020_Generic_x0020_Web_x0020_ServiceSoap">
  <soap:binding transport="http://schemas.xmlsoap.org/soap/http" />
  <wsdl:operation name="Provision">
    <soap:operation soapAction="http://xmlns.fmr.com/systems/dev/aar/2008/05/GenericWebService/Provision" style="document" />
    <wsdl:input>
      <soap:body use="literal" />
      <soap:header message="tns:ProvisionServiceProcessingDirectives" part="ServiceProcessingDirectives" use="literal" />
      <soap:header message="tns:ProvisionServiceCallContext" part="ServiceCallContext" use="literal" />
    </wsdl:input>
    <wsdl:output>
      <soap:body use="literal" />
    </wsdl:output>
  </wsdl:operation>
</wsdl:binding>

<wsdl:service name="AC_x0020_Generic_x0020_Web_x0020_Service">
  <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">Generic web service definition for provisioning requests callable by AccessCENTRAL</wsdl:documentation>
  <wsdl:port name="AC_x0020_Generic_x0020_Web_x0020_ServiceSoap" binding="tns:AC_x0020_Generic_x0020_Web_x0020_ServiceSoap">
    <soap:address location="" />
  </wsdl:port>
</wsdl:service>

UPDATED SOLUTION:
The problem was that the parser needed a value in the <soap:address location="" /> for it to complete.  I added the URL of my service and it worked.

New Lines looked like:

<soap:address location="" http://localhost:8080/axis/services/AC_x0020_Generic_x0020_Web_x0020_Service" />


how to make a UIImageView rotate around its center

im making an ios app in xcode 4 and I need a square UIImageView to rotate around its center to the number of degrees I give it.

does anyone know how to do this??

thanks


Create Sitecore cshtml Rendering for Inserting JavaScript

I need to create a cshtml rendering and Sitecore control that allows me to insert JavaScript from a Sitecore field. I can then attach this control to the layout to insert the JavaScript on the page.

I tried inserting <script> into a control that uses a rich text editor, but Sitecore strips out <script> from the editor by default, which led me to this solution.

I know the basics--there needs to be the cshtml rendering, a template (assuming one field only, a multiline text field), and a layout rendering with the path to the cshtml file, but not much more than that.

The developers have used Glass Mapper, I don't know how that plays into the above, or how to re-instance this. This will be my first control. Here's a sample cshtml file if it helps:

@inherits Glass.Mapper.Sc.Web.Mvc.GlassView<Company.Model.TDS.sitecore.templates.User_Defined.Company.Platform.Modules.Common.Sidebar_Text_Callout>

    @if (Model != null)
    {
        <div class="sidebar-text-callout">
            <h3>@Editable(Model, x => x.Sidebar_Callout_Title)</h3>
            <p>@Editable(Model, x => x.Sidebar_Callout_Copy)</p>
            @if (Model.Sidebar_Callout_Link != null)
            {
                <div class="all-caps-callout">
                    <a class="link-with-icon" href="@Model.Sidebar_Callout_Link.Url" target="@Model.Sidebar_Callout_Link.Target">@Model.Sidebar_Callout_Link.Text <span class="svg">@Html.Partial("~/Views/Icons/arrowRight.cshtml")</span></a>
                </div>
            }
        </div>
    }


opengl color conversion / or SDI signal conversion?

I draw in opengl with RGBA colors these texts (with the color between parenthesis) :
RED-alpha50 (255,0,0,50) RED-alpha128 (255,0,0,128) RED-alpha255 (255,0,0,255)
GREEN-alpha50 (0,255,0,50) GREEN-alpha128 (0,255,0,128) GREEN-alpha255 (0,255,0,255)
BLUE-alpha50 (0,0,255,50) BLUE-alpha128 (0,0,255,128) BLUE-alpha255 (0,0,255,255)

I memcpy in the buffer (getByte) of a frame created with the format bmdFormat8BitBGRA
at the size of 1280 pixels by 720 pixels,
and then send it to the SDI output of a video capture card.

Here are links to screenshot of what we see on the TV set :
Channel A (should be the fill : so we expect RGB values)
Heberger image http://img11.hostingpics.net/thumbs/mini_444718SDIChA.jpg

Channel B (should be the key : so we expect grey-scale values)

Heberger image http://img11.hostingpics.net/thumbs/mini_449411SDIChB.jpg

I am not sure which color conversion I should try.

=> Can someone give me hint or working tracks for why the background which should be black is a "half" green (I reckon it to be green with 50% alpha : 0,255,0,128 or else in YUV) ?

=> Is it a question of unsigned byte vs byte : why do I obtain black with (255,0,0,128) and red with (255,0,0,255) : why is the red range reached with alpha between 128 and 255 ?
(but green gets whiter at (0,255,0,255) and blue is a little greenish at (0,0,255,128)).

=> is it a question of converting SDI to HDMI or a HDCP issue ?

Thanks to all for any help,
I am a bit dazzled, and quite new to color conversion,
any help will be so great,
cheers,


Does javascript on iOS have to be downloaded *by* the WebKit framework in addition to executing within its framework?

The agreement says this:

3.3.2 An Internal Use Application may not download or install executable code. Interpreted code may only be used in an Application if all scripts, code and interpreters are packaged in the Application and not downloaded. The only exception to the foregoing is scripts and code downloaded and run by Apple's built-in WebKit framework.

It particular it says ".. code downloaded .. by Webkit framework".

Does anybody know if for a native app using UIWebView this means Javascript has to be downloaded automatically by Webkit i.e. as a consequence of the user clicking on an external url link. Or if it would be acceptable for the scripts to be downloaded by creating my own HTTP connection to a server and downloading them myself - but they would be executed within Webkit (via UIWebView) ?

I presume this restriction is for security purposes, so does the security come from limiting the execution to within WebKit, as opposed to where the scripts are downloaded from?

I realize its unlikely anybody can definitively answer this except Apple, but speculate answers are very welcome.

Thanks


ColdFusion Object to String

I'm really new to ColdFusion and am trying to pull data out of the database and send it to an email function I have created.

myQry = new Query();
myQry.setSQL("select * from stocknotifications LEFT JOIN options ON stocknotifications.stocknotification_id = options.option_id  ORDER BY stocknotification_id DESC LIMIT 1 "); //set query

qryRes = myQry.execute();

writedump(qryRes.getResult(), false);

Mail = variables.NotificationService.newMail();
Mail.setTo("bfrench@destinationcms.co.uk");
Mail.setSubject( "New Stock Request" );

// render body with layout which uses the rc.emailView
Mail.setBody(ToString(qryRes.getResult()));
variables.NotificationService.sendMail( Mail );

My writeDump() works and shows the last item in table. The only problem is I can't pass it into setBody() without it throwing an error.

Can't cast Complex Object Type Query to String
  Use Built-In-Function "serialize(Query):String" to create a String from Query

Any ideas?


Write a list of Complex Numbers as Binary Data

I'm trying to output some data from a python script to a binary file.

If I have a list of floats I've been using this

out_file = open("filename", "wb")
float_array.array("f", [])
float_array.fromlist(mylist)
float_array.tofile(out_file)
out_file.close()

This seems to work fine, at least it's resulting in a file with the correct number of bytes.

How can I do the same thing but using a list of complex numbers?

Thanks


Rails 3 wicked_pdf and pagination

Is there any simple solution for custom paginating pdf? I was thinking about some javascript which will check the div height and paginate when next element will overflow the aggregating div - is there something like this implemented already?


32bit or 64bit Android SDK on Windows 64bit OS?

Installing a dev machine for Android development. 64bit Win7, soon will upgrade to Win8, 16GB RAM. Now the selection at the android download:

64bit or 32bit Android SDK?

What should Duffman do? Seems most poeple here go for the 64bit version, but are there arguments for/against? Hasslefree installation?

EDIT

This question was posted because I wanted to setup JetBrains IntelliJ together with the SDK. Reason was that I did not like Eclipse in the past. So when I reached the 32/64 question while downloading I was not sure and did research. The result was that there were many troubles dependent on the 32/64bit-version. In the end I gave the current Eclipse/ADT version a try and got it running quickly. I got great support from a Jetbrains guy, but finally did not follow that route, since the Eclipse toolset just worked.

EDIT 29.7.2013

64bit Version Eclipse works just fine


best way to refractor this code?

package com.example.moviesearch;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class ParseJSON {
    private ArrayList<Movie> movies;
    private String genres;
    private String rated;
    private String language;
    private int rating;
    private String country;
    private String release_date;
    private String title;
    private String directors;
    private String actors;
    private String plot_simple;
    private String poster;
    private String runtime;
    private String imdb_url;

    public ArrayList<Movie> parseJson(String json) {
        movies = new ArrayList<Movie>();
        try {
            JSONArray jArray = new JSONArray(json);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject j = jArray.getJSONObject(i);
                try {
                    genres = j.getString("genres").replace("[", "")
                            .replace("]", "").replaceAll("\"", "");
                } catch (Exception e) {
                    genres = "notfound";
                }
                try {
                    rated = j.getString("rated");
                } catch (Exception e) {
                    rated = "not found";
                }
                try {
                    language = j.getString("language").replace("[", "")
                            .replace("]", "").replaceAll("\"", "");
                } catch (Exception e) {
                    language = "notfound";
                }

                try {
                    rating = j.getInt("rating");
                } catch (Exception e) {
                    rating = 404;
                }

                try {
                    country = j.getString("country").replace("[", "")
                            .replace("]", "").replaceAll("\"", "");
                } catch (Exception e) {
                    country = "not found";
                }
                try {
                    release_date = j.getString("release_date");
                } catch (Exception e) {
                    release_date = "notfound";
                }
                try {
                    title = j.getString("title").replace("\n", "");
                } catch (Exception e) {
                    title = "notfound";
                }
                try {
                    directors = j.getString("directors").replace("[", "")
                            .replace("]", "").replaceAll("\"", "");
                } catch (Exception e) {
                    directors = "notfound";
                }
                try {
                    actors = j.getString("actors").replace("[", "")
                            .replace("]", "").replaceAll("\"", "");
                } catch (Exception e) {
                    actors = "notfound";
                }
                try {
                    plot_simple = j.getString("plot_simple");
                } catch (Exception e) {
                    poster = "notfound";
                }
                try {
                    JSONObject c = j.getJSONObject("poster");
                    poster = c.getString("cover");
                } catch (Exception e) {
                    poster = "notfound";
                }
                try {
                    runtime = j.getString("runtime").replace("[", "")
                            .replace("]", "").replaceAll("\"", "");
                } catch (Exception e) {
                    runtime = "notfound";
                }
                try {
                    imdb_url = j.getString("imdb_url");
                } catch (Exception e) {
                    imdb_url = "notfound";
                }
                Movie movie = new Movie(genres, rated, language, rating,
                        country, release_date, title, directors, actors,
                        plot_simple, poster, runtime, imdb_url);
                movies.add(movie);
            }

        } catch (JSONException e) {
            Log.e("jsonerror", "", e);
        }
        return movies;
    }
}

I am making an android app and needing to parse json data. I turn this json data into a custom Class. Sometimes the json I parse doesn't exist so I have to put in a default value for it, I feel this is too brute.


Language Hierarchy in Java

public class BLLanguageProvider extends LanguageProvider {
    @Override
    public LanguageEmbedding<?> findLanguageEmbedding(Token<?> token, LanguagePath lp, InputAttributes ia) {
        return null;
    }

    @Override
    public Language<?> findLanguage(String mimeType) {
        if("text/x-bl".equals(mimeType)){
            return new BLLanguageHierarchy().language();
        }

        return null;
    }
}

I'm having a problem with my code.
I already imported LanguageHierarchy but it's returning "cannot find symbol"

I'm following a tutorial at the following link:
http://wiki.netbeans.org/SyntaxColoringANTLR#Using_an_ANTLR_Lexer_For_Syntax_Coloring_Tutorial

I'm at the part of making the C Minus language provider which I replaced with BL.


Call function from React Component from function

I have a React Component

export function sendAlert(msg) {
    showAlert() //How to call in normal function a function from React.Component
}

export class Alert extends React.Component {

  showAlert = () => {
     alert("a")
  };

  render() {
     return (
      <div>
        <h1>Component</h1>
      </div>
    )
  }
}

Its possible to call function which call a function from React.Component


Dimension-independent loop over boost::multi_array?

Say I've got an N-dimensional boost::multi_array (of type int for simplicity), where N is known at compile time but can vary (i.e. is a non-type template parameter). Let's assume that all dimensions have equal size m.

typedef boost::multi_array<int, N> tDataArray;
boost::array<tDataArray::index, N> shape;
shape.fill(m);
tDataArray A(shape);

Now I would like to loop over all entries in A, e.g. to print them. If N was 2 for example I think I would write something like this

  boost::array<tDataArray::index, 2> index;
  for ( int i = 0; i < m; i++ )
  {
    for ( int j = 0; j < m; j++ )
    {
      index = {{ i, j }};
      cout << A ( index ) << endl;
    }
  }

I've used an index object to access the elements as I think this is more flexible than the []-operator here.

But how could I write this without knowing the number of dimensions N. Is there any built-in way? The documentation of multi_array is not very clear on which types of iterators exist, etc.
Or would I have to resort to some custom method with custom pointers, computing indices from the pointers, etc.? If so - any suggestions how such an algorithm could look like?


Get element being sorted within helper function

i'm using jQuery UI and would like to modify the helper So I do this:

$("#container").sortable({
    helper: function(event, ui) {
        var newHelper = ; // new helper HTML
        return newHelper;
    }
});

My question is: How can I get the element being sorted within the helper function? I want to get the height of the sorted element but can't get the element to begin with. I have tried the following with no luck:

ui.item;
ui.element;
ui.helper;


How am I supposed to get the Container instance for my app

I can get access to this variable using the private instance variable App.__container__, but this is obviously bad practice.


How topojson's world map scale has set?

in world-110m.json

there is a scale value.
[0.0036000360003600037, 0.0017364686646866468]

and I got this values are computed from [360/99990, 173.64513/99999]

ok, 360 from latitude, 173.64 from longitude, just for including northernmost lang point.

but where does that denominators (99990 and 99999) came from?


JS events source detection

I'm working on a part of my web site where people can vote on publications, I have many in the same page, and next every publication there are two images one to agree and the other to disagree. I want to change the images, so when someone votes, whether agree or not, the image changes to say he already voted.
Here's my code:

JPS:

<logic:iterate id="comment" name="Liste_Comments" scope="request">
<html:img  src="pages/images/ok.png" alt="Vote pour!" paramId="code" paramName="comment"   paramProperty="code" onclick="voterComment('pour');"/>

<html:img  src="pages/images/ko.png" alt="Vote contre!" paramId="code" paramName="comment"  paramProperty="code" onclick="voterComment('contre');"/>

       <bean:write name="comment" property="libelle" />
       <bean:write name="comment" property="subject" />
       <br>
</logic:iterate>

Script:

<script type="text/javascript">
            function voterComment(vote) {
                var url = "<%=request.getContextPath()%>/VoteComment.do";
                new Ajax.Request(url, {
                    parameters: {vote: vote},
                    onSuccess: function(transport, json) {
                        if (json.error) {
                            alert(json.error);
                        }
                        else{
                            window.event.srcElement.src = "pages/images/photo.jpg";
                        }
                    }
                });
            }
   </script>

I have a problem to access to the image that was clicked!!

Thanks guys, in advance, for your great helping :)


Quick algorithm of comparing sums of two arrays?

Suppose I have 2 integer arrays, they could be not in same length and value on any index is a valid integer (min ~ max). such as:

int data1[] = {1227210749, 382745290, 567552295, 1910060611,
           577735884, 75518037, 742485551, 1202127013,
           386030509, 308032134};

int data2[] = {1729472635, 1258098863, 259427472, 1664987257,
           994376913, 1581883691, 1728724734, 2034013490};

How could I quickly compare of them to know which one have a bigger sum?

int compare(int a[], int len_a, int b[], int len_b)
{
    // compares if the sum of data1 is bigger than sum of data2
}


Erlang Web framework and SSL?

Can anyone either 1) tell me how to do it, or 2) point me to a resource on how to run/enable/use SSL with the Erlang Web framework?  I can't find anything in any docs or online web searches, and it looks like the last post to their mailing list is a couple of years old.

Thanks.


Find optimum value based on multiple constraints algorithm

I have the following vectors (or C matrix and V vector) and K1, K2, K3 constants

Constraints      [c11 + c12 + c13 + ... + c1n] <= K1
                 [c21 + c22 + c23 + ... + c2n] <= K2
                 [c31 + c32 + c33 + ... + c3n] <= K3
-------------------------------------------------
Values           [ v1 +  v2 +  v3 + ... +  vn] -> Max

As an input I am getting values of C and V, and as an output I want to provide the X vector which contains only 0 and 1 values and gives me

          [c11 * x1 + c12 * x2 + c13 * x3 + ... + c1n * xn <= K1
          [c21 * x1 + c22 * x2 + c23 * x3 + ... + c2n * xn <= K2
          [c31 * x1 + c32 * x2 + c33 * x3 + ... + c3n * xn <= K3
          ------------------------------------------------------
          [ v1 * x1 +  v2 * x2 +  v3 * x3 + ... + vn *  xn] -> Max

As an over simplified example:

Input:

          K1 = 15
          K2 = 20
          K3 = 10

          c1 = [3, 6, 8]    | sum(c1 * X) <= 15
          c2 = [8, 9, 3]    | sum(c2 * X) <= 20
          c3 = [7, 5, 2]    | sum(c3 * x) <= 10
           v = [2, 5, 3]    | sum( v * X) -> Max

Output providing X vector which is maximizing the value within the constrains:

           X = [0, 1, 1]

I am looking for an elegant algorithm (may be a Java or C# implementation as well) giving me the output based on the input. We can assume that the number of constraints is always 3 and all values of C and V (and K1, K2, K3) are provided.

Another simple example could be: You have a room (3D), so your constraints are the width, height and length of the room (K1, K2, K3) and you have a list of furniture items (n items). All i furniture item has it's own lenght (c1i), width (c2i) and height (c3i) and value (vi). You want to pack the room with the most valuable furniture items which fits inside the rooms dimensions. So the output is an n-long X variable which contains only 0 and 1 values, if xi = 1, the i-th element gets picked to be in the room, if xi = 0 the ith element won't be picked to be in the room.


How to pass multidimensional values to a json array?

I am trying to pass the value to an api through json request.

  $payload = json_encode( array("phones"=> "971xxxxxxx",
"emails"=> "fadfad@xyz.com",
"id"=> "1"
  ) );

How will i pass the below multi dimensional values to a json request like the above code?

 { "contactList": [ { "phones" : ["+91 9000000034"], "emails" : [fadfad@xyz.com], "id" : 1 }, { "phones" : ["+91 903-310-00-001"], "emails" : [krs@xyz.in], "id" : 2 } ] }


How to add support for 10.5 inch iPad Pro

I've just downloaded the latest Xcode 8.3.3 update from the MAS. I was wondering how to add support for the new 10.5-inch iPad Pro?

I'm using storyboards with auto-layout, a launch screen storyboard and all app icon sizes are added to the xcassets.


Are objects in PHP passed by value or reference?

In this code:

<?php
class Foo
{
    var $value;

    function foo($value)
    {
        $this->setValue($value);
    }

    function setValue($value)
    {
        $this->value=$value;
    }
}

class Bar
{
    var $foos=array();

    function Bar()
    {
        for ($x=1; $x<=10; $x++)
        {
            $this->foos[$x]=new Foo("Foo # $x");
        }
    }

    function getFoo($index)
    {
        return $this->foos[$index];
    }

    function test()
    {
        $testFoo=$this->getFoo(5);
        $testFoo->setValue("My value has now changed");
    }
}
?>

When the method Bar::test() is run and it changes the value of foo # 5 in the array of foo objects, will the actual foo # 5 in the array be affected, or will the $testFoo variable be only a local variable which would cease to exist at the end of the function?


jQuery works in jsfiddle, but not in html file?

I checked many times, but I have no idea why the jQuery wont work. It works in jsfiddle!

html:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Josue Espinosa</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="animate.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
</head>
<body>
<div id="menu">

</div>
</body>
</html>

css:

#menu{
    width:15px;
    height:200px;
    background:red;
}

jquery:

$('#menu').hover(function(){
     $("#menu").stop().animate({width : "300px"});
});


How can I disable swift-Mixpanel on development?

On appDelegate, I used to write like this on obj-c, but in swift, it will crash on development when the app call Mixpanel.mainInstance().track(event: "")

What is a good way not to send mixpanel data on development mode?

#if DEBUG
#else
    Mixpanel.initialize(token: Key.Mixpanel.token)
#endif


how to send data to controller ruby by ajax

In application.js :

function get_cell_id(select_id)
{
  $.ajax({
      url: "/assign_variable",

      type: "GET",
       data:{channel:"abc"},
      error: function(){
      alert('fail')
      }
  });
}

in static_pages_controller

def assign_variable
  @Four_Season_Set_Channel= params[:channel]
  end

in routes.rb

 match '/assign_variable', to:'static_pages#assign_variable', via: 'Get'

but i got alert fail, please help me fix it.


Autcomplete - custom renderItem/Menu and item selection issue

I am using jQueryUI (1.10.2) and jQuery (1.9.1) with the autocomplete tool.

I have remote json data AND categories AND custom display with an image for each item from the json data (showed in the autocomplete list).

This is my autocomplete init

var autoSearch = $("#header-search-text").autocomplete({
    source: function( request, response ) {
        $.ajax({
            //I have items with label, value, category and imgPath info
        });
    },
     focus: function( event, ui ) {
        console.log("focus is ");
        //This line shows "null"
        console.log(ui);
        return false;
    },
    minLength: 4,
    select: function( event, ui ) {
        //Never shows up
        console.log("selected is ");
        console.log( ui.item);/* ?
        "Selected: " + ui.item.label :
        "Nothing selected, input was " + this.value);*/
    },
    open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
    },
    close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
    }
}).data('ui-autocomplete');

I have a custom _renderMenu

//Working
autoSearch._renderMenu = function( ul, items ) {
        var that = this,
        currentCategory = "";
        $.each( items, function( index, item ) {
            console.log(item);
            if ( item.category != currentCategory ) {
                ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                currentCategory = item.category;
            }
            that._renderItem( ul, item );
        });
};

But when I had the _renderItem, the keys (up and down) for selection doesn't work anymore and I cannot click on anything (no :hover CSS showing up)

autoSearch._renderItem = function(ul, item) {
    console.log("ul is ");
    console.log(ul);
    return $('<li>')
        .data('item.autocomplete', item)
        .append('<img style="width:50px;height:50px;" src="' + base_url + "/"+ item.imgPath + '" alt="" />' + item.label)
        .appendTo(ul);
};


Hotel prices spanning multiple dates issue

Question is somehow related to this one, with the exception that I use parameters.
I have this on my button click :

procedure TForm1.Button1Click(Sender: TObject);
begin
with ABSQuery1 do begin
ABSQuery1.Close;
ABSQuery1.SQL.Clear;
ABSQuery1.SQL.Add('select * from ROOM_RATES where CENIK_ID = :a4 and ROOM_TYPE = :A1');
ABSQuery1.SQL.Add('and rate_Start_DATE < :a3 AND rate_End_DATE  > :a2 ORDER BY rate_Start_DATE ASC ');
ABSQuery1.Params.ParamByName('a1').Value:= cxLookupComboBox2.Text;
ABSQuery1.Params.ParamByName('a2').Value:= cxDateEdit1.Date;
ABSQuery1.Params.ParamByName('a3').Value := cxDateEdit2.Date;
ABSQuery1.Params.ParamByName('a4').Value := cxLookupComboBox1.Text;
ABSQuery1.Open;
end;
end;

This kind of works but not what I want actually.Problem is related to this one:
Hotel Booking Rates SQL Problem

Problem is with the overlapping dates like in the mentioned hyperlink.Right now I am getting this :

How can I obtain result similar in the mentioned hyperlink with the above example ?

This is the snapshot of the db table :

Update (NEW):
This is the code on the button click :

procedure TForm1.AdvGlowButton1Click(Sender: TObject);
var
     nxt             : integer;
     mem_from         : TDateTime;
     mem_to           : TDateTime;
     mem_RATE_ID      : integer;
     mem_ROOM_TYPE    : string[10];
     mem_Start_DATE_1 : TDateTime;
     mem_End_DATE_1   : TDateTime;
     mem_RATE_Price_1 : Currency;
     mem_calc_END     : TDateTime;
     mem_calc_DAYS    : integer;
     c_from           : TDateTime;
     c_to             : TDateTime;
     c_from_test      : TDateTime;
     c_to_test        : TDateTime;

begin
ABSQuery2.Close;
ABSQuery2.SQL.Text:='DELETE from TEMP';
ABSQuery2.ExecSQL;
ABSQuery2.SQL.Text:='SELECT * from TEMP ORDER BY ID ';
ABSQuery2.Open;

c_from := cxDateEdit1.Date;
c_to   := cxDateEdit2.Date;

mem_from := cxDateEdit1.Date;
mem_to   := cxDateEdit2.Date;

with ABSQuery1 do begin
ABSQuery1.Close;
ABSQuery1.SQL.Clear;
ABSQuery1.SQL.Add('select * from ROOM_RATES where CENIK_ID = :a4 and ROOM_TYPE = :A1');
ABSQuery1.SQL.Add('and rate_Start_DATE < :a3 AND rate_End_DATE  > :a2 ORDER BY rate_Start_DATE ASC ');
ABSQuery1.Params.ParamByName('a1').Value:= cxLookupComboBox2.Text;
ABSQuery1.Params.ParamByName('a2').Value:= cxDateEdit1.Date;
ABSQuery1.Params.ParamByName('a3').Value := cxDateEdit2.Date;
ABSQuery1.Params.ParamByName('a4').Value := cxLookupComboBox1.Text;
ABSQuery1.Open;

     nxt              := 1;
     mem_RATE_ID      := ABSQuery1.FieldByName('RATE_ID').AsInteger;
     mem_ROOM_TYPE    := ABSQuery1.FieldByName('ROOM_TYPE').AsString ;
     mem_Start_DATE_1 := ABSQuery1.FieldByName('RATE_START_DATE').AsDateTime;
     mem_End_DATE_1   := ABSQuery1.FieldByName('RATE_END_DATE').AsDateTime;
     mem_RATE_Price_1 := ABSQuery1.FieldByName('RATE_PRICE').AsCurrency;

     if mem_to > mem_End_DATE_1 then begin
         mem_calc_END  := mem_End_DATE_1;
         mem_calc_DAYS := Daysbetween(mem_from,mem_End_DATE_1);
     end else begin
         mem_calc_END  := mem_to;
         mem_calc_DAYS := Daysbetween(mem_from,mem_calc_END);
     end;
end;

if ABSQuery1.RecordCount > nxt then ABSQuery1.Next;
with ABSQuery2 do begin
open;
Insert;
  ABSQuery2.FieldByName('RATE_ID').AsInteger:=mem_RATE_ID;
  ABSQuery2.FieldByName('ROOM_TYPE').AsString:=mem_ROOM_TYPE;
  ABSQuery2.FieldByName('DATE_FROM').AsDateTime:=mem_from;
  ABSQuery2.FieldByName('DATE_TO').AsDateTime:= mem_to;//mem_calc_END;
  ABSQuery2.FieldByName('RATE_PRICE').AsCurrency:=mem_RATE_PRICE_1;
  ABSQuery2.FieldByName('DAYS').AsInteger:=mem_calc_DAYS;
  ABSQuery2.FieldByName('TOTAL').AsCurrency:=mem_RATE_PRICE_1 * mem_calc_DAYS;
post;
end;  ///////////////////////////////////////////////////////////////////
if ABSQuery1.RecordCount > nxt then begin
     inc(nxt);

    if mem_to < ABSQuery1.FieldByName('rate_End_DATE').AsDateTime then begin
       mem_calc_END   := mem_to;
       mem_calc_DAYS  := Daysbetween(ABSQuery1.FieldByName('rate_Start_DATE').AsDateTime,mem_calc_END);
    end else begin
       mem_calc_END   := ABSQuery1.FieldByName('rate_End_DATE').AsDateTime;
       mem_calc_DAYS  := Daysbetween(ABSQuery1.FieldByName('rate_Start_DATE').AsDateTime, ABSQuery1.FieldByName('rate_End_DATE').AsDateTime);
    end;
       mem_RATE_ID      := ABSQuery1.FieldByName('RATE_ID').AsInteger;
       mem_ROOM_TYPE    := ABSQuery1.FieldByName('ROOM_TYPE').AsString;
       mem_Start_DATE_1 := ABSQuery1.FieldByName('rate_Start_DATE').AsDateTime;
       mem_End_DATE_1   := ABSQuery1.FieldByName('rate_End_DATE').AsDateTime;
       mem_Rate_Price_1 := ABSQuery1.FieldByName('RATE_PRICE').AsCurrency;

    // calculation : second row.
with ABSQuery2 do begin
Insert;
  FieldByName('RATE_ID').AsInteger:=mem_RATE_ID;
  FieldByName('ROOM_TYPE').AsString:=mem_ROOM_TYPE;
  FieldByName('DATE_FROM').AsDateTime:=mem_Start_DATE_1;
  FieldByName('DATE_TO').AsDateTime:= mem_calc_END;
  FieldByName('RATE_PRICE').AsCurrency:=mem_RATE_PRICE_1;
  FieldByName('DAYS').AsInteger:=mem_calc_DAYS;
  FieldByName('TOTAL').AsCurrency:=mem_RATE_PRICE_1 * mem_calc_DAYS;
post;
end;
 ABSQuery2.refresh;
end;
end;

The result I get is this :

As you can see from the database snapshot, prices are set OK.


variable manipulation in Less

all

I want to calculate the height of the page ,and in my test.less

@clientHeight:`$(window).height()`;

when I use the @clientHeight,as jquery return just a number,I need to plus the unit like px

So,I tried these ways:

1)

div{height: @clientHeight+px;

It came out :

height: 705 px;
(Note that there's a space between them)

2)

@clientHeight:`$(window).height()+'px'`

It came out :

height: "705px";


grunt-init not recognised / added to path (windows)

I'm on Windows and installed the new grunt using:
npm install -g grunt-cli
npm install -g grunt-init

grunt-init is the issue here.

If I try to run "grunt-init" in the command console, it is not recognised. Also after restarting the PC it's a nogo.
I checked the environment settings and grunt-init is indeed not included. In fact, when checking the node_modules directory (in "C:\Users\\AppData\Roaming\npm\node_modules") I see a directory "grunt-init", but there is no .cmd or other executable whatsoever.

Before I file a bug I wanted to ask here, because it seems that other Windows users have no issues with this..


How to set path inside of c++ program using system() function

I need to write c++ program which sets path using system() function:

system("set PATH=%PATH%;C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\bin\\amd64");
system("nvcc -x cu -o cudapair cudapair.c");

But it doesnt work. It throws error, because path wasn't set. What's the problem?


HTML form doesnt allow spaces on inputs

I have an HTML form loaded in via ajax to a lightbox.

You can see the behaviour on the homepage of http://www.powerbuy.com.au/

In the bottom right of the page there is a Link 'Let us negotiate a deal for you' Clicking this creates a lightbox and loads the form.

The issue is that you cannot put in spaces to any of the fields, it appears to be accepting any other characters, numbers and symbols, but not spaces.

I have looked through the code for any keyCode in the JS, but I cant find anything related to spaces.

Can you replicate the issue? Can you tell me what is going on?


Using <nav> <ul> and <li> to make navbar instead of a table. How do I make whole block clickable while spanning the width of the page?

There are three goals I have with this nav bar.

To make it 140px tall to fit a logo. This block will have a fixed width.

To make each link block have an even width and have the nav bar span the page.

To make the entire block clickable to the link.

Here is my code:

nav {
  position: absolute;
  list-style-type: none;
  z-index: 1;
  width: 100%;
  text-align: center;
  height: 140px;
  vertical-align: middle;
  overflow: hidden;
}
li {
  width: 16.7%;
  display: inline-block;
  vertical-align: middle;
}
li a {
  display: inline-block;
  color: white;
  font-size: 100%;
  font-family: 'Arial Narrow', Arial, sans-serif;
  text-decoration: none;
}

<nav>
  <ul>
    <li>
      <a href="homepage" title="Home Page">
        <img src="r3wmod.png">
      </a>
    </li>
    <li><a href="about" title="About Me">ABOUT</a>
    </li>
    <li><a href="projects" title="Projects">PROJECTS</a>
    </li>
    <li><a href="thoughts" title="Thoughts">THOUGHTS</a>
    </li>
    <li><a href="resume" title="Resume">RESUME</a>
    </li>
  </ul>
</nav>


character string buffer too small error

I'm trying to create a table with a select statement. I want to populate this new table with the aggregated value from a VIEW. Following is the code used for creating the VIEW,

  create or replace view FINAL_WEB_LOG
 as
 select SESSION_ID,
        SESSION_DT,
        C_IP,
        CS_USER_AGENT,
        tab_to_string(CAST(COLLECT(web_link) AS t_varchar2_tab)) WEBLINKS
 from web_views_tab
 group by C_IP, CS_USER_AGENT, SESSION_DT;

I want to create a table with WEBLINKS and SESSION_ID which is a sequence from another table.And when I try to create a table from VIEW (the one without the SESSION_ID), I get the following error,

SQL Error: ORA-06502: PL/SQL: numeric or value error: character string buffer too small

This has to do with the field, Weblinks, it does have longer values. What can I do now to get around this error??

More information on the aggregate function can be found in AskTom


Overriding javascript function on different page

This is new to me, and I don't know how to handle it.

The page has a logo that uses transitions to change its size and color and is triggered by this on the bottom of the HTML:

document.onload="initialize()"
setInterval(function(){
    setTimeout(function(){
        $('#path1').css('transform','scale(.95)');
        $('#path2').css('transform','scale(.95)');
        $('#path2').css('fill','#F7A700');
    }, 2000);
$('#path1').css('transform','scale(1.05)');
    $('#path2').css('transform','scale(1.00)');
    $('#path2').css('fill','#FFCF55');
}, 4000);

This starts the transition and changes the color of the svg path in coordination. On a separate script page there is a function that determines the current page slider and I need to change the css fill on #path2 for a specific page. I've tried if...else statements, moving the setInterval() function to the same page, etc, but nothing is letting me override the fill color in the setInterval() function.

REVISION: Its included in the html and there is a separate js page with all of the other functions. So I thought maybe it had something to do with that but now I'm understanding it is running on an infinite loop so any changes I try to make are going to be overridden. Its a logo that is a svg with multiple paths and on the homepage slide one path needs to be white and everything else stay the same for all other pages slides. There is only one page of html and the content slides on a slider. Not sure if I explained it any better. I'm working with existing code done by someone else so I'm trying to work with what I've been given but maybe there is a better solution to run this? maybe through css? I need it to load on window or document load and run infinitely but need to be able to modify the css on it. I have to use css transforms to set it up.


Jquery Plugins for Financial Reporting?

Any suggestions on some Jquery plugins for reporting a balance sheet or income statement?


jquery has no method error

I am  writing an ajax navigation script.
I found out i could highlight the current section into the menu by using

('a[href=' + document.location.hash + ']').addClass('current');

But I am getting this Error:

Object a[href="#home"] has no method 'addClass'

Any suggestion?


How to find all WiFi networks that are not in range?

I am writing an application to display the WiFi network types and status. How do I find all the "not in range" WiFi networks? Is it possible to get the list of all configured (previously seen) WiFi networks that are out of range?

I used the below code to get the result

    WifiManager mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<WifiConfiguration> configs = mWifiManager.getConfiguredNetworks();
    List<ScanResult> results = mWifiManager.getScanResults();
    if (configs != null) {
        for (WifiConfiguration config : configs) {
            for (ScanResult result : results) {
                if (result.SSID  == null || result.SSID.length() == 0) {
                    continue;
                }

                else {
                    if (result.SSID.equals(MyString.removeDoubleQuotes(config.SSID))) {
                        int level = mWifiManager.CalculateSignalLevel(result.level, 4);
                        Log.d("MyApp", Config.SSID + "  " + level);
                    }
                }
            }
        }
    }

But if configured network is high in number then it will take long time to execute. Is there any way to optimize this problem? By getting the scanned result of only the configured network.


popup image viewer doesn't resize the image when it is bigger than the screen resolution

I'm working with Bootstrap, i used this template of Gallery Image.

The website demo works great because the images are horizontal :

But when i edited the code and put my picture (which are verticals), i think it is trying to fill them horizontally so the image isn't visible at 100%.

How can i fix that, here is the code i think (I'm newbie so I'm not sure) :

<script>
                popup = {
                    init: function(){
                        $('figure').click(function(){
                            popup.open($(this));
                        });

                        $(document).on('click', '.popup img', function(){
                            return false;
                        }).on('click', '.popup', function(){
                            popup.close();
                        })
                    },
                    open: function($figure) {
                        $('.gallery').addClass('pop');
                        $popup = $('<div class="popup" />').appendTo($('body'));
                        $fig = $figure.clone().appendTo($('.popup'));
                        $bg = $('<div class="bg" />').appendTo($('.popup'));
                        $close = $('<div class="close"><svg><use xlink:href="#close"></use></svg></div>').appendTo($fig);
                        $shadow = $('<div class="shadow" />').appendTo($fig);
                        src = $('img', $fig).attr('src');
                        $shadow.css({backgroundImage: 'url(' + src + ')'});
                        $bg.css({backgroundImage: 'url(' + src + ')'});
                        setTimeout(function(){
                            $('.popup').addClass('pop');
                        }, 10);
                    },
                    close: function(){
                        $('.gallery, .popup').removeClass('pop');
                        setTimeout(function(){
                            $('.popup').remove()
                        }, 100);
                    }
                }

                popup.init()

            </script>


How to properly handle hibernate/SQL exception

In my Spring mvc + hibernate web-app, I'd like to handle SQL exception. so i have implement my GlobalExceptionHandler().

actually i send a duplicated value to simulate error

here console :

WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 23505
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: duplicate key value violates unique constraint "profiles_registration_number_key"
  Détail : Key (registration_number)=(1) already exists.
INFO : org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl - HHH000010: On release of batch it still contained JDBC statements
ERROR: org.hibernate.internal.ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
11:40:20.792 [http-nio-8080-exec-2] DEBUG org.springframework.orm.jpa.JpaTransactionManager - Initiating transaction rollback after commit exception
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [profiles_registration_number_key]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy87.save(Unknown Source)
    at tn.alveodata.studyink.controllers.PersonController.save(PersonController.java:143)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3013)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3513)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:589)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1437)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3207)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2413)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
    ... 48 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "profiles_registration_number_key"
  Détail : Key (registration_number)=(1) already exists.
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2190)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:136)
    at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:97)
    at org.apache.tomcat.dbcp.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
    ... 66 common frames omitted

my GlobalExceptionHandler()

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(DataIntegrityViolationException.class)
    public @ResponseBody ExceptionBean handle(DataIntegrityViolationException ex) {
        return new exceptionBean(ex.getMessage());
    }
...
}

How to properly handle SQLException so in my console i'll get rid with wran messages.

l have also tried with @ExceptionHandler(SQLException ex) in order to handle all kind of SQLException but exception was not handled


How to merge two git repos - local and remote?

I started developing some code at my laptop, so I executed git init and then made some commits. After that I even created branch on my local repo. I didn't expect that my colleague in the meantime will push some his work to remote repo I was planning to push my code (it was empty). What is the easiest way to merge those two repos into one?


Gulp, browserify and remapify

I'm trying to find a nice way to map directories with browserify and gulp so I don't have lots of paths link this:

var uriparser = require('../../../app/assets/javascripts/app/module/mymodule.coffee')

So I have been trying to use remapify with gulp so I have recipe like this:

var gulp = require('gulp');
var browserify = require('browserify');
var remapify = require('remapify');
var source = require('vinyl-source-stream');

gulp.task("test", function () {
  var b = browserify({entries:['./spec/javascripts/modules/tests.coffee'],
    extensions: ['.coffee']
  });

  b.plugin(remapify, [
    {
      src: './app/assets/javascripts/app/**/*.coffee'
      , expose: 'app'
      , cwd:__dirname
    }

  ])

  libs.forEach(function (lib) {
    b.external(lib);
  });

  return b.bundle()
    .pipe(source("app.js"))
    .pipe(gulp.dest('./spec/javascripts/specs/helpers'));
});

Not sure what I am missing, but it simply not mapping the paths correctly, maybe this isn't the best tool, but have tried quite a few options with no success, so any help would be great!


How to set first letter to upperCase on button click

When i click button and it appears on web-page i want to do the first letter toUpperCase(); But i don't know how to it properly. I made it like this:

function toUpper() {
            arr.charAt(0).toUpperCase() + arr.slice(1);
 }

But this seems not correct, please explain how to do it right way?

    <input type="text" id="inp">
    <button class="btn">Push to array</button>
    <button class="delete">Delete</button>
    <br><br>
    <div id="list"></div>

<script>

var inp = document.getElementById("inp");
var btn = document.querySelector(".btn");
var list = document.querySelector('#list');
var del = document.querySelector(".delete");
var arr = [];

btn.addEventListener('click', function() {
  var valInp = inp.value;
  if (valInp === '') { return; }
  arr.push(valInp);
  inp.value = "";
  list.innerHTML = arr.join("<br>").trim();

    function toUpper() {
        arr.charAt(0).toUpperCase() + arr.slice(1);
    }
});

 del.addEventListener('click', function(){
    arr.pop();
    list.innerHTML = arr.join("<br>").trim();
});

</script>


SQL injection help

So I was just testing out the mysql_real_escape(); function and what that does is puts a \ before the ". The when the content is echoed back out onto the page I just get content with \'s before any ". So let's say I posted """""""""""""""""""""""""""" all I get is \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" echoed back.

Is there some code to remove the \ when it's echoed back onto the page?


Windows Phone 7 ListBox index operator

I am trying to add Strings in a ListBox in Silverlight for Windows Phone 7. I want the strings to appear in fixed width columns, and for the ListBox to scroll into view when a new row is started in the listBox. Additionally, one word is added to the listBox at a time when the user clicks a button. I tried using a WrapPanel, but that did not allow for scrolling into view. Now my current solution would be valid, however the index operator gives me an index out of bounds error and the insert method gives me duplicate entries that appear on the next row down...

I am trying to use either the Insert method or the index operator (obviously not both) like so:

this.wordListBox.Items.Insert(numRows, formatRow);
this.wordListBox.Items[numRows] = formatRow;

This is an idea of the flow of my program, Example:
The user clicks a button and a Word is concatenated to the presently null formatRow and formatRow is added to the wordListBox at numRows which is presently 0. The button is clicked again and another word is concatenated to formatRow and formatRow is added to the wordListBox at numRows which is still 0. Thus, I now have the first element of wordListBox set to a string that contains two words. This repeats until 5 words have been added to formatRow and then, numRows is incremented and formatRow is set to null. Now, words will be added to the next row in the wordListBox, and the wordListBox will scroll into view because each element of the ListBox will be one string.

Can anyone point out my error with the insert method of index operator or show me how to make these functions work for my purposes?
Also, If anyone needs a better explanation I will try my best to explain in more detail.


Allocating dynamic array within a function of a structure

I have a BST structure:

struct bst {
    int *data;
    int max;
};

And I have a function to create a bst initially:

struct bst *create_bst(int max) {
    struct bst *b;
    b->data = malloc(pow(2, max) * sizeof(int));

    return b;
}

But I'm getting error at the line where I'm allocating memory to data.

Am I doing something wrong?


Can't generate javadoc in eclipse

This really should be a stupid question, but I'm trying to generate javadoc in my Android eclipse project and I'm getting errors.  I'm on a mac and the javadoc command is set at

 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/javadoc

But for some reason it seems to be using 1.3

 annotations are not supported in -source 1.3
 (use -source 5 or higher to enable annotations)
        @Override

Has anyone else run into this?


strip timestamp/syntax-sequence from python string

I'm working on a python script which retrieves values from an sdict as a string value. Many of the returned values contain a timestamp depending on the sdict, which is a tad annoying.

Eg. <2006-12-20 00:10:24 Cattle is a tree>

I cannot for the life of me, figure out how to remove the 2006-12-20 00:10:24 from the returned value. Has anyone got any ideas? I was thinking I could strip anything between - characters. However, the returned values often contain - throughout.


PyCharm does not recognize iPython when installed via Ubuntu's apt-get

I've installed iPython for Ubuntu's default Python installation (because I couldn't compile some particular program with Anaconda) using sudo apt-get install ipython. I can use /usr/bin/ipython in the command line.

However, when linked against the default python interpreter in the project settings (/usr/bin/python3.5), the python command line does not support ipython and is the standard python command line.

The project interpreter window also does not list ipython as installed package for the /usr/bin/python3.5 configuration. But it is there:

sudo apt-get install ipython
Reading package lists... Done
Building dependency tree
Reading state information... Done
ipython is already the newest version (2.4.1-1).

How can I fix this?

Output from initializing command line:

/usr/bin/python3.5 /opt/pycharm-2016.3.2/helpers/pydev/pydevconsole.py 44543 41206
PyDev console: starting.
import sys; print('Python %s on %s' % (sys.version, sys.platform))
sys.path.extend(['$$projectPath$$'])
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux


jpanel not showing contents

I am trying to make a generic Ok/Cancel dialog that can accept a subclassed JPanel that adds two abstract methods (void ok() and void cancel());

The idea is that when the Ok button or the Cancel button is pushed, the appropriate methods on the subclassed panel are called. However, I cannot get the main frame to show the JPanel.

here is the OkCancelFrame code. If it is run, it should show an Ok/Cancel form with the text "Now you see me".

import javax.swing.JLabel;

public class OkCancelForm extends javax.swing.JFrame {

    private OkCancelPanel okCancelPanel;

    public OkCancelForm(OkCancelPanel okCancelPanel) {
        this.okCancelPanel = okCancelPanel;
        initComponents();
        mainPanel.add(okCancelPanel);
        mainPanel.revalidate();
        mainPanel.repaint();
        pack();
    }

    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        mainPanel = new javax.swing.JPanel();
        javax.swing.JPanel buttonPanel = new javax.swing.JPanel();
        javax.swing.JButton ok = new javax.swing.JButton();
        javax.swing.JButton cancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        mainPanel.setLayout(null);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        getContentPane().add(mainPanel, gridBagConstraints);

        buttonPanel.setLayout(new java.awt.GridBagLayout());

        ok.setText("Ok");
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okActionPerformed(evt);
            }
        });
        buttonPanel.add(ok, new java.awt.GridBagConstraints());

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });
        buttonPanel.add(cancel, new java.awt.GridBagConstraints());

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        getContentPane().add(buttonPanel, gridBagConstraints);

        pack();
    }

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {
        okCancelPanel.cancel();
        this.dispose();
    }

    private void okActionPerformed(java.awt.event.ActionEvent evt) {
        okCancelPanel.ok();
        this.dispose();
    }

    public static void main(String args[]) {
        OkCancelPanel panel = new OkCancelPanel() {
            public void ok() { }
            public void cancel() { }
        };

        panel.add(new JLabel("Now you see me"));

        new OkCancelForm(panel).setVisible(true);
    }

    private javax.swing.JPanel mainPanel;
}


Create small read-only unfocused buffer

I have a problem explaining what I need, and this is why I can't find it (probably), but I'll try my best.

I need one line of text on top of modeline, kind of a footer in the buffer. It is for displaying help, so with-electric-help gets very close to it except that there's an issue with focus (I can move focus back to the original window, but the key bindings will be of the help buffer - not good).

Ideally it would be just a line of text which stays on top of modeline (doesn't scroll with the buffer).

My issues with creating just a separate buffer: I don't know how to find out that the user removed focus from the buffer which was previously showing the "small buffer", so I don't know when to hide it.


Do any distributed computing platforms use a common format to exchange messages?

I'm writing my own toy platform and I'd like to make it compatible with others if possible. Is there a common message format that allows nodes from different platforms to communicate with one another?

edit: Added terminology tag for clarity. I've seen the phrase 'exchange format' used to describe what I'm asking for but I don't know whether that is a canonical term.


Is let validators: { [s: string]: StringValidator; } = {}; the same as ...?

The typescript handbook has the following example:

// Validators to use
let validators: { [s: string]: StringValidator; } = {};
validators["ZIP code"] = new ZipCodeValidator();

Is doing:

let validators: { [s: string]: StringValidator; } = {};

The same as:

let validators = {};
validators["s"] = new StringValidator();

If you could elaborate on the details on how the syntax works that would be great.


How do I access a third party DLL from a Tcl script?

I am trying to learn how to access a third party DLL from a Tcl script.  There are a lot of tidbits of information on this topic in numerous places, but nothing that provides a nice, concise start-to-finish description of how to do it.  I've tried a number of things, with varying degrees of failure.  I've gotten the closest to success using SWIG and Visual Studio Express 2012 (both of which I am a complete newbie...)

I saw a previous response to a similar question here How to create a DLL with SWIG from Visual Studio 2010, in which the goal was to create a DLL from C code.  I do not have the source for the DLL, only the .dll, .h, and .lib files from the vendor who created the DLL.

The responder in that post had instructions that are very close to what I'm looking for, I think.  He stated that the process for wrapping a DLL is similar, and to ask if instructions were needed to accomplish that.  I'm hoping he responds to this post...

(Disclaimer: I'm a complete newbie to this forum as well, and I couldn't figure out a way to follow up on that post directly.  Please forgve my ignorance...)

Can anyone povide detailed instructions on how to accomplish my goal?  Thanks in advance!


Linking to local video file for video background HTML/CSS

I've been stuck trying to make a video on my computer be the video in the background. My video is titled "runbg.avi" and it is in the same folder as my HTML and CSS files.

These are a couple of many websites that I visited to search for an answer.

Using file:// instead of http:// when trying to get video from my computer rather than the web.

I can point to video on the web but not locally.

My program so far.

/* BACKGROUND */
video#vid {
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
background-size: cover;
margin: 0 auto;
}

<!DOCTYPE html>
<head>
<title>Seb's Fitness</title>

<link rel = "stylesheet"
      type = "text/css"
      href = "css.css" />

      <video autoplay loop poster="" id="vid">
    <source src="file://runbg.avi" type="video/avi">
    </video>


msysgit and git-cheetah having issues on winXP with "Git Bash" context menu

I've installed msysgit version 1.8.0 on Windows XP and I chose to use the plugin "advanced" version for the context menu.  If i start up git bash from the shortcut icon, it starts up fine.  But if I use the right click context menu, I got the following errors:

Welcome to Git (version 1.8.0-preview20121022)

Run 'git help git' to display the help index.
Run 'git help <command>' to display help for specific commands.
sh: /bin/stty: No such file or directory
sh: /bin/stty: No such file or directory
sh: hostname: command not found
sh: unalias: cm: not found
:Desktop/2 part Auth/GoogleAuth>

I used the same version on my home windows 7 machine and had no issues at all.

Any clues?

Thanks,
Justin


How to upload Site in WHM SERVER?

I have a WHM Control Panel. I want to Upload Site on WHM SERVER But i am not getting File Manager Like  in Cpanel Hosting Where we can upload site form File Manager.


Generate list from user input

How could I have a user input something like Blah Blah [1-30] Blah and then parse it to get a list like so:

[
    'Blah Blah 1 Blah',
    'Blah Blah 2 Blah',
    etc...
    'Blah Blah 30 Blah',
]


How to insert the rows in the database mysql table in the following?

I have two table named: Blog for displaying blogs post and comments for displaying comments section for each blog post.

The fields for these are as follows:

For Blog:

1: blog_id

2: title

3: body

4: author

5: updated

For Comments:

1: comments_id

2: name

3: email

4: body

5: blog_id

The field blog_id must be the same for both the table.

Now what i want is that suppose for blog_id = "2", I am writing comment, so what would be the insert query so that when i visit index.php?blog_id=2, I get the comments for only that particular post.

I mean how to insert the comments for a particular blog_id?

I tried this query to insert:

INSERT INTO cms.comments(blog_id, name,email,comments_body)
                VALUES (
                    '".$arr['blog_id']."',
                    '".$arr['name']."',

                    '".$arr['email']."',
                    '".$arr['body']."'
                ) );


How do I make an erasing animation in CSS?

I have a webpage designed in CSS and HTML that shows stuff written on a blackboard.

When the user clicks on a link on the homepage, I want the user to see a huge hand with a duster act like erasing the content to reveal the new webpage.

Is it possible to achieve this animation using only CSS? If not, then how do I do this in Javascript?


Deserializing Json using .Net

I have an external vendor API that returns JSON in this format

{"3":{"id":1,"name":"Scott Foo","age":55},
"59":{"id":2,"name":"Jim Morris","age":62}}

I am trying to deserialize it using the following code

[DataContract]
public class Name
{
    [DataMember]
    public int id { get; set; }

    [DataMember]
    public string name { get; set; }

    [DataMember]
    public int age{ get; set; }
}

Code to deserialize is

List<Name> nameList = Deserialize<List<Name>>(temp);

where the Deserialize is defined as

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    ms.Dispose();
    return obj;
}

The object returned in nameList is of zero count. Any idea how this JSON can be deserialized in .Net (i.e. not using Json.Net or any such third-party dll)?


Angular UI Router reset $scope

I'm building a quiz using AngularJS and UI Router.

I have my app structured like this:

 - intro screen
 - app screen (where you play the actual quiz)
 - results screen (where i display the score)

The app use the same controller (MainCTRL). I store in the MainCTRL in $scope.score the score.

The problem is that when I $state.go('results'); the controller is being reseted I think and the $scope.score is equal to 0.

How can I fix this problem?


What is the best way to update the DOM with AJAX to reflect changes in the DB?

I'm building this application using PHP, MySQL and jQuery. Essentially it's a checklist management application.

I have these checklists (laid out as tables, much like a spreadsheet) that can be edited asynchronously; every time there's a change, it's reported through an AJAX call to PHP which updates MySQL.

The tricky part is that it's possible for other people to be editing the same checklist at the same time, the content of the checklist is updated if jQuery notices a change between the JSON object (it fires of an HTTP request periodically to ping the DB) and the content in the HTML table row.

This works fine for a limited number of items in my checklist, but when when my checklist numbers a considerable amount of rows, it kinda craps itself and lags out. I know that the inefficiency lays in the fact that every time an HTTP request is made for the most recent items in the checklist, I loop through every row in the HTML table and compare the contents of the row with the corresponding checklist item in the JSON object to see if there was a change.

I was wondering if there's a more efficient way to detect changes between my JSON object and what I have on the screen without looping through the DOM?

Essentially, how do I keep a large dataset in sync asychronously with minimal DOM manipulation?

Thanks a lot!