text:
Q: Setting a file upload field value - Javascript/jQuery I have a form page that has a file upload field and I am trying to set the value of that field programmatically and although I know that it isn't possible due to security reasons, I would like to know if we still can? If there is a plugin or something that I could use to perform the upload. I have the Base64 value of the file field that is required to set that field, all I need to know is if there is a way to set it.
Any suggestions or help would be great in this regard.
Thanks.
Update:
Added a JsFiddle to demonstrate what I'm trying out.
Please visit this website to create a text file using the example in the js fiddle and convert it using this link.
var str = `text`;

http://www.motobit.com/util/base64-decoder-encoder.asp
JsFiddle

Note:
The answer(s) below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017.
See the answer in this question for details as well as a demo:How to set file input value programatically (i.e.: when drag-dropping files)?

A: You can convert the base64 string to a blob and then add it to the formData before submitting it with an ajax request:
$("#form").submit(function(e) {
  e.preventDefault();
  formData = new FormData($(this)[0]);
  var blob = dataURLtoBlob("base64 string");
  formData.append("yourfile", blob);
  $.ajax({
    url: "whatever.php",
    type: "POST",
    data: formData,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
      alert("Form has been submitted with file");
    }
});

dataURLtoBlob is a function that converts the base64 string to the binary file (blob) source: Blob from DataURL?

A:
Update: Added a JsFiddle to demonstrate what I'm trying out.

@seahorsepip Answer, minimally adjusted to substitute success for done which is not a defined $.ajax() setting, and removing trailing ; following done:function(){}, which logs a syntax error, should return expected result. Where convertedvalue at linked jsfiddle at updated Question is also adjusted to a valid data URI. That is, after converting string to base64, use the "data" URL scheme to convert base64 string to valid data URI; e.g.,
"data:text/plain;base64," + convertedvalue

Note, File object created at FormData is requested with GET and returned at success at stacksnippets and jsfiddle to demonstrate file within FormData POSTed by $.ajax()
var convertedvalue = btoa(str); // where `str` is string
$("#form").submit(function(e) {
  e.preventDefault();
  formData = new FormData($(this)[0]);
  // pass valid `data URI` to `dataURItoBlob`
  // note `base64` extension
  var blob = dataURItoBlob("data:text/plain;base64," + convertedvalue);
  formData.append("yourfile", blob);
  $.ajax({
    url: "/path/to/server",
    type: "POST",
    data: formData,
    contentType: false,
    cache: true,
    processData: false,
    // substitute `success` for `done`
    success: function(data) {
      //alert("Form has been submitted with file");
    } // remove trailing `;`
  });
})

var str = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.

Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.

Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.

Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.

Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.

Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.

Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.

Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.

Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.

Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.

Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.

Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.

Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.

Images:
1) Copy and replace the following files in the /images folder
        i.      1icon.png
        ii.     2icon.png
        iii.        3icon.png
        iv.     mobil-app.png
        v.      mobil-app-this.png
        vi.     properties-icon.svgz
        vii.        setupLogo.svgz
        viii.       web-app.png
        ix.     web-app-this.png`;
var convertedvalue = btoa(str);
console.log(convertedvalue);
$("#b64text").html(convertedvalue);
$("input[type=submit]").prop("disabled", false);
function dataURItoBlob(dataURI) {
  // convert base64 to raw binary data held in a string
  // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  var byteString = atob(dataURI.split(',')[1]);

  // separate out the mime component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

  // write the bytes of the string to an ArrayBuffer
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  // write the ArrayBuffer to a blob, and you're done
  var blob = new Blob([ab], {
    type: mimeString
  });
  return blob;

  // Old code
  // var bb = new BlobBuilder();
  // bb.append(ab);
  // return bb.getBlob(mimeString);
}

$("#form").submit(function(e) {
  e.preventDefault();
  formData = new FormData($(this)[0]);
  // pass valid `data URI` to `dataURItoBlob`
  var blob = dataURItoBlob("data:text/plain;base64," + convertedvalue);
  formData.append("yourfile", blob);
  $.ajax({
    url: URL.createObjectURL(formData.get("yourfile")),
    type: "GET",
    // data: formData,
    contentType: false,
    cache: true,
    processData: false,
    success: function(data) {
      console.log(data);
      $("#b64text").html(data);
      //alert("Form has been submitted with file");
    }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<form id="form">
  <input type="submit" disabled/>
</form>
<div id="b64text" style="  word-wrap: break-word;">

</div>

jsfiddle https://jsfiddle.net/rccfymrz/17/

A: The easiest way is to do an AJAX POST request to the form's action field on the <form> tag. This is what the normal HTML does on its own anyways, but in our case you can specify the data programmatically, in this case a multipart file.
For an example, see this question.

A: It is that simple: file type input accepts the path to file, that would be sent on form submit, not the file itself.
UPD: Well, currently it's a little bit more complex (File API), however this is just meant to give you access to the data the user wants to give you.
You don't actually need to mess with file input to send the file.
If you are the one that owns server, you always can accept base64 string from regular text input field as a valid file (as an alternative to regular file field).
Otherwise you can always use ajax (with text or blob) to send your  form.

A: Simple fileupload without submit form.
HTML
<input id="inputfileUpload" onchange="fileChanged(this);" type="file" accept="*/*" />

JAVACRIPT
function fileChanged(element) {
  if (element.files[0]) {
    var file = element.files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
      //file.name
      //file.size

      //Filedata: e.target.result
      //You can convert to base64
      //Angular sample:
      //$base64.encode(e.target.result);
    };
    reader.readAsBinaryString(file);
 }
}

A:
I have the Base64 value of the file field [...] I need to know is if there is a way to set it.

Wouldn't be possible to have an hidden input ?
You set the base64 to that field, as the maximum size of an input type="hidden" is the same as type="file"
This way, you avoid the security reasons preventing you to load the local file, and still let you send the base64 representation.
The only problem is, we don't know how you have this base64 string. Is it loaded from a request ? Already populated from php ? ...

A: If you just want to set what file is going to be the value of your file input field, you cannot. But you can set the field to blank for form validation reasons try using JavaScript:
document.getElementById("your-file-form-field-id").value = "";

A: Use jquery:
$('#file_id_here').attr({'value':'file_path_here'})


text:
Q: Possible breaking change in MVC4 Razor that can be fixed with "@:@" I recently upgraded my website from ASP.NET MVC3 (Razor) to MVC4 (Razor2), and in doing so found what seemed like a breaking change in the Razor view engine.
The scenario (greatly simplified) is shown below.
@model IEnumerable<string>

@{ Layout = null; }

<!DOCTYPE html>

<html>
    <body>
        <div>
              @foreach (var x in Model)
              {
                  @string.Format("Foo bar: {0}", x) // Errors in MVC4/Razor2
              }
        </div>
    </body>
</html>

This works fine in MVC3/Razor, however in MVC4/Razor2 the string.Format line results in an error of:

Unexpected "string" keyword after "@" character. Once inside code, you do not need to prefix constructs like "string" with "@".

If you remove the @, the view engine then demands that you terminate the string.Format line with a semicolon. However, ReSharper then warns (rightly so):

Return value of pure method is not used.

The two fixes I've found for this are either to use <text>:
<text>@string.Format("The value {0}", x)</text>

Or a more curious approach using @:@:
@:@string.Format("The value {0}", x)

Is this a known and documented change in the Razor view engine?

A: This is indeed a bug we decided not to fix, note that the syntax is incorrect as there is no transition between C# and markup in this case.
I understand that resharper shows a warning here but I believe the warning is wrong.
Here is the bug for future reference
https://aspnetwebstack.codeplex.com/workitem/458

A: Seems like a bug. It works with String:
@foreach (var x in Model)
{
    @String.Format("Foo bar: {0}", x)
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: JobRunrException when scheduling java background job We are using JobRunr to do some background job processing in Java.
We enqueue the jobs as follows:
CalendarEntry calendarEntry = new CalendarEntry("Quatuor Ebène", LocalDateTime.of(2020, 9, 16, 20, 0, 0).toInstant(ZoneOffset.UTC));
jobScheduler.enqueue(() -> calendarService.createCalendarEntry(calendarEntry));

When scheduling the job, we receive the following exception... any idea what is going on?
Did you register all necessary Jackson Modules?
org.jobrunr.JobRunrException: Did you register all necessary Jackson Modules?
    at org.jobrunr.JobRunrException.configurationException(JobRunrException.java:56)
    at org.jobrunr.utils.mapper.jackson.JacksonJsonMapper.deserialize(JacksonJsonMapper.java:76)
    at org.jobrunr.jobs.mappers.JobMapper.deserializeJob(JobMapper.java:20)
    at org.jobrunr.storage.InMemoryStorageProvider.deepClone(InMemoryStorageProvider.java:243)
    at org.jobrunr.storage.InMemoryStorageProvider.saveJob(InMemoryStorageProvider.java:259)
    at org.jobrunr.storage.InMemoryStorageProvider.save(InMemoryStorageProvider.java:109)
    at org.jobrunr.scheduling.JobScheduler.saveJob(JobScheduler.java:406)
    at org.jobrunr.scheduling.JobScheduler.enqueue(JobScheduler.java:397)
    at org.jobrunr.scheduling.JobScheduler.enqueue(JobScheduler.java:79)
    at org.jobrunr.scheduling.BackgroundJob.enqueue(BackgroundJob.java:39)
    at be.es.eventsystem.calendar.CalendarService.createCalendarEntry(CalendarService.java:106)
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `be.es.eventsystem.calendar.CalendarEntry` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"version":0,"jobSignature":"CalendarService.createCalendarEntry(CalendarEntry)","jobName":"CalendarService.createCalendarEntry(be.es.eventsystem.calendar.CalendarEntry@ea7ae0ea)","jobDetails":{"className":"be.es.eventsystem.calendar.CalendarService","staticFieldName":null,"methodName":"createCalendarEntry","jobParameters":[{"className":"be.es.eventsystem.calendar.CalendarEntry","object":{"@class":"be.es.eventsystem.calendar.CalendarEntry","title":"Quatuor Ebène","eventDate":"2020-09-16T20:00:00Z","id":"bc8ad3db-cf89-49b6-a382-8b3a08c3cbd2"}}]},"id":"43a6e74a-4b53-4227-9985-4daf0005abc7","jobHist"[truncated 182 chars]; line: 1, column: 358] (through reference chain: org.jobrunr.jobs.Job["jobDetails"]->org.jobrunr.jobs.JobDetails["jobParameters"]->java.util.ArrayList[0]->org.jobrunr.jobs.JobParameter["object"])
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1615)
    at com.fasterxml.jackson.databind.DatabindContext.reportBadDefinition(DatabindContext.java:400)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1077)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1332)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:331)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:199)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166)

A: I think the reason is that your CalendarEntry class does not have a default constructor, which is needed as Jackson will try to deserialize it.


text:
Q: MVC form post doesn't return render partial result According to some post here, i user Html.BeginFrom instead of Ajax.BeginForm, but on submit I take the control and return results with partial view:
$('#SearchForm').on('submit', function (evt) {
    evt.preventDefault();
    $.post('/Search/Index', $(this).serialize(), function (response) {
        $('#searchResults').html(response); // assuming response is HTML
    });
});

Here is the action which i call:
    [HttpPost]
    public ActionResult Index(SearchModel searchModel)
    {
        if (ModelState.IsValid)
        {
            searchModel = CustomBehaviour.GetResults(searchModel);
            return PartialView("SearchResults", searchModel);
        }

        return View(searchModel);
    }

When debugging the action is called and the js is called, also but there are no results, what could be the problem?
Here is the view:
        @using (Html.BeginForm("Index", "Search", FormMethod.Post, new { role = "form", @class = "form-horizontal", id="SearchForm" }))
        {
            @Html.AntiForgeryToken();
             @Html.EditorFor(m => m.Requirement)

             @Html.EditorFor(m => m.Location)

                    <button type="submit" class="btn btn-default">@Base.Search</button>

        }

A: The problem is your div id:

It needs to be:


text:
Q: Running Babun, Getting error "The system cannot find the batch label specified - CHECKTARGET" I am trying to set up Babun, a terminal emulator (see http://babun.github.io/). However, I am having difficulty simply installing it, getting the following error message:
The system cannot find the batch label specified - CHECKTARGET

I am following the install instructions from the github page, which are:
"Just download the dist file, unzip it and run the install.bat script. After a few minutes babun starts automatically. The application will be installed to the %USER_HOME%\.babun directory."
I have run them by going to the directory in the command prompt and then just typing in install.bat. I have also tried dragging the install.bat file into the terminal.
What do I need to do in order to run install.bat successfully?
Thanks for your help!

A: You have probably downloaded the source instead of the install dist.  Try downloading from here: http://babun.github.io/ and run the install.bat provided in that download.


text:
Q: the performance of json for the moment I have a dictionary with the keys names and the values id that belong to those names. When I want to search the id belonging to a particular name, I have to walk over the whole structure, so this method has a bad performance.
I was wondering if a json-structure would provide a more performant solution? So my question is: is the retrieving of the value of an attribute in json quick? I am talking about at least 250 different attributes in a single json.
If not, what would be the best way to solve this performance-issue?

A: 250 different elements is very unlikely to cause performance issues. Don't worry about it. If you really care, you can put the contents of your structure into a hash table, which will give you really fast look up performance. I would recommend that you don't worry about this unless you can prove (with a profiler) that this look up is a performance problem.


text:
Q: 'NoneType' object has no attribute '__getitem__' when I try to return a dict Traceback Switch to copy-and-paste view
C:\Python27\lib\site-packages\django-1.7.3-   py2.7.egg\django\core\handlers\base.py in get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) ...

 ▶ Local vars

 c:\mystudio\tag_study\views.py in recite_words
        VariablesNew = next_word(request) ...

▶ Local vars

c:\mystudio\tag_study\views.py in next_word
                p_t_set.type7_status = change["type_status"] ...

▶ Local vars

return (control)

I think I build a dict in the chossen_old_words function and return it, But when I try use the dict, it shows the following error:

'NoneType' object has no attribute 'getitem'

I do not know what produces this error. Is there some basics I missed?

A: I don't see any return statement in the chossen_old_words() function so while you build a dictionary in the function (I suppose it's the control one), you don't return it.
When you accept the return value in the next_word() function, as I said the chossen_old_words() function returns nothing. However, in Python every function returns something and if you don't return anything explicitly (like in your case), then None is returned. Which is exactly what happened to you.
None's type is NoneType and it doesn't have any method. You're trying to use it as a dictionary though and as soon as you try and retrieve an item from it, you'll get this error.
I believe this error can be fixed by adding return control statement at the end of the chossen_old_words() function. Hard to say if there are any other errors though.
BTW, your indentation seems to be off.


text:
Q: How to ignore max and min of rows when applying describe function to pandas groupby I am using pandas groupby function and trying to get the description of the grouped results, but without each group's maximum and minimum row. I can't find the right answer to my question.
data = {'class': ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'],
       'num': [-10,18,12,15,50, 10,60,51,54,100]}
df = pd.DataFrame(data)
df.groupby('class').describe()

output:
         num
        count   mean    std        min    25%    50%     75%    max
class
a      5.0     17.0   21.494185   -10.0   12.0    15.0  18.0    50.0
b      5.0     55.0   31.984371    10.0   51.0    54.0  60.0    100.0

The result that I want is:
       num
       count    mean    std         min     25%     50%     75%  max
class
a      3.0      15.0    3.000000    12.0    13.5    15.0    16.5    18.0
b      3.0      55.0    4.582576    51.0    52.5    54.0    57.0    60.0

A: Using transform and masking:
df['max']=df.groupby('class')['num'].transform('max')
df['min']=df.groupby('class')['num'].transform('min')

mask = df['num'].ne(df['min'])&df['num'].ne(df['max'])

df.loc[mask,:].groupby('class')['num'].describe()

       count  mean       std   min   25%   50%   75%   max
class
a        3.0  15.0  3.000000  12.0  13.5  15.0  16.5  18.0
b        3.0  55.0  4.582576  51.0  52.5  54.0  57.0  60.0

Or:
df.loc[mask, ['class', 'num']].groupby('class').describe()
        num
      count  mean       std   min   25%   50%   75%   max
class
a       3.0  15.0  3.000000  12.0  13.5  15.0  16.5  18.0
b       3.0  55.0  4.582576  51.0  52.5  54.0  57.0  60.0

A: Another method using apply() , idxmax() and idxmin()
>>df.groupby('class').apply(lambda x: x.drop([x['num'].idxmax(),x['num'].idxmin()])).rename_axis([None,None]).groupby('class').describe()

     num
     count mean std         min    25%     50%      75%     max
class
a   3.0   15.0  3.000000    12.0    13.5    15.0    16.5    18.0
b   3.0   55.0  4.582576    51.0    52.5    54.0    57.0    60.0

Explaination: Do a groupby on class and remove max and min values index from each group. then do a groupby on class and call the describe() function.


text:
Q: remembering last hovered li and default hovered li on page load Ok so i have a UL and each of the li has a background colour of blue, when you hover over the li its background colour changes to yellow.
That all works great with CSS but i want the last hovered li to remain hovered when the mouse is no longer hovering over an li.
But thats not all id also like the first li to by default be hovered when the page loads, going to non hovered when you hover over another li.
since :hover only works when you hover over an object you can't use CSS so i guess it will need to be done using Javascript and Classes. Should it be done like a Javascript hover button, with the first li having an active class which is removed when you hover over another li?
HTML

1

Option 1

2

Option 2

3

Option 3

4

Option 4

5

Option 5

CSS
ul.menu li{
display:inline-block;
height:5vh;
width:80%;
background-color:#003399;
color:#FFF;
margin-bottom:2px;
}

ul.menu li:hover{
background-color:#fed928;
color:#003399;
}

A: You answered your own question.  Since you want this to persist over page loads, you'll definitely have to use javascript or somesuch to write to a cookie or a session.

A: In javascript simply you can use JQuery and this code:
$("ul li").mouseover(function() {
    $(this).css("background-color", "#EEE").siblings("li").css("background-color", "");
});

For include jquery in your code use this:

in your html code
If you need to remember last hover li in next page reload you can use Cookie and read this


text:
Q: p-value of an Average Correlation Coeficient I have several Pearson correlation coefficients with their corresponding p-values. But I need an Average Correlation Coefficient. To calculate it, I've used the Fisher z transformation mentioned here and here. But, probably due to my lack of knowledge, I didn't find a way to compute a p-value for this average correlation coefficient.
Can you help me with this?

A: You might just want to calculate the confidence interval.
Zr has a nearly normal distribution with variance
sz² = 1 / n - 3.
Using these statistics we can construct a level C confidence interval for the population value
Zr +/- z* / Square Root(n - 3)
where z* is the critical value from the normal distribution such that the area between -z* and z* is equal to C.


text:
Q: Early return in functions and yield I'm not sure what the correct way is to early return in a function when using the yield keyword.
Is a "return void" return; the correct return value? Because the return type is specified to be iterable. Although it works without any error, returning void if the type hint would be int would lead to an error. So is iterable type hint an exception to still accept a void return statement although the type hint indicates something iterable should be returned?
See the example below to clarify my question:
class Collection
{
    public $items;
}

class OrderedCollection extends Collection
{
    public $orderedItems;
}

class Test
{
    public function getCollectionItems(Collection $collection): iterable
    {
        if ($collection instanceof OrderedCollection) {
            yield from $collection->orderedItems;
            return; // What should I return here to early exit the function?
        }

        yield from $collection->items;
    }
}


text:
Q: How to check if dropdown has one value or none in jquery? What I want to do is check if a drop down has one value or none and then make it read only?
if(){
 $('#dropdown').attr("disabled", "disabled");
}

<select class="dropdown" name="dropdown" id="dropdown">
        <option value="L6.5">L6.5</option>
   </select>

<select class="dropdown" name="dropdown2" id="dropdown2"></select>

<select class="dropinput" name="dropdown3" id="dropdown3">
       <option value=""></option>
       <option value=""></option>
</select>

I need all top three dropdowns to be disabled

A: According to HTML specs, the select tag in HTML doesn't have a readonly attribute, only a disabled attribute. Try this it will check for one or no option and disable it accordingly.
var $dd = $('#dropdown');
if($dd.find('option').length <= 1){
    $dd.prop('disabled', true);
}
else{
    $dd.prop('disabled', false);
}

Demo

A: Try this:
if ($('#dropdow').length < 2) {
  $('#yourcheck').attr('checked', true);
  $('#yourcheck').attr('readonly', true);
}


text:
Q: Is it mandatory to keep images in assets folder in Angular 2? Images are kept in "assets" directory as its public but can it be kept in respective components so HTML files can easily access

A: It is not required to put images in assets project.
Asset folder is preconfigured. When you run build command then all the things in asset folder will copied to output folder(dist) automatically for publish. So no need to copy manually.
You can also configured different folder as a asset. see in below code sample.
  "assets": [
    "assets",
    "xyz",
    "favicon.ico"
  ],

A: Assets folder is used in angular for maintaining file which doesn't have to be modified while compiling. You can't maintain any files like Images, json or any other file types in a component folder(folders are only for development purpose only) because it will be not recognized while compiling.
If you are in any component always set image path like this. Always maintain assets as a starting folder
"assets/pic.img"

Not like this and it won't be recognized
"./../assets/pic.img"


text:
Q: What is the VC++ compiler option /Oi equivalent for gcc? /Oi allows the VC++ compiler to use intrinsics. What is the equivalent in gcc 9 or 10?
Would gcc -O3 compiler option enable the use of intrinsics?

A: What you are searching is Built-in Functions.
https://gcc.gnu.org/onlinedocs/gcc-4.9.2/gcc/Other-Builtins.html
Builtins are enabled by default :
-fno-builtin
-fno-builtin-function
Don't recognize built-in functions that do not begin with '__builtin_' as prefix. See Other built-in functions provided by GCC, for details of the functions affected, including those which are not built-in functions when -ansi or -std options for strict ISO C conformance are used because they do not have an ISO standard meaning.

GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to alloca may become single instructions which adjust the stack directly, and calls to memcpy may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to printf when printf is built in and strlen is known not to modify global memory.

With the -fno-builtin-function option only the built-in function function is disabled. function must not begin with '__builtin_'. If a function is named that is not built-in in this version of GCC, this option is ignored. There is no corresponding -fbuiltin-function option; if you wish to enable built-in functions selectively when using -fno-builtin or -ffreestanding, you may define macros such as:

#define abs(n)          __builtin_abs ((n))
#define strcpy(d, s)    __builtin_strcpy ((d), (s))

https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#C-Dialect-Options
When you see the optimisations which turn on with O3, there is no mention of builtin. https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html


text:
Q: In Java program how to export data from database to text file I am trying to write a file fetching values from Database using java code.
The Resultset values are retrieved from DB & Then writing to a file.I am able to write to File ,But I am not getting the exact value ,instead getting the Junk Value.
Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String n=request.getParameter("device");

                Connection conn = null;
                PreparedStatement pst = null;
                ResultSet rs = null;

                String url = "jdbc:mysql://localhost:3306/";
                String dbName = "db5";
                String driver = "com.mysql.jdbc.Driver";
                String userName = "root";
                String password = "root";

                 try {
                        Class.forName(driver).newInstance();
                        conn = DriverManager.getConnection(url + dbName, userName, password);

                    File file = new File("D://Code2.txt");
                    FileWriter fw = new FileWriter(file.getAbsoluteFile());
                    BufferedWriter bw = new BufferedWriter(fw);

                    pst = conn.prepareStatement("select latitude,longitude,speed,heading,timeofday,timeofhours,gpssource  from nidgis where nidevid=?");
                    pst.setString(1, n);
                    rs = pst.executeQuery();
                    out.println("");
                    out.println("
LIVE  VEHICLE DATA
");

                    out.println("
");
                    while(rs.next())
                     {
                           out.println("
");

                           out.println("DAYS	");
                           out.println("HOURS	");
                           out.println("SPEED	");
                           out.println("HEADING	");
                           out.println("GPSDATA	");
                           out.println("
");

                          out.println("
");

                          out.println(""+rs.getInt("timeofday") +"	");
                          out.println(""+rs.getInt("timeofhours") +"	");
                          out.println(""+rs.getInt("speed") +"	");
                          out.println(""+rs.getInt("heading") +"	");
                          out.println(""+rs.getInt("gpssource") +"	");

                          out.println("
");

                          bw.write(rs.getInt("latitude"));
                          bw.write(rs.getInt("longitude"));

                    }
                    out.println("
");

                    out.println("");
                    bw.close();
                }
                catch (Exception e)
                {
                    System.out.println(e);
                }
                finally
                {
                    if (conn != null)
                    {
                        try {
                            conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    if (pst != null) {
                        try {
                            pst.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    if (rs != null) {
                        try {
                            rs.close();
                        } catch (SQLException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }

I am Writing only Latitude & Longitude to File ,Rest Displaying it in a table.For Both data type in DB is DOUBLE.
                      bw.write(rs.getInt("latitude"));
                      bw.write(rs.getInt("longitude"));

O/P that I am getting code2.txt is some string values :
M
M

A: That's because, your integer is type casted to character as per the write api. See this line cb[nextChar++] = (char) c;
So int 77 = M character and is what is being written onto file. You could convert your integer to String and write onto file like:
bw.write(String.valueOf(rs.getInt("latitude")));

A: Try to close BufferedWriter and then FileWriter in finally block.
bw.close();
fw.close();

A: The getInt(...) method returns an int value.
You can convert those values to String by using String.valueOf(rs.getInt(...)).
Or you can call rs.getString(...) to get those values as Strings from the ResultSet

A: 2 things:

*

*Use bw.flush() before bw.close(). See this.

*If latitude and longitude are of type double, then why not use ResultSet#getDouble(...)?

Also share some more details regarding the original longitude/latitude values and the output that you're getting in the file. This will help is identifying the problem (if any).

A: You can see this solution:
exporting sql query result to a csv or excel
In poperties files set this values:
fileExtension=.txt
columSeparator=\t


text:
Q: How do I ensure that typedefs in a template are also swigged? I am wrapping a C++ class (PointMatcher.h) for C# using SWIG. I have used the %template directive to concretise a template class as follows:
%include "../pointmatcher/PointMatcher.h"

%template(PointMatcherFloat) PointMatcher<float>;

However, it turns out the template PointMatcher<T> contains typedefs and typenames based on <T> and these are not being included in the SWIG wrapper. (Specifically, I need access to TransformationParameters below.)
//! The scalar type
typedef T ScalarType;
//! A vector over ScalarType
typedef typename Eigen::Matrix<T, Eigen::Dynamic, 1> Vector;
//! A vector of vector over ScalarType, not a matrix
typedef std::vector<Vector, Eigen::aligned_allocator<Vector> > VectorVector;
//! A quaternion over ScalarType
typedef typename Eigen::Quaternion<T> Quaternion;
//! A vector of quaternions over ScalarType
typedef std::vector<Quaternion, Eigen::aligned_allocator<Quaternion> > QuaternionVector;
//! A dense matrix over ScalarType
typedef typename Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Matrix;
//! A dense integer matrix
typedef typename Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic> IntMatrix;

//! A matrix holding the parameters a transformation.
/**
    The transformation lies in the special Euclidean group of dimension \f$n\f$, \f$SE(n)\f$, implemented as a dense matrix of size \f$n+1 \times n+1\f$ over ScalarType.
*/
typedef Matrix TransformationParameters;

// alias for scope reasons
typedef PointMatcherSupport::Parametrizable Parametrizable; //!< alias
typedef Parametrizable::Parameters Parameters; //!< alias
typedef Parametrizable::ParameterDoc ParameterDoc; //!< alias
typedef Parametrizable::ParametersDoc ParametersDoc; //!< alias
typedef Parametrizable::InvalidParameter InvalidParameter; //!< alias

I have tried duplicating the declarations above as an %inline block, using T and float. (As described in the SWIG 3.0 documentation on typedef.) In both cases the typedefs are simply included in the .cxx file, but no associated classes or methods are generated.
How do I make sure these types are made available in PointMatcherFloat?

Edit note: I previously thought this was about member templates (like How to instantiate a template method of a template class with swig? and How to get SWIG to apply templates when wrapping a template class containing vectors?) but it's actually about typedefs/typenames within a template.


text:
Q: Marshal.DestroyStructure not working after .net framework upgrade I have upgraded my solutions .net framework from 3.5 to 4.6.1 and I got an APPCRASH error while running my tool.
So I tried to debug the code and seems like when the control reaches the below code the debugging is simply getting exited without throwing any error.
Tried exception handling to catch the error but no use.
Marshal.DestroyStructure(p, typeof(DS_SELECTION))

Example
See this example in .Net Fiddle
using System;
using System.Runtime.InteropServices;
public class Program
{
    public static void Main()
{
    IntPtr p = IntPtr.Zero;
    IntPtr dsSL = IntPtr.Zero +1;
    p = (IntPtr)(((int)dsSL) + Marshal.SizeOf(typeof(DS_SELECTION_LIST)));
    if(IntPtr.Zero.Equals(p) == false)
    {
        //Console.WriteLine("Hello");
        Marshal.DestroyStructure(p, typeof(DS_SELECTION));
    }
}
internal struct DS_SELECTION
{
    [MarshalAs(UnmanagedType.LPWStr)]
    public string pwzName;
}

internal struct DS_SELECTION_LIST
{
    public uint cFetchedAttributes;
}
}


text:
Q: How to empty md-autocomplete text field after submit? I used md-autocomplete inside html form, then I wanted to set its field to empty after submitting. I tried, as shown in the snippet, to use $setPristine() but it didn't work. I also tried to assign the model to null or empty string, but also it wasn't successful.
PS: Angularjs version I used is v1.3.15

angular.module("myApp", ["ngMaterial"])
.controller("main", function($scope){
  $scope.searchString = "";
  $scope.routeToSearchPage = function (searchString, form) {
            $scope.form.$setPristine();
        };

    $scope.simulateQuery = false;
        $scope.isDisabled    = false;
        $scope.states        = loadAll();
        $scope.querySearch   = querySearch;
       function querySearch (query) {
            var results = query ? $scope.states.filter( createFilterFor(query) ) : $scope.states,
                deferred;
            if ($scope.simulateQuery) {
                deferred = $q.defer();
                $timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
                return deferred.promise;
            } else {
                return results;
            }
        }
        function loadAll() {
            var allStates = "aaa, bbbb, cccc, bla";
            return allStates.split(/, +/g).map( function (state) {
                return {
                    value: state.toLowerCase(),
                    display: state
                };
            });
        }
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);
            return function filterFn(state) {
                return (state.value.indexOf(lowercaseQuery) === 0);
            };
        }
})

<form name="form"
                             ng-submit="submit(searchString);$event.preventDefault();">
   <md-autocomplete
        md-floating-label="search"
        ng-disabled="isDisabled"
        md-no-cache="noCache"
        md-selected-item="selectedItem"
        md-search-text="searchString"
        md-items="item in querySearch(searchString)"
        md-item-text="item.display"
        ng-keyup="$event.keyCode == 13 ? routeToSearchPage(searchString) : null">
      <md-item-template>
        {{item.display}}
      </md-item-template>
  </md-autocomplete>
</form>
<md-button ng-click="routeToSearchPage(searchString, form)">
     <md-icon class="material-icons">search</md-icon>
</md-button>

A: Here's an example of clearing an md-autocomplete - CodePen
Your snippet isn't actually showing the md-autocomplete as it should appear.
JS
$scope.clear = function () {
    $scope.searchString = null;
};

I have also removed the markup below for the CodePen to work correctly:
ng-keyup="$event.keyCode == 13 ? routeToSearchPage(searchString) : null">


text:
Q: How do I show validation error when users submit the form without selecting anything from the drop-down list in ASP.NET MVC? In my ASP.NET MVC application, I have a form with drop-down list. If the user did not select a category and submitted the form, I will get exception. So How do I send validation error from the controller to the view? because I don't want to write JavaScript.
This is the drop-down list:
@Html.DropDownListFor(m => m.Article.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "Select Category", new { @class = "form-control" })

I know this way is working but I need that label (Select Category)
 @Html.DropDownListFor(m => m.Article.CategoryId, new SelectList(Model.Categories, "Id", "Name"), null, new { @class = "form-control" })

All and New controllers:
       [HttpPost]
       public ActionResult New(Article article)
        {

            if(ModelState.IsValid)
            {
                string FullName = HttpContext.GetOwinContext()
                    .GetUserManager<ApplicationUserManager>()
                    .FindById(User.Identity.GetUserId()).FullName;

                article.AuthorName = FullName;
                article.UserId = User.Identity.GetUserId();
                db.Aricles.Add(article);
                db.SaveChanges();
                return RedirectToAction("All");
            }
         }

        public ActionResult All()
        {
            var Articles = db.Aricles.ToList();
            return View(Articles);
        }

My model:
  public class Article
{
    public int Id { get; set; }
    [Required]
    public string Title { get; set; }
    [Required]
    public string Body { get; set; }
    public string UserId { get; set; }
    public string AuthorName { get; set; }
    public ApplicationUser User { get; set; }
    public Category Category { get; set; }
    public int CategoryId { get; set; }
}

I tried to use [Required] attribute but I don't know why it does not work.

This is a screenshot of the exception click

A: I found the issue after I thought about the comment written by Mannan Bahelim . I don't get validation error because the model in the view was ArticleCategoryViewModel while it should be Article model.


text:
Q: How many constructor arguments is too many? Let's say you have a class called Customer, which contains the following fields:

*

*UserName

*Email

*First Name

*Last Name

Let's also say that according to your business logic, all Customer objects must have these four properties defined.
Now, we can do this pretty easily by forcing the constructor to specify each of these properties.  But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object.
I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them.  But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties.
Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?

A: If you have unpalatably many arguments, then just package them together into structs / POD classes, preferably declared as inner classes of the class you are constructing. That way you can still require the fields while making the code that calls the constructor reasonably readable.

A: I think it all depends on the situation.  For something like your example, a customer class, I wouldn't risk the chance of having that data being undefined when needed.  On the flip side, passing a struct would clear up the argument list, but you would still have a lot of things to define in the struct.

A: I think your question is more about the design of your classes than about the number of arguments in the constructor. If I needed 20 pieces of data (arguments) to successfully initialize an object, I would probably consider breaking up the class.

A: I see that some people are recommending seven as an upper limit. Apparently it is not true that people can hold seven things in their head at once; they can only remember four (Susan Weinschenk, 100 Things Every Designer Needs to Know about People, 48). Even so, I consider four to be something of a high earth orbit. But that's because my thinking has been altered by Bob Martin.
In Clean Code, Uncle Bob argues for three as an general upper limit for number of parameters. He makes the radical claim (40):

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic) followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn't be used anyway.

He says this because of readability; but also because of testability:

Imagine the difficulty of writing all the test cases to ensure that all various combinations of arguments work properly.

I encourage you to find a copy of his book and read his full discussion of function arguments (40-43).
I agree with those who have mentioned the Single Responsibility Principle. It is hard for me to believe that a class that needs more than two or three values/objects without reasonable defaults really has only one responsibility, and would not be better off with another class extracted.
Now, if you are injecting your dependencies through the constructor, Bob Martin's arguments about how easy it is to invoke the constructor do not so much apply (because usually then there is only one point in your application where you wire that up, or you even have a framework that does it for you). However, the Single Responsibility Principle is still relevant: once a class has four dependencies, I consider that a smell that it is doing a large amount of work.
However, as with all things in computer science, there are doubtless valid cases for having a large number of constructor parameters. Don't contort your code to avoid using a large number of parameters; but if you do use a large number of parameters, stop and give it some thought, because it may mean your code is already contorted.

A: Steve Mcconnell writes in Code Complete that people have trouble keeping more 7 things in their head at a time, so that'd be the number I try to stay under.

A: I'd encapsulate similar fields into an object of its own with its own construction/validation logic.
Say for example, if you've got

*

*BusinessPhone

*BusinessAddress

*HomePhone

*HomeAddress

I'd make a class that stores phone and address together with a tag specifying wether its a "home" or a "business" phone/address. And then reduce the 4 fields to merely an array.
ContactInfo cinfos = new ContactInfo[] {
    new ContactInfo("home", "+123456789", "123 ABC Avenue"),
    new ContactInfo("biz", "+987654321", "789 ZYX Avenue")
};

Customer c = new Customer("john", "doe", cinfos);

That should make it look less like spaghetti.
Surely if you have a lot of fields, there must be some pattern you can extract out that would make a nice unit of function of its own. And make for more readable code too.
And the following is also possible solutions:

*

*Spread out the validation logic instead of storing it in a single class. Validate when user input them and then validate again at the database layer etc...

*Make a CustomerFactory class that would help me construct Customers

*@marcio's solution is also interesting...

A: Style counts for a lot, and it seems to me that if there is a constructor with 20+ arguments, then the design should be altered. Provide reasonable defaults.

A: I would think the easiest way would be to find an acceptable default for each value. In this case, each field looks like it would be required to construct, so possibly overload the function call so that if something is not defined in the call, to set it to a default.
Then, make getter and setter functions for each property so that the default values could be changed.
Java implementation:
public static void setEmail(String newEmail){
    this.email = newEmail;
}

public static String getEmail(){
    return this.email;
}

This is also good practice to keep your global variables secure.

A: In your case, stick with the constructor. The information belongs in Customer and 4 fields are fine.
In the case you have many required and optional fields the constructor is not the best solution. As @boojiboy said, it's hard to read and it's also hard to write client code.
@contagious suggested using the default pattern and setters for optional attributs. That mandates that the fields are mutable, but that's a minor problem.
Joshua Block on Effective Java 2 say that in this case you should consider a builder. An example taken from the book:
 public class NutritionFacts {
   private final int servingSize;
   private final int servings;
   private final int calories;
   private final int fat;
   private final int sodium;
   private final int carbohydrate;

   public static class Builder {
     // required parameters
     private final int servingSize;
     private final int servings;

     // optional parameters
     private int calories         = 0;
     private int fat              = 0;
     private int carbohydrate     = 0;
     private int sodium           = 0;

     public Builder(int servingSize, int servings) {
      this.servingSize = servingSize;
       this.servings = servings;
    }

     public Builder calories(int val)
       { calories = val;       return this; }
     public Builder fat(int val)
       { fat = val;            return this; }
     public Builder carbohydrate(int val)
       { carbohydrate = val;   return this; }
     public Builder sodium(int val)
       { sodium = val;         return this; }

     public NutritionFacts build() {
       return new NutritionFacts(this);
     }
   }

   private NutritionFacts(Builder builder) {
     servingSize       = builder.servingSize;
     servings          = builder.servings;
     calories          = builder.calories;
     fat               = builder.fat;
     soduim            = builder.sodium;
     carbohydrate      = builder.carbohydrate;
   }
}

And then use it like this:
NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).
      calories(100).sodium(35).carbohydrate(27).build();

The example above was taken from Effective Java 2
And that doesn't only applies to constructor. Citing Kent Beck in Implementation Patterns:
setOuterBounds(x, y, width, height);
setInnerBounds(x + 2, y + 2, width - 4, height - 4);

Making the rectangle explicit as an object explains the code better:
setOuterBounds(bounds);
setInnerBounds(bounds.expand(-2));

A: Two design approaches to consider
The essence pattern
The fluent interface pattern
These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step.
An example of the fluent interface in action would be:
public class CustomerBuilder {
    String surname;
    String firstName;
    String ssn;
    public static CustomerBuilder customer() {
        return new CustomerBuilder();
    }
    public CustomerBuilder withSurname(String surname) {
        this.surname = surname;
        return this;
    }
    public CustomerBuilder withFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }
    public CustomerBuilder withSsn(String ssn) {
        this.ssn = ssn;
        return this;
    }
    // client doesn't get to instantiate Customer directly
    public Customer build() {
        return new Customer(this);
    }
}

public class Customer {
    private final String firstName;
    private final String surname;
    private final String ssn;

    Customer(CustomerBuilder builder) {
        if (builder.firstName == null) throw new NullPointerException("firstName");
        if (builder.surname == null) throw new NullPointerException("surname");
        if (builder.ssn == null) throw new NullPointerException("ssn");
        this.firstName = builder.firstName;
        this.surname = builder.surname;
        this.ssn = builder.ssn;
    }

    public String getFirstName() { return firstName;  }
    public String getSurname() { return surname; }
    public String getSsn() { return ssn; }
}

import static com.acme.CustomerBuilder.customer;

public class Client {
    public void doSomething() {
        Customer customer = customer()
            .withSurname("Smith")
            .withFirstName("Fred")
            .withSsn("123XS1")
            .build();
    }
}

A: I think the "pure OOP" answer is that if operations on the class are invalid when certain members aren't initialized, then these members must be set by the constructor.  There's always the case where default values can be used, but I'll assume we're not considering that case.  This is a good approach when the API is fixed, because changing the single allowable constructor after the API goes public will be a nightmare for you and all users of your code.
In C#, what I understand about the design guidelines is that this isn't necessarily the only way to handle the situation.  Particularly with WPF objects, you'll find that .NET classes tend to favor parameterless constructors and will throw exceptions if the data has not been initialized to a desirable state before calling the method.  This is probably mainly specific to component-based design though; I can't come up with a concrete example of a .NET class that behaves in this manner.  In your case, it'd definitely cause an increased burden on testing to ensure that the class is never saved to the data store unless the properties have been validated.  Honestly because of this I'd prefer the "constructor sets the required properties" approach if your API is either set in stone or not public.
The one thing I am certain of is that there are probably countless methodologies that can solve this problem, and each of them introduces its own set of problems.  The best thing to do is learn as many patterns as possible and pick the best one for the job.  (Isn't that such a cop-out of an answer?)

A: Just use default arguments. In a language that supports default method arguments (PHP, for example), you could do this in the method signature:
public function doSomethingWith($this = val1, $this = val2, $this = val3)
There are other ways to create default values, such as in languages that support method overloading.
Of course, you could also set default values when you declare the fields, if you deem it appropriate to do so.
It really just comes down to whether or not it is appropriate for you to set these default values, or if your objects should be specced out at construction all the time. That's really a decision that only you can make.

A: I agree on the 7 item limit Boojiboy mentions.  Beyond that, it may be worth looking at anonymous (or specialized) types, IDictionary, or indirection via primary key to another data source.

A: In a more Object-Oriented situation of the problem, you can use properties in C#. It doesn't help much if you create an instance of an object, but suppose we have a parent class that needs too many parameters in its constructor.
Since you can have abstract properties, you can use this to your advantage. The parent class needs to define an abstract property that the child class must override.
Normally a class might look like:
class Customer {
    private string name;
    private int age;
    private string email;

    Customer(string name, int age, string email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
}

class John : Customer {
    John() : base("John", 20, "John@email.com") {

    }
}

It can become messy and unreadable with too many parameters.
Whereas this method:
class Customer {
    protected abstract string name { get; }
    protected abstract int age { get; }
    protected abstract string email { get; }
}

class John : Customer {
    protected override string name => "John";
    protected override int age => 20;
    protected override string email=> "John@email.com";
}

Which is much cleaner code in my opinion and no contractors are needed in this case, which saves room for other necessary parameters.

A: Unless it's more than 1 argument, I always use arrays or objects as constructor parameters and rely on error checking to make sure the required parameters are there.


text:
Q: Use only some items in a list comprehension? Surely this is possible. Searches turned up nil.
How do I create a list comprehension (or any type of comprehension) which only selects certain values from the source list or other iterable?

Example
Let's say I just want even numbers from a list. For example, given:
a = [1, 2, 3, 4, 5, 6, 7]

I can do this easily with a for loop, but need to initialize a variable:
b = []
for item in a:
    b.append(item) if item % 2 == 0
print(b)

Which returns:
[2, 4, 6]

But how to do this in a list comprehension and without initializing a variable first?

Failed List Comprehensions
I tried:
b = [ item if item % 2 == 0 for item in a ]

Which returns SyntaxError: invalid syntax after the for.
I if I add an else xxx it works, but then I must have the same number of total elements:
b = [ item if item % 2 == 0 else None for item in a ]

which returns:
[None, 2, None, 4, None, 6, None]

How can I remove or filter out items from the final comprehension if they don't meet the criteria?

A: After writing the question, the list of related items offered an answer indirectly.
Simply put, my guess at the syntax was wrong - I just have the "if" in the wrong place. It goes after the for statement:
a = [1, 2, 3, 4, 5, 6, 7]
b = [ item for item in a if item % 2 == 0 ]

I found the answer indirectly as part of this answer, but the question is different. I wasn't able to find anything directly asking this question, so I'll leave this up for other noobs like me that are still learning basic comprehension syntax.


text:
Q: First law of thermodynamics applied to a electrical conduction My book says that for current flowing in a wire
$Ri^2dt = mcdT + hS(T-T_0)dt $
and when equilibrium is reached
$Ri^2dt =  hS(T-T_0)dt $
where R is the resistance of the conductor, i is the current, dt is a time differential, m is the mass of the conductor, c is the specific heat, dT is the differential of temperature, h is the thermal conductivity, S the section of the wire, and external environment temperature.
The books says the electrical work done by the generator provoques an increase in temperature of the wire and heat is given to the external environment
I am trying to make sense of this equation by using the first law of thermodynamics,$W=Q-\Delta U $ but signs are not coming out well  and I am not sure of how should I do the energy balance or if I should make the external environment part of my system or not.
My try:
If the system is composed of just the wire
The work done by the generator should be - because it enters the system, so
 $W=- Ri^2dt  $
I am not sure if the increase of temperature of the wire should be $\Delta U$ or $Q$, because internal energy is due to temperature but this is also  heat being given to the environment, right? Considering it corrisponds to $\Delta U$ we have  $\Delta U =mcdT $
and so the heat should be given by Newton's conduction law, and since it leaves the system it is negative, so, $Q= - hS(T-T_0)dt $, then
$W=Q-\Delta U $
yields
$-Ri^2dt=- hS(T-T_0)dt-mcdT $
which would give the right answer, but
Why can't I consider $Ri^2dt$ to be instead the heat produced by the circuit and released to the environment, how would the energy balance be in that case?
One more thing, why does $ mcdT $ has temperature expressed with a differential, while  $ hS(T-T_0)dt $  does not?

A: This starts out with the time derivative of the first law equation:
$$\frac{dU}{dt}=\frac{dQ}{dt}-\frac{dW}{dt}$$where $$\frac{dU}{dt}=mC\frac{dT}{dt}\tag{1}$$$$\frac{dQ}{dt}=hS(T_0-T)\tag{2}$$and$$\frac{dW}{dt}=-i^2R\tag{3}$$
With regard to Eqn.2, this does not represent conductive heat transfer.  It represents the rate of convective heat transfer from the surroundings to the wire.  In this equation, S represents the surface area of the wire and h represents the convective heat transfer coefficient.  It says that the rate of heat flow from the surroundings to the wire is proportional to the temperature difference between the surroundings and the wire.
With regard to Eqn.3, $i^2R$ represents the power supplied to the wire by the surroundings (via a potential difference imposed across the wire by an electrical source in the surroundings).  This is the rate at which the surroundings do work on the wire (which comprises the system).
If we combine the previous equations, we obtain:  $$mC\frac{dT}{dt}=hS(T_0-T)+i^2R$$Multiplying this equation by dt gives back your original equation.


text:
Q: find values between range, fill in next cells I'm looking for a way for copying down all data found between a range and paste it in a next column.
A= text data
B= Random numbers but always starting from 1
C= some data
D= My needed solution
Example:
     A          B   C    D
    018404.00   1   20  20
    018404x0    2   0   20
    018404f1    2   0   20
    018404v1    3   0   20
    11000-0532  4   0   20
    1004-1101   5   0   20
    0720-0125   3   0   20
    0810-0001   3   0   20
    0710-0040   3   0   20
    052269.00   1   0   80
    052269v6    2   0   80
    11001-0000  3   0   80
    1001-1110   4   0   80
    0720-0500   2   0   80
    0810-0001   2   80  80
    0720-0002   2   0   80
    052275.00   1   0   160
    052275v2    2   160 160

When the value in column B is 1 then find value in column C (in Range B:B from 1 to 1) copying it to D
I have tried it with a formula but this limits the depth. If value on Column C isto far from the 1 row it doesn't work.
=IF(AND(B2=1;C2=0);IF(B3=1;0;IF(C3=0;IF(C4=0;C5;C4);C3));IF(C2>0;C2;I1))

So I think I need a vba solution.

A: i think you need something like this.
This code search max value between your 1 and 1 value
Sub FindValBetweenOne()

Dim LastRow As Long
Dim FindVal As Long

LastRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row

For I = 1 To LastRow
    If Cells(I, "B").Value = 1 Then 'find next "1"
        FindVal = Cells(I, "C").Value
        J = I + 1
        Do While (J <= LastRow And Cells(J, "B").Value <> 1)
            If Cells(J, "C").Value > FindVal Then
            FindVal = Cells(J, "C")
            End If
            J = J + 1
        Loop
    End If
    Cells(I, "D").Value = FindVal
Next I

End Sub


text:
Q: Weakly monotonic sequences I am confused with the definition of 'Weakly Monotonic Sequences'. Which one is correct?

*

*A sequence which is neither increasing nor decreasing

*A sequence which is not increasing or not decreasing

So, if the 2nd one is the correct one, then does it imply that an increasing sequence is weakly monotonic?(Similarly, does it imply that a decreasing sequence is weakly monotonic?)
Can anyone please help me to understand the correct definition?

A: A sequence which is either weakly increasing or weakly decreasing, Weakly, i.e. $a_n\leq a_{n+1}$ (or $a_n\geq a_{n+1}$).

A: Definition: A sequence (or function) $a(n)$ is increasing (decreasing) if $n\leq m$ implies $a(n)\leq a(m)$ ($n\leq m$ implies $a(n)\geq a(m)$. A monotone sequence (or function) is one that is either increasing or decreasing. With the exception of constant sequences (functions), these are mutually exclusive options.
Issues: It is common to give the above definition with strict inequalities ($<$ or $>$) instead of weak inequalities ($\leq$ or $\geq$). The difference usually does not matter, but it is a real difference. Because both definitions are common, a popular way of avoiding ambiguity is to use the terms strict and weak to specify whether you mean the definition with strict inequalities or the one with weak inequalities.
Examples:
$1,\frac{1}{2},\frac{1}{3},\frac{1}{4},\frac{1}{5}\ldots$ is weakly decreasing, strictly decreasing, weakly monotone, and strictly monotone. It is not increasing.
$1,1,1,1,1,\ldots$ is weakly increasing, weakly decreasing, and weakly monotone. It is not strictly monotone (thus not strictly increasing or strictly decreasing).
In the abstract, if I were talking about decreasing sequences then both of these would fall under the discussion. If I want to exclude the second sequence as an option, then I will talk about strictly decreasing sequences.
Many other mathematicians would only be referring to the former behavior when talking about decreasing sequences. They would specifically say they are talking about weakly decreasing sequences if they wanted the latter sequence to also fall under the discussion.
Both of these uses of the term are common in textbooks and, in my experience you won't have trouble finding mathematicians in the same department who disagree on which is the "right" definition.


text:
Q: How to compile & execute text in c#? I am working on an operating system with Cosmos, I am wondering if there is a way to compile text from a file, for example: helloworld.cs, and then execute the file. Thanks in advance.

A: If you want to compile a c# file (.cs) like helloworld.cs in Windows
namespace test {
    class test {
        static void Main(string[] args) {
            System.Console.WriteLine("Hello World");
        }
    }

}

you can use csc.exe to compile the file
C:\Windows\Microsoft.NET\Framework\{version}\csc.exe pathToFile


text:
Q: How can I list all service accounts (also those created by GCP) with the "gcloud" CLI? When using gcloud iam service-accounts list I only see those service accounts created by me. But for script reasons I'd like to obtain also those created by GCP.
Especially I am looking for 815330817453@cloudbuild.gserviceaccount.com. Since I am creating my GCP infrastructure with terraform I can not depend on 815330817453 as an identifier and therefore need to look for the service account manually via gcloud.
However gcloud iam service-accounts list does not list the cloudbuild.gserviceaccount.com service account (nor any other like compute.gserviceaccount.com`

A: Check your IAM roles , start by adding the role IAM admin/Viewer to your user, don't forget to use the command with the filter --project
gcloud iam service-accounts list --project=PROJECTID .
check also the IAM&Admin interface -> Service account if you can see all service accounts, that means you can list them using the gcloud command , if not you're user is messing a role

A: There are a couple of important qualifications to your question.
Service Accounts have a dual role in Google Cloud Platform. Service Account are (both) resources and may be used as identities.
1. Resource
Service Accounts are resources created in (owned by) a Google Cloud Platform project.

NOTE Service Accounts may be applied to non-Project resources too and, what follows, excludes (does not include) those bindings.

A Project foo owns zero or more Service Accounts. For Project (PROJECT), these may be enumerated:
gcloud iam service-accounts list \
--project=${PROJECT}

2. Identity
A Project foo includes an IAM Policy that may reference zero or more Service Accounts. These Service Accounts may be created in (owned by) any Google Cloud Platform project (not just the project policy in which they're referenced). These Service Accounts include Google-managed Service Accounts such as those in the domain gserviceaccount.com.
To enumerate these Service Accounts requires a different command. For Project (PROJECT), these may be enumerated:
gcloud projects get-iam-policy ${PROJECT} \
--flatten="bindings[].members[]" \
--filter="bindings.members~\"serviceAccount:\"" \
--format="value(bindings.members.split(sep=\":\").slice(1))"

It's a little gnarly:

*

*--flatten breaks the bindings slice into easier to use chunks

*--filter filters the chunks to only include Service Accounts

*--format parses serviceAccount:foo into foo
gcloud provides decent filtering and formatting but, if you'd prefer a more general-purpose tool like jq, then:
FILTER='
  .bindings[].members[]
  |select(. | startswith("serviceAccount:"))
  |.[15:]
'

gcloud projects get-iam-policy ${PROJECT} \
--format="json" \
| jq -r "${FILTER}"

Explanation:

*

*.binding[].members[] for these objects

*select(. | startswith("serviceAccount:")) selects the serviceAccount:

*.[15:] strips the serviceAccount: (15) leaving the account email


text:
Q: barnyard2 for snort permission denied I installed barnyard2 for snort, but when i run command below this error appear.
[root@localhost snort]# barnyard2 -c /etc/snort/barnyard2.conf -d /var/log/snort/ -f snort.log -w /etc/snort/bylog.waldo /etc/snort/gen-msg.map /etc/snort/sid-msg.map -C /etc/snort/classification.config
Running in Continuous mode

    --== Initializing Barnyard2 ==--
Initializing Input Plugins!
Initializing Output Plugins!
Parsing config file "/etc/snort/barnyard2.conf"

+[ Signature Suppress list ]+
----------------------------
+[No entry in Signature Suppress List]+
----------------------------
+[ Signature Suppress list ]+

Barnyard2 spooler: Event cache size set to [2048]
ERROR: Can not get write access to logging directory "/var/log/barnyard2". (directory doesn't exist or permissions are set incorrectly or it is not a directory at all)
Fatal Error, Quitting..
Barnyard2 exiting

and permission is:
[root@localhost snort]# ls -l /var/log/barnyard2
-rwxrwxrwx. 1 root root 0 Aug 14 16:35 /var/log/barnyard2

in this link this problem was solved but i don't understand how ...
https://forums.freebsd.org/threads/barnyard2-start-service-error.51378/

A: It looks like directory flag is missing there. The error message says
ERROR: Can not get write access to logging directory "/var/log/barnyard2". (directory doesn't exist or permissions are set incorrectly or it is not a directory at all)

Probably the last case of /var/log/barnyard2 being not a directory at all might apply.
Backup the file and try creating a directory /var/log/barnyard2 with permissions 640 and corresponding ownership.
EDIT: As long as you do not know the contents of /var/log/barnyard2, rename or move the file to some place ( as root 'mv /var/log/barnyard2 /var/log/barnyard2.old'). Restarting barnyard2 now could help, it might create the directory with appropriate permissions by itself. Otherwise as root type 'mkdir /var/log/barnyard2' and then set permissions by typing 'chmod 640 /var/log/barnyard2'. Additionally check the user under which barnyard2 is running by typing 'ps -u | grep "barnyard2"'. Then find the appropriate group to that user by typing 'groups <user>' and then set the ownership of the directory to the corresponding user by typing 'chown <user>:<group> /var/log/barnyard2'.

A: '/var/log/barnyard2' should be the log directory. In your case it is a file. So, delete the file and create a directory instead. Here are the steps. Enter the commands as a root user.
rm /var/log/barnyard2
mkdir /var/log/barnyard2


text:
Q: Windows/Linux Dual Boot Error: "Failed to open \EFI\ubuntu\grubx64.efi - Not Found" I am a Windows 11 user and I have been using linux via ubuntu dual boot. The dual boot has been working wonderfully for months, until one day it stopped working for seemingly no reason. When I boot up the computer, I do not get to choose ubuntu/windows thru grub, instead I get the following error message on my boot up screen:
Failed to open \EFI\ubuntu\grubx64.efi - Not Found
Failed to load image \EFI\ubuntu\grubx64.efi:Not Found
start_image() returned Not Found, falling back to default loader
Failed to open \EFI\ubuntu\grubx64.efi - Not Found
Failed to load image \EFI\ubuntu\grubx64.efi:Not Found
start_image() returned Not Found

As of right now, I can access my default windows OS, but I can't access the linux portion of my computer at all. I tried a couple things that other people have been suggesting on other forums. I already went into BIOS and disabled secure boot, and I also made sure that ubuntu is at the top of the boot order. None of this has worked for me. When ubuntu is at the top of the boot order, I can't even access windows either, the computer just shows me a black screen.
I tried running the boot-repair, and I had a problem with this as well. I accessed linux with a usb, and I ran the boot-repair commands on terminal. I chose the "recommended repair" option but the repair system got stuck, showing me a message that says "Applying changes. This may require several minutes..." I left it on but hours but I was not able to complete boot repair, never getting past this message. So basically not even the boot-repair program seems to be functioning properly.
Is there any way to fix this situation? Like I said earlier, I was using windows/linux dual-boot fine for months, I just don't know why this happened, nor how to fix it. Please let me know if you need anymore information from me. Here is the BootInfo summary link that I acquired through the Boot-repair system:
https://paste.ubuntu.com/p/fhzNxsRxgq/

A: I was able to fix this error using the solution here:
Failed to open \EFI\BOOT\grubx64.efi - Not Found (Dual Boot Ubuntu with Windows 10)
The commands I ran were:
sudo mount -tvfat /dev/nvme0n1 /mnt
sudo cp /cdrom/EFI/BOOT/grubx64.efi /mnt/EFI/ubuntu/

Now everything is working fine, thank goodness.

A: Restore Dual Boot Menu Using the System Configuration Tool:

*

*Press Win+R to open Run.

*Type msconfig and click OK to open the System Configuration utility.

*Here, open the Boot tab.

*Select the OS that is not set as default and click the Set as default button.


text:
Q: Tracking particles with ImageFeatureTrack I am currently trying to track little dots in a series of the following images:

However, some of the dots disappear and reappear all the time. As soon as a dot is not linked by ImageFeatureTrack, no new track is generated at a later time, so eventually no tracks remain.
I am able to write a more sophisticated tracking algorithm, but before I do that I was wondering if one can modify ImageFeatureTrack to not only track particles visible in the first image, but also new ones that might appear later.


text: Q: How to synchronize multiple local MySql databases with live server mysql database We have multiple instances of same MySql db running locally and if any change to the local db, it should reflect to the live Mysql Database and vice versa


text:
Q: Serialize same level object from Many to many field I have to serialize spare instance from spare variety many to many field.
Models.py
class SpareVariety(models.Model):
  quality = models.ForeignKey(Quality, max_length=255, on_delete=models.CASCADE, null=True, blank=True)

  variety_name = models.CharField(max_length=255, null=True, blank=True)
  property = models.ForeignKey(SpareProperty, null=True, blank=True, on_delete=models.CASCADE)
  purchase_price = models.PositiveIntegerField(help_text="in INR", blank=True, null=True)
  retail_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
  dealer_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
  stock_available = models.PositiveIntegerField(blank=True, null=True,default=True)
  spare_costing = models.ForeignKey(SpareCosting, on_delete=models.CASCADE, blank=True, null=True)
  spare_discount = models.ForeignKey(Discount, on_delete=models.CASCADE, blank=True, null=True)
  is_available = models.BooleanField(default=False)
  date_added = models.DateTimeField(auto_now=True)
  date_updated = models.DateTimeField(auto_now_add=True)

class Spare(models.Model):
  product = models.ForeignKey(Product, on_delete=models.CASCADE)
  spare_variety = models.ManyToManyField(SpareVariety, related_name='spare_varieties', null=True, blank=True)
  name = models.CharField(max_length=255, help_text="Enter the name of spare (Ex:Display, Speakers)")
  type = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE)
  date_added = models.DateTimeField(auto_now=True)
  date_updated = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return '%s - %s' % (self.product.name, self.name)

Serialize the spare model from spare variety serializer
serializers.py
class SpareVarietySerializer(serializers.HyperlinkedModelSerializer):
  spare_costing= SpareCostingSerializer(many=False, read_only=False)
  spare_discount = DiscountSerializer(many=False, read_only=False)
  quality = QualitySerializer(many=False, read_only=False)
  property = SparePropertySerializer(many=False, read_only=False)
  spare_name = serializers.CharField(read_only=True, source="spare.name")
  class Meta:
    model = SpareVariety
    fields = ['id','quality','variety_name','purchase_price','spare_name','retail_price','property', 'dealer_price', 'stock_available','spare_costing','spare_discount','is_available', 'date_added', 'date_updated',]


text:
Q: Share data:image on facebook API share_open_graph So I have the following code -
      const canvas = jQuery(`#canvasId`);

      const facebookShare = jQuery(`#share`);

      facebookShare.on("click", () => {
        FB.ui({
          method: 'share_open_graph',
          action_type: 'og.shares',
          action_properties: JSON.stringify({
              object: {
                  'og:url': "sitename.com",
                  'og:title': title,
                  'og:image': canvas.toDataURL("image/png")
              }
          })
        }, function(response){});
      });

Which should share the image of the canvas on the fb share button click, but the facebook is returning me an error message

Object Invalid Value: Object at URL
  'http://sitename.com/#share'
  of type 'object' is invalid because the given value
  'data:image/png;base64,...................' for property
  'og:image:url' could not be parsed as type 'url'.

Any ideas how to fix that? I would need to retrieve a shareable image from the canvas and use it in the share window.


text:
Q: Connecting REST WebService to MySQL database I want to create a REST WebService which is connected to a MySQL database. But I got stuck at a point and don´t really know how to get further.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SimpleRESTServer.Models;
using MySql.Data;

namespace SimpleRESTServer
{
    public class PersonPersistance
    {

        private MySql.Data.MySqlClient.MySqlConnection conn;

        public PersonPersistance()
        {
            string myConnectionString;
            myConnectionString = "server=127.0.0.1;uid=Local Instance MySQL80; pwd=;database=employeedb";
            try
            {
                conn = new MySql.Data.MySqlClient.MySqlConnection();
                conn.ConnectionString = myConnectionString;
                conn.Open();
            }
            catch (MySql.Data.MySqlClient.MySqlException ex)
            {

            }

        }
        public long savePerson(Person personToSave)
        {
            String sqlString = " INSERT INTO tblpersonnel (FirstName, LastName) VALUES ('"+ personToSave.FirstName + "','" + personToSave.LastName + "')";}
            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn);
            cmd.ExecuteNonQuery();
            long id = cmd.LastInsertedId;
            return id;
    }

}

So my problem is that in the savePerson function something doesn´t work. When I write 'sqlString' and 'conn' ind the MySqlCommand part, it always get underlined red. I don´t really know what´s wrong.
I listend to this guys tutorial: https://youtu.be/LpySuvYPMZQ
I hope somebody can help me.
Thanks for your help in advance!

A: You are closing the method at the sqlString variable. Just after the semi colon you have a closing curly braces.


text: Q: Whenever I switch from another window to Google Chrome, my mouse stutters for a few seconds Whenever I switch from another window to Google Chrome, my mouse stutters/lags for a few seconds. I have tried restarting my computer and installing updates for windows and graphics card, but this didn't help. Not sure what is causing this, but it is really slowing down my productivity. Please help


text:
Q: react-native-svg-charts Areachart renders an extra bottom line I am using react-native-svg-charts to render some charts. In my case i use area chart (see image below). When the last data entries have same values, there is a bottom line appearing

Here is how i render the area chart
<AreaChart style = {{height: '100%', width: '100%' }} data = {Object.values(chartData)} curve={shape.curveBasis}
           svg={{ fill: 'url(#gradient)', stroke: 'blue', fillOpacity: 0.8, scale: 1.002, strokeWidth: 0 }}
           contentInset={{ top: scaleHeight(10), bottom: scaleHeight(10) }} animate >
   <Gradient/>
</AreaChart>

The code for Gradient is as follows
 const Gradient = ({ index }) => (
        <Defs key={index}>
            <LinearGradient id={'gradient'} x1={'0%'} y={'0%'} x2={'0%'} y2={'100%'}>
                <Stop offset={'0%'} stopColor="blue" stopOpacity={1}/>
                <Stop offset={'100%'} stopColor="white" stopOpacity={1}/>
            </LinearGradient>
        </Defs>
    )


text:
Q: Images upload in the wrong order I am aware it's an old script (an old way of doing things). The script works, however, the images do not upload in the right order. I am not exactly sure but it looks to me they upload from last to first instead of from first to last. What makes it do that?
if (count($_FILES['pic']['tmp_name']))
{
    $ipval = ipval();
    $uploaderror = 0;
    $uploadcount = 0;
    $errorMessages = array();
    foreach ($_FILES['pic']['tmp_name'] as $k=>$tmpfile)
}
if ($tmpfile)
{
    $thisfile = array("name"=>$_FILES['pic']['name'][$k],
    "tmp_name"=>$_FILES['pic']['tmp_name'][$k],
    "size"=>$_FILES['pic']['size'][$k],
    "type"=>$_FILES['pic']['type'][$k],
    "error"=>$_FILES['pic']['error'][$k]);
    if ($_FILES['pic']['size'][$k] > $pic_maxsize*1000)
    {
        $errorMessages[] = $thisfile['name'] . " - " . $lang['ERROR_UPLOAD_PIC_TOO_BIG'];
        $uploaderror++;
    }
    elseif (!isValidImage($thisfile))
    {
        $errorMessages[] = $thisfile['name'] . " - " . $lang['ERROR_UPLOAD_PIC_BAD_FILETYPE'];
        $uploaderror++;
    }
    else
    {
        $newfile = SaveUploadFile($thisfile, "{$path_escape}{$datadir['adpics']}", TRUE, $images_max_width, $images_max_height);
        if($newfile)
        {
            $sql = "INSERT INTO $t_adpics
            SET adid = $adid,
            picfile = '$newfile'";
            mysql_query($sql);
            if (mysql_error())
            {

                ...

A: If by "order" you mean the order that you selected the images in a multiple file input, you cannot rely on that order being consistent on the back end. It varies by browser and server: does multiple upload follow the same order of uploading in which we select the images?
If you are always seeing the order reversed, perhaps you need to change some code in the script that serves them up (ASC instead of DESC).
One way you could keep the order consistent is by sending another variable to the server on upload that contains an array of the file names in order, then base your INSERT order off of that array, not the order of the $_FILES array.


text:
Q: scatter chart is not rendering properly I'm using fusioncharts library. I am not able to find what's wrong with data which I'm sending for scatter chart.
Demo - JSFiddle
{
    "chart": {
        "animation": 0,
        "yaxisname": "OAE (%)",
        "xaxisname": "Week",
        "xaxismaxvalue": 54,
        "xaxisminvalue": 0,
        "showregressionline": "1",
        "regressionlinethickness": "2",
        "regressionLineColor": "008ee4",
        "bgcolor": "FFFFFF",
        "canvasborderthickness": "1",
        "canvasbordercolor": "CCCCCC",
        "showalternatehgridcolor": "0",
        "divlineColor": "#FFFFFF",
        "showLegend": "1",
        "showValues": "1"
    },
    "categories": [{
        "verticallinecolor": "c7c7c7",
        "category": [{
            "label": "46",
            "x": "46",
            "showverticalline": "1"
        }, {
            "label": "47",
            "x": "47",
            "showverticalline": "1"
        }, {
            "label": "48",
            "x": "48",
            "showverticalline": "1"
        }, {
            "label": "49",
            "x": "49",
            "showverticalline": "1"
        }, {
            "label": "50",
            "x": "50",
            "showverticalline": "1"
        }, {
            "label": "51",
            "x": "51",
            "showverticalline": "1"
        }, {
            "label": "52",
            "x": "52",
            "showverticalline": "1"
        }, {
            "label": "53",
            "x": "53",
            "showverticalline": "1"
        }, {
            "label": "01",
            "x": "01",
            "showverticalline": "1"
        }, {
            "label": "02",
            "x": "02",
            "showverticalline": "1"
        }, {
            "label": "03",
            "x": "03",
            "showverticalline": "1"
        }, {
            "label": "04",
            "x": "04",
            "showverticalline": "1"
        }]
    }],
    "dataset": [{
        "seriesname": "Target",
        "color": "93cc1a",
        "regressionLineColor": "93cc1a",
        "showValues": "0",
        "anchorradius": "0",
        "anchorSides": "8",
        "regressionLineThickness": "5",
        "anchorBorderColor": "2A612D",
        "anchorBgColor": "93cc1a",
        "data": [{
            "y": "40%",
            "x": "46"
        }, {
            "y": "40%",
            "x": "47"
        }, {
            "y": "40%",
            "x": "48"
        }, {
            "y": "40%",
            "x": "49"
        }, {
            "y": "40%",
            "x": "50"
        }, {
            "y": "40%",
            "x": "51"
        }, {
            "y": "40%",
            "x": "52"
        }, {
            "y": "40%",
            "x": "53"
        }, {
            "y": "40%",
            "x": "01"
        }, {
            "y": "40%",
            "x": "02"
        }, {
            "y": "40%",
            "x": "03"
        }, {
            "y": "40%",
            "x": "04"
        }]
    }, {
        "seriesname": "OAE",
        "color": "008ee4",
        "anchorradius": "5",
        "anchorSides": "7",
        "anchorBorderColor": "008ee4",
        "anchorBgColor": "008ee4",
        "data": [{
            "y": "29.73",
            "x": "46"
        }, {
            "y": "100.36",
            "x": "47"
        }, {
            "y": "69.37",
            "x": "48"
        }, {
            "y": "55.55",
            "x": "49"
        }, {
            "y": "64.4",
            "x": "50"
        }, {
            "y": "135.43",
            "x": "51"
        }, {
            "y": "55.02",
            "x": "52"
        }, {
            "y": "NA",
            "x": "53"
        }, {
            "y": "NA",
            "x": "01"
        }, {
            "y": "73.36",
            "x": "02"
        }, {
            "y": "8.28",
            "x": "03"
        }, {
            "y": "137.91",
            "x": "04"
        }],
        "dashed": "1"
    }]
}

You can see there are space in between the chart X-axis. Also I want that chart should plot X-axis as I'm passing in categories object. Why it's automatically sorted.

A: In the fiddle, if you check the minimum value for x-axis ranges from 01-04 and max values from 46 to 52.
Since, there isn't any labels in between 04 and 46, the space in-between is empty. The chart actually is plotted from 01 to 52, the space in between where there is no value or labels will not be skipped.
You can achieve what you want using label.  Its just a work around.
Updated Fiddle
"categories": [{
   "verticallinecolor": "c7c7c7",
      "category": [{
         "label": "46",
          "x": "0",
          "showverticalline": "1"
       }, {
          "label": "47",
          "x": "1",
          "showverticalline": "1",
       } //......


text:
Q: Status of VideoCapture object in OpenCV I have encapsulated the OpenCV VideoCapture class into a class of my own and am trying to initialize it from a video file on disk. The .isOpened() function returns true, but the frames I read later on are empty.

*

*If the VideoCapture can't read frames, why is it reporting being open?

*How can I further inspect the status of the VideoCapture object to find out why it's not reading frames?

Here is a tiny excerpt. Init() later throws an error because the frames read by camera_.read() are empty. Better scroll through to the code at the bottom, it exemplifies the problem better.
Camera::Camera(int target_width, int target_height, std::string filename)
    : target_width_(target_width),
      target_height_(target_height),
      camera_(filename)
{
    if (!camera_.isOpened()){
        cerr << "Failed to open video file" << endl;
        exit(EXIT_FAILURE);
    }
    camera_.read(frame_full_);
    if (frame_full_.empty()){
       cerr << "Failed to read from video file" << endl;
       exit(EXIT_FAILURE);
    }
    Init();
}

EDIT:
So, reading from an actual webcam works fine, it is the code above (reading from a file by filename) that returns empty frames.
EDIT2:
So—as suggested by Mhd.Tahawi—my whole problem can be summarized by the code below:
cv::VideoCapture cap("/Users/Me/Projects/whatev/some_video__640x360.avi");
cv::Mat test;

if (cap.isOpened()){
    cap.read(test);
    if (test.empty()) {
        std::cout << "BRO DO YOU EVEN CAPTURE?" << std::endl;
    }
}

A: I suspect codec problems - your code looks fine.
On a Mac, use brew install opencv --with-ffmpeg .
(But double check if you really have a the correct filepath, even though it shouldn't say that it is open). If you are on windows you need "\" in your path.


text:
Q: angular change pseudo element style by condition I need to change :before style by condition
I try to use the https://stackoverflow.com/a/37902154/13739803 solution but not work
my code is:
.sender:before {
              content: "";
              width: 0px;
              height: 0px;
              position: absolute;
              border-left: 15px solid $otaghakPinkLight;
              border-right: 15px solid transparent;
              border-top: 15px solid $otaghakPinkLight;
              border-bottom: 15px solid transparent;
              right: -16px;
              top: 0px;
              visibility: var(--porcentaje-visibility);
}

html code:

test

I want to visible or hide :before by condition

A: Does this variable needs to be placed in scss? If it can be moved into .ts file, I'd suggest to add conditional class in your template:
[class.sender--visible]="showAvatar"

Then you need to modify your existing .scss class, adding visibility: hidden and create a new one, which will be:
.sender.sender--visible::before {
    visibility: visible;
}