text:
Q: NSTask /bin/echo: /bin/echo: cannot execute binary file I am making an OS X App that requires running an shell script. Here are my swift code:
func runTask(arguments: [String]) {
    output.string = ""

    task = NSTask()
    task.launchPath = "/bin/bash"
    task.arguments = arguments;

    errorPipe = NSPipe()
    outputPipe = NSPipe()

    task.standardError = errorPipe
    task.standardOutput = outputPipe

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didCompleteReadingFileHandle(_:)), name: NSFileHandleReadCompletionNotification, object: task.standardOutput!.fileHandleForReading)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didCompleteReadingFileHandle(_:)), name: NSFileHandleReadCompletionNotification, object: task.standardError!.fileHandleForReading)

    errorPipe.fileHandleForReading.readInBackgroundAndNotify()
    outputPipe.fileHandleForReading.readInBackgroundAndNotify()

    task.launch()
}

func didCompleteReadingFileHandle(sender: NSNotification) {
    let data: NSData = sender.userInfo![NSFileHandleNotificationDataItem] as! NSData;
    let string = NSString(data: data, encoding: NSUTF8StringEncoding)!
    // The output property is a NSTextView object
    output.string?.appendContentsOf(String(string))
}

Now I tried calling the runTask method:
runTask(["/bin/echo", "1234"])

It says the following error:
/bin/echo: /bin/echo: cannot execute binary file

Now I went back into Terminal and typed in echo 1234 it runs perfectly without any trouble, now how do you get this to work? Thanks.

A: bash has three main modes of operation:

*

*If you pass it -c "some command string", it'll execute that command string.

*If you pass it a file path as an argument, it'll read commands from that file and execute them (i.e. execute the file as a shell script).

*If you don't pass it any arguments, it'll read and execute commands from standard input.
Since you passed it the arguments "/bin/echo" and "1234", it's assuming you want mode 2, so it tries to read shell commands from /bin/echo, and fails. I'm not clear on exactly what you're trying to achieve, but I see several options that might be relevant:

*

*If you're trying to execute a binary (e.g. /bin/echo), just execute that directly without using bash at all:
task.launchPath = "/bin/echo"
task.arguments = ["1234"]

*If you need to execute a command string (i.e. if you need the shell to parse it before executing it, so e.g. wildcards get expanded, or there's more than one command, or...), use bash -c:
task.launchPath = "/bin/bash"
task.arguments = ["-c", "/bin/echo 1234; ls *"]

*If you need to execute an actual script, i.e. a file with shell commands in it, then leave runTask alone, but pass it an actual script:
runTask(["/path/to/script", "scriptarg", "another argument"])

A: You're executing /bin/bash /bin/echo which doesn't work in Terminal.app either.
Remove /bin/bash
task.launchPath = "/bin/echo"
...
runTask(["1234"])


text:
Q: Google Two-way factory authentication PHP I want to have a Google Authenticator for my website (PHP) / 2FA.
What I exactly want:

*

*For the login page: username, password and (if enabled) GAuth (6 numbers).

*In profile settings a person can scan the QR code in his Google Authenticator app and enable/disable the GAuth.

*I do NOT want to use the google login button, just the 6 number authentication.

Info: It's a game website where people can register their account, which means every QR code is personalized to one user.
Question:

*

*I have been searching the web a lot on how to implement this AND how to generate a QR code, but I have not found a useful tutorial. How can I implement this API?

I've installed composer https://github.com/google/google-api-php-client, but now I'm stuck.

A: Although the app is Google's, what you are looking for is not an API from google. What you need is a TOTP php class.
Here is one (quite old) that you can use: https://www.idontplaydarts.com/static/ga.php_.txt

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i reset anything after commit? I need to commit a folder, then reset anything else to the remote state and push the commit.
If I would do
git commit
git reset --hard
git push

then the git reset --hard would destroy the commit, right?
how can I achieve it?

A: after performing a commit, you can safely do
git push

This will only push the commits that you made. Any unstaged or untracked changes will remain locally, you don't need to remove them.
Suppose you really want to remove them for another reason; to remove all the unstaged changes (warning: those changes will be lost!) you can do:
git checkout -- :/

if you have any untracked changes; and you don't want them to show up, you can either

*

*remove those files

*put them in the .gitignore file.


text:
Q: how to repeat same values as first row for entire dataframe and append with other dataframes I have multiple dataframes with different shape (length). I have to combine them as one.
For example,
df1:

version   Col1   Col2
1.0.0     234    456

df2:
ID    Col1_df2   Col2_df2   Col3_df2
1     aaaa       dfgr       1234
2     bbbb       njogn      7890
3     cccc       gmhlj      3456

df3:
Col1_df3    Col2_df3   Col3_df3
qwe         dfg        dffd

Firstly , I would like to look for maximum length dataframe which is df2 here . that many times , records have to be repeated for df1 and df3 . Then combine all of them in one dataframe.
final_df
version   Col1    Col2   ID  Col1_df2   Col2_df2   Col3_df2   Col1_df3   Col2_df3  Col3_df3
1.0.0     234    456     1     aaaa       dfgr       1234     qwe         dfg        dffd
1.0.0     234    456     2     bbbb       njogn      7890     qwe         dfg        dffd
1.0.0     234    456     3     cccc       gmhlj      3456     qwe         dfg        dffd

I am thinking of something like this:
1. look for maximum length of dataframe ,here it is len(df2).
2. loop through other dataframes in this range and repeat the rows .
3. append all the files into one.

I am trying to loop througn using set_index and stack but I am missing something.
Can anyone please help me ?

A: I was able to accomplish this using pd.merge() and ffill()
df_merge = pd.merge(df1, df2, left_index=True, right_index=True, how = 'outer')
df_merge = pd.merge(df_merge, df3, left_index=True, right_index=True, how = 'outer')
df_merge = df_merge.ffill()
df_merge

A: Here is my sample code. You can try
df1_extend = pd.concat([df1]*int(df2.shape[0]//df3.shape[0]), ignore_index=True)
df3_extend = pd.concat([df3]*int(df2.shape[0]//df3.shape[0]), ignore_index=True)
final_df = pd.concat((df1_extend, df2, df3_extend), axis=1)

EDIT
if df_1.shape[0]=1 and df_3.shape[0]=1, you can do it faster
final_df = pd.concat((df1, df2, df3), axis=1)
final_df.ffill()

A: You can try using
final_df = pd.concat([df1,df2,df3],axis=1)

And then doing a ffill like this
final_df.ffill(axis = 0)

That oughta fill the na values and make sure you get equal values for each shaped columns

A: Here is one approach, which is to introduce a key column in all DF and then merging them together
df1['key'] = 1
df2['key'] = 1
df3['key'] = 1

df1.merge(df2, on='key').merge(df3, on='key')

version Col1 Col2   key     ID  Col1_df2    Col2_df2    Col3_df2    Col1_df3    Col2_df3    Col3_df3
0   1.0.0 234 456   1       1   aaaa       dfgr     1234    qwe     dfg     dffd
1   1.0.0 234 456   1       2   bbbb       njogn    7890    qwe     dfg     dffd
2   1.0.0 234 456   1       3   cccc       gmhlj    3456    qwe     dfg     dffd


text:
Q: cocoa/iPad How do I keep a UIButton clickable when its alpha == 0? When I set a UIButton's alpha to 0, it behaves as if it isn't enabled. I've checked and, even though the button does remain enabled (though invisible (but not hidden, I checked that as well)), it ceases to work.
Is there any way to keep it clickable even when its alpha is 0?

A: UIButtonStyle set to "custom". And instead of alpha 0, you need to set background to 'clear color'.

A: Try to put another UIButton on top of it with it's UIButtonStyle set to "custom" and just leave it as it is, except of adding your IBAction to it.


text:
Q: How to get list of keys based on a field in value from Kafka state store I have a state store which is defined like below:
StoreBuilder<KeyValueStore<String, DataDocument>> indexStore = Stores.keyValueStoreBuilder(
            Stores.persistentKeyValueStore("Data"), Serdes.String(), DataDocumentSerDes.dataDocumentSerDes())
            .withLoggingEnabled(changelogConfig);

I have processor defined which will process source topic and write it to this state store.
I have a use-case to get list of keys based on a field in the DataDocument which is the value in the state store. Is there a way I can achieve it?
One way I can think of is get all the keys and then perform filter. But it's going to be expensive as we iterate all keys always.
ReadOnlyKeyValueStore<String, DataDocument> roStore = streams.store(StoreQueryParameters.fromNameAndType("Data",
            QueryableStoreTypes.<String, DataDocument>keyValueStore()));
    KeyValueIterator<String, DataDocument> kvItr = roStore.all();
    while(kvItr.hasNext()) {
        if(kvItr.next().value.isField()) {
            //Store to a list
        }
    }

Another approach is create state stores for all fields which has to be queryable with field as key and list of keys. But this is not scalable.
Is there a better way I can achieve it with kafka topology?


text:
Q: MOSFET threshold voltage calculation across temperature using normalised values I have an application in which the gate voltage is 300mV to turn off the MOSFET which is active when on. The data sheet for the ZVN3310F specifies the threshold at 0.8V-2.4V at room temperature. A normalised threshold graph is also presented. I want to know whether the MOSFET would remain off across temperature so my question is;
1/ Would one use the temperature or the normalised threshold voltages in deriving the percentage difference in the threshold voltage across the temperature of interest?
2/ Once the percentage difference has been derived, for say a temperature of -40 degrees C, would we use the worst-case threshold tolerance of 0.8V, given that the threshold voltage is inversely proportional to temperature and multiply the percentage difference by that value?
3/ Similarly, at 125 degrees C say, would we calculate the threshold using the maximum threshold specified or stick with the minimum value of 0.8V as the worst case minimum?
e.g.
(125 Deg C - 25 Deg C) / 125 Deg C = 0.8 x 0.8V = 0.64V
Is this correct for the expected threshold voltage at 125 deg C?

A: You cannot get absolute values of VGS(th) from normalized data.
From the data sheet:

The variation of VGS(th) with temperature tells you the you can expect a drop in VGs(th) of 10% from 25 -125 degC. That gives you 0.1% per degC
It tells you little about an individual device VGS(th) since the range is from 0.8 min to 2.4 V max.
To be sure you are putting devices with an absolute range of VGS(th) over temperature you'd need to buy binned devices, which cost more.


text:
Q: redirect user from page to another with a message I have 2 PHP pages, 'users list' and 'create a user'. if I create new user successfully the page will redirect me to 'users list' page and show the new created user. the question is how I can make 'user list' page show message like 'new user was created successfully' when redirecting the client to 'user list' page?

A: Solution 1: Use a query parameter
You can redirect to something users-list.php?create=successful. Then testing the presence (and eventually value) of the create GET param can tell when a message has to be displayed.
Solution 2: Store it in the session
Another solution would be to store something in the user's session, that will tell you in the other page that a message has to be displayed. This something could be the message itself or just a flag.

A: I hope Its Solve Your Problem..
<?php
$msg="create new user successfully ";
header('users-list.php?msg='.$msg);
?>


text:
Q: how to validate dynamic created element in jquery without using plugin here i have created dynamic elements after clicking its adding one row.but how to validate it without plugin.
var cnt = 1;
$("#anc_add").click(function() {
    cnt++;
    $("input[id=rows]").val(cnt);
    $('#tbl1 tr').last().after('
<select name="'+cnt+'1" id="'+cnt+'1" class="Exp"><option value="0" >Select Expenses Type</option></select>	<textarea name="'+cnt+'2"></textarea>	<input type="text" name="'+cnt+'3" id="'+cnt+'3"  onkeypress="return isNumberKey(event)">
');
    element_id=cnt+'1';/*alert(element_id);*/
    $.ajax({
        url: "../../modal/system_operator/get_companyexpenses_type.php",
        dataType: "html",
        type: 'POST',
        success:function(json) {
            var result = jQuery.parseJSON(json);
            length=result.len;
            /*alert(length);*/
            for(k=1;k<=length;k++) {
                $('#'+element_id+' option').last().after('<option value="'+eval("result.row"+k+".company_expenses_type_id")+'">'+eval("result.row"+k+".company_expenses_type")+'</option>');
            }
            $('select[name="'+element_id+'"]').rules('add', {required:true});
        }
    });
});

A: I assume by without plugin means you do not use jquery.validate or some other plugin to validate your input control values.
Then try the following snippet
$(document).on('blur','#form_id input,#form_id select', function(){
   // write your validation logic here
});

The above code says that all (including dynamic) input,select controls within #form_id element will call the function on blur event.


text:
Q: How to automatically logout of chrome on exit? I don't want my google account to be logged in to chrome when I launch chrome. Is there a way to do that? I've tried searching for queries like "chrome logout on exit", but so far I haven't found anything that works.
Related: https://productforums.google.com/forum/#!topic/chrome/oH7VZGY5h9w

A: All you need to do is install this extension:
AUTO LOGOUT
It will logout on normal exits, but will not do so during an abrupt system shutdown like Win7 does.

There is a lot of info about this on Google HERE


text:
Q: $\sum a_n$ converges conditionally and $\sum b_n$ converges absolutely, then will $\sum a_nb_n$ converge absolutely? Suppose $\sum a_n$ converges conditionally and $\sum b_n$ converges absolutely, then will $\sum a_nb_n$ converge absolutely?
I know that $\sum|a_n|$ does not converge while $\sum a_n$  does
and that $\sum|b_n|$ does converge, and also that $\lim_{n \to \infty} |a_nb_n|=0$ but I'm not sure how to proceed from here.

A: $|a_{n}|<1$ eventually and so $|a_{n}b_{n}|\leq|b_{n}|$ eventually, but $\displaystyle\sum|b_{n}|<\infty$, then so is $\displaystyle\sum|a_{n}b_{n}|<\infty$.


text:
Q: Why is iframe.contentWindow == null? I use the following code to dynamically create an iframe.
var iframe_jquery = $("<iframe>")
    .addClass("foo")
    .appendTo(container); // container is a jQuery object containing a <div> which already exists

Then, I want to access its contentWindow, but it's null:
var iframe = iframe_jquery.get(0);
if (iframe){ // iFrame exists
    console.log(iframe.contentWindow); // Prints "null"
    var doc = iframe.contentWindow.document; // NullpointerException
}

So I thought: "Maybe the iframe isn't ready yet?" So I tried:
iframe_jquery.ready(function(){
    var iframe = iframe_jquery.get(0);
    console.log(iframe.contentWindow); // Prints "null"
    var doc = iframe.contentWindow.document; // NullpointerException
});

Same result.
What's wrong?

A: Depending on the browser, accessing the document or an <iframe> may vary.
Here is an example of how to handle it:
if (iframe.contentDocument) // FF Chrome
  doc = iframe.contentDocument;
else if ( iframe.contentWindow ) // IE
  doc = iframe.contentWindow.document;

A: I had this problem last week while playing with iframes (building an rtf editor), and yeah it's not ready yet.
I thought if I put it in a .ready(), it would work, but .ready() is when the DOM is ready, not when the iframe has loaded its contents, so I ended up wrapping my code with jQuery .load().
So try this:
$(function () {
    $("#myiframe").load(function () {
        frames["myframe"].document.body.innerHTML = htmlValue;
    });
});

Hope this helps

A: You can also make a function that will be executed when the iframe has finished loading by setting it's onload attribute.

A: The problem is that your <iframe> won't be "real" until it's really added to the actual DOM for the page.  Here is a fiddle to demonstrate..

A: Bookmarklet version
Just out of curiosity I thought I'd put this together. Remembering that iframes and load events don't play well together on different browsers (mainly older, falling apart, should-be-dead browsers)... plus not being entirely sure how jQuery gets around this problem... my brain decided that this would be better supported (whether it is or not is neither here nor there):
$(function(){
  /// bind a listener for the bespoke iframeload event
  $(window).bind('iframeload', function(){
    /// access the contents of the iframe using jQuery notation
    iframe.show().contents().find('body').html('hello');
  });
  /// create your iframe
  var iframe = $('<iframe />')
        /// by forcing our iframe to evaluate javascript in the path, we know when it's ready
        .attr('src', 'javascript:(function(){try{p=window.parent;p.jQuery(p).trigger(\'iframeload\');}catch(ee){};})();')
        /// insert the iframe into the live DOM
        .appendTo('body');
});

The reason for taking this approach is that it is normally far better to trigger your load event from inside the iframe itself. But this means having a proper document loaded in to the iframe, so for dynamic iframes this is a little tedious. This is kind of a mixture between having a document loaded, and not.
The above works on everything I have tested so far - and yes you are correct - it is a little ridiculous, non-future-proof and propably other things that have negative connotations ;)
One positive thing I'll say about this post is that introduces the use of .contents() to access the document of the iframe, which is at least a little bit useful...


text:
Q: Update columns in UItable with timer in Matlab I have a UItable with the 4 first columns that are being updated every 1 second with some external logger data. I would like to have a 5 column with a logical select column, so I could select which instruments to display.
The problem is the timer update the 'data' of the UItable, and I can't find a way to only update the first 4 columns without updating the last (5th) one.
Does anyone would have a solution ?
Thanks for your help.


text:
Q: ASP Net Core 7.0 SPA Configuration - does not load static files on sub URL paths I am trying to configure Asp Net Core 7.0 to host Vanilla JS SPA APP. It seams to work when navigating to single paths, but on sub paths, it does not load the static files folder containing the Views and the main.js which is the client side routing for the JS SPA APP. It loads only index.html without the main.js and the Views, thus the app can't route to the Home view because the main.js file and the "Home.js" view are missing, actually the whole folder with the static files is not loaded.
I think that it is something to do with the Program.cs file and the configuration.
So what I am trying to do is to load the Home View when there is wrong path.
Ex. On single path as http://localhost:5109/Login works

Program.cs
using Microsoft.Extensions.FileProviders;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}
else
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

// SPA
app.UseDefaultFiles();
app.UseStaticFiles();

app.UseRouting();

app.MapFallbackToFile("index.html");
app.Run();

Thanks in advance.

A: The problem was the missing "/" efore the static
Before:

Now:

The whole index.html:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

        Register
        Log In
        Home

It works now on sub paths.


text:
Q: Where is this System.MissingMethodException occurring? How can I tell? I am a newbie to ASP.NET MVC (v2), and I am trying to use a strongly-typed view tied to a model object that contains two optional multi-select listbox objects.  Upon clicking the submit button, these objects may have 0 or more values selected for them.
My model class looks like this:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace ModelClasses.Messages
{
    public class ComposeMessage
    {
        public bool is_html { get; set; }
        public bool is_urgent { get; set; }
        public string message_subject { get; set; }
        public string message_text { get; set; }
        public string action { get; set; }
        public MultiSelectList recipients { get; set; }
        public MultiSelectList recipient_roles { get; set; }

        public ComposeMessage()
        {
            this.is_html = false;
            this.is_urgent = false;
            this.recipients = new MultiSelectList(new Dictionary<int, string>(), "Key", "Value");
            this.recipient_roles = new MultiSelectList(new Dictionary<int, string>(), "Key", "Value");
        }
    }
}

My view looks like this:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ModelClasses.Messages.ComposeMessage>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Compose A Message
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

 Compose A New Message:

<%= Html.ActionLink("\\Home", "Index", "Home") %><%= Html.ActionLink("\\Messages", "Home") %>
<% using (Html.BeginForm())
 { %>
<fieldset>
<legend>Message Headers</legend>

Subject:
<%= Html.TextBox("message_subject")%>
<%= Html.ValidationMessage("message_subject")%>

Recipient Users:
<%= Html.ListBox("recipients") %>
<%= Html.ValidationMessage("selected_recipients")%>

Recipient Roles:
<%= Html.ListBox("recipient_roles") %>
<%= Html.ValidationMessage("selected_recipient_roles")%>

Urgent?
<%= Html.CheckBox("is_urgent") %>
<%= Html.ValidationMessage("is_urgent")%>
</fieldset>
<fieldset>
<legend>Message Text</legend>
<%= Html.TextArea("message_text") %>
<%= Html.ValidationMessage("message_text")%>
</fieldset>
<input type="reset" name="reset" id="reset" value="Reset" />
<input type="submit" name="action" id="send_message" value="Send" />
<% } %>

<%= Html.ActionLink("\\Home", "Index", "Home") %><%= Html.ActionLink("\\Messages", "Home") %>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Scripts" runat="server">
</asp:Content>

I have a parameterless ActionResult in my MessagesController like this:
    [Authorize]
    public ActionResult ComposeMessage()
    {
        ModelClasses.Messages.ComposeMessage FormData = new ModelClasses.Messages.ComposeMessage();
        Common C = (Common)Session["Common"];
        FormData.recipients = new MultiSelectList(C.AvailableUsers, "Key", "Value");
        FormData.recipient_roles = new MultiSelectList(C.AvailableRoles, "Key", "Value");
        return View(FormData);
    }

...and my model-based controller looks like this:
    [Authorize, AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ComposeMessage(ModelClasses.Messages.ComposeMessage FormData)
    {
        MyUserClass CurrentUser = (MyUserClass )Session["CurrentUser"];
        Common C = (Common)Session["Common"];
    //... (business logic)
    return View(FormData);
    }

Problem is, I can access the page fine before a submit.  When I actually make selections and press the submit button, however, I get:

    Server Error in '/' Application.
    No parameterless constructor defined for this object.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
    Source Error:
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    Stack Trace:
    [MissingMethodException: No parameterless constructor defined for this object.]
    System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
    System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
    System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
    System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
    System.Activator.CreateInstance(Type type) +6
    System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +307
    System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +495
    System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +473
    System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45
    System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +642
    System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +144
    System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +95
    System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2386
    System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +539
    System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +447
    System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +173
    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +801
    System.Web.Mvc.Controller.ExecuteCore() +151
    System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +105
    System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +36
    System.Web.Mvc.<>c__DisplayClass8.b__4() +65
    System.Web.Mvc.Async.<>c__DisplayClass1.b__0() +44
    System.Web.Mvc.Async.<>c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +42
    System.Web.Mvc.Async.WrappedAsyncResult1.End() +140
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +36
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677678
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
    Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082

This error shows up before I can trap it.  I have no idea where it's choking, or what it's choking on.  I don't see any point of this model that cannot be created with a parameterless constructor, and I can't find out where it's dying... Help is appreciated, thanks.
-Jeremy

A: Strongly typing recipients and recipient_roles as MultiSelectList may be causing this problem. Try the following simple mod to your code:
public object recipients { get; set; }
public object recipient_roles { get; set;


text: Q: Automorphisms of a finite group stabilizing a subgroup. Suppose I have a group $G$ and a subgroup $H< G,$  where $|H| = k, |G| = k l.$ Let $A_H < Aut(G) = \{\phi \left| \phi(H) = H\right.\}.$ The question is: is there any decent (where you can define "decent" in your favorite way) universal upper bound on the index of $A_H$ in $Aut(G)$ in terms of $k, l?$


text:
Q: How to move bubble with value of input type range Currently I'm trying to figure out how to move bubble which contains current value of input type="range" element. I mean my goal is when I move slider-thumb , the bubble will move with it too ,so the bubble will be always above the slider-thumb.
I've tried to google it,but all I can find was how to style that div to look like bubble and some small code to display that exactly above slider thumb ,but It does not work for me and I can't really figure it out how to make it work or how to calculate the position where to display it.
Code that i've found
const
    range = document.getElementById('range'),
    rangeV = document.getElementById('rangeV'),
    setValue = ()=>{
        const
            newValue = Number( (range.value - range.min) * 100 / (range.max - range.min) ),
            newPosition = 10 - (newValue * 0.2);
        rangeV.innerHTML = `<span>${range.value}</span>`;
        rangeV.style.left = `calc(${newValue}% + (${newPosition}px))`;
    };
document.addEventListener("DOMContentLoaded", setValue);
range.addEventListener('input', setValue);

I'm working in React ,and the result of this will be BMI calculator app.
Has anybody encountered this type of problem? I'll be glad for every advice or explanation . Thank you.
codesandbox link : https://codesandbox.io/s/suspicious-tereshkova-ujk45?file=/src/Components/Button.js

A: Although it is not advisable to use vanilla javascript for uncontrolled components in react. See React useRef. But you already have the solution. All you need do is put that snippet in a useEffect() hook in Range.js.
In Range.js
function Range(props) {

  useEffect(() => {
    const
    range = document.getElementById('range'),
    rangeV = document.getElementById('rangeV'),
    setValue = ()=>{
        const
            newValue = Number( (range.value - range.min) * 100 / (range.max - range.min) ),
            newPosition = 10 - (newValue * 0.2);
        rangeV.innerHTML = `<span>${range.value}</span>`;
        rangeV.style.left = `calc(${newValue}% + (${newPosition}px))`;
    };
document.addEventListener("DOMContentLoaded", setValue);
range.addEventListener('input', setValue);
  }, [])

...//rest of Range.js

See https://jsfiddle.net/7wmgspvq/3/


text:
Q: How to find and replace by reading xml node value? Following is my XML value.
<Components>
    <Component>
        <FullName>CoreEnvironment</FullName>
        <ShortName>CoreEnv</ShortName>
    </Component>
    <Component>
        <FullName>Excel Addin 2007</FullName>
        <ShortName>Excel_07</ShortName>
    </Component>
</Components>

If user pass Full Name of a component then corresponding short name should be displayed. I am able to read a particular node in xml using powershell. But in this case if one FullName node is found then corresponding shortname node should be displayed. I am unable to figure out the logic for this.

A: [xml]$xml="<Components>
    <Component>
        <FullName>CoreEnvironment</FullName>
        <ShortName>CoreEnv</ShortName>
    </Component>
    <Component>
        <FullName>Excel Addin 2007</FullName>
        <ShortName>Excel_07</ShortName>
    </Component>
</Components>"

$test="Excel Addin 2007"

$xml.Components.Component |% { if( $_.fullname -match $test) { write-host  $_.ShortName}}

A: Similar to Kayasax's answer but using XPath
[xml] $xml = "<Components>
    <Component>
        <FullName>CoreEnvironment</FullName>
        <ShortName>CoreEnv</ShortName>
    </Component>
    <Component>
        <FullName>Excel Addin 2007</FullName>
        <ShortName>Excel_07</ShortName>
    </Component>
</Components>"

$param = "Excel Addin 2007"

$xml.SelectNodes('//Component') | Where-Object {$_.FullName -eq "$param" } | Select-Object -ExpandProperty ShortName


text:
Q: If f is differentiable at a, then f is Lipschitz of order 1 at a If f is differentiable at a, then f is Lipschitz of order 1 at a.
[attempt]
lim_x->a {(f(x)-f(a))/(x-a)} = f'(a).
hmm if I can somehow change this to f'(a)(x-a)=f(x)-f(a). And let C be a constant such that C > f'(a) then I would be done...
Any help?
Side-Note: Last time I asked something about Lipschitz at a point, I was met with comments asking what this meant, so I'm assuming this isn't standard usage? Anyways what I meant by "f is Lipschitz of order 1 at a": f is Lipschitz continuous at a if there exists a neighborhood of a such that |f(y)−f(x)|< C|y−x|.
EDIT: I have understood that lim_x->a {(f(x)-f(a))/(x-a)} = f'(a) can be changed to  f'(a)(x-a)=f(x)-f(a) in a nhbd of a. And we're looking for Lipschitz at point a, so we only consider the nbhd of a anyways. So I think that should complete the proof (coupled with user15464's idea. thanks for the help!

A: Choose an exponent $u$ and define a function $f$ by $f(0)=0$ and, for $x\ne0$,
$$
\color{red}{f(x)=x^u\cos(\pi x^{-1})}.
$$
Then $f$ is continuous at $0$ (and everywhere else) if $u>0$ and $f$ is differentiable at $0$ (and everywhere else) if $u>1$. But $x=(2n)^{-1}$ and $y=(2n+1)^{-1}$ for any positive integer $n$ yields $|x-y|=x-y=\Theta(n^{-2})$ while $\cos(\pi x^{-1})=+1$ and $\cos(\pi y^{-1})=-1$ hence $|f(x)-f(y)|=x^u+y^u=\Theta(n^{-u})$.
Finally, for every exponent $u$ in $(1,2)$, $f$ is differentiable everywhere and is not what you call Lipschitz continuous at $0$.


text:
Q: Where is my iframe in the published web application/sidebar? I've been running into various errors when trying to control the window in DOM of my published web app and addon sidebar.

*

*window.location returns a vague  unknown url like n-rysutduudd.google-usercontent.com instead of my published web app url script.google.com/[SCRIPT_ID]/exec

*Attempts to redirect my published web-app to a new url fails
window.location.href=www.google.com

*Forms in web app, when submitted  redirects to blank page.
After researching, I figured  this is due to the web content being served in a iframe. The documentation doesn't show much except that the webapp is sandboxed in a iframe.
Relevant documentation I've researched:

*

*https://developers.google.com/apps-script/migration/iframe

*https://developers.google.com/apps-script/guides/html/restrictions
Some of the relevant questions I've looked into:

*

*window.location.href = window.location.href returning a blank page

*Google script web app goes blank page after submit

*How to stop redirected URL from being masked?
My specific question is: Where exactly is my iframe window in the published web app or my add on sidebar?

A:               PUBLISHED WEB APP
+---------------------------------------------+
|              script.google.com              |
|                                             |<------- [#0] window.top The top frame
|                                             |
|     +---------------------------------+     |
|     |     *.googleusercontent.com     |<----+-------- [#1] Outer Sandboxed Iframe
|     |         sandboxFrame            |     |
|     |    +-----------------------+    |     |
|     |    |        /blank         |    |     |
|     |    |    userHtmlFrame      |    |     |
|     |    |                       |    |     |
|     |    |     Where the html    |<---+-----+-------- [#2] Inner Sandboxed Iframe
|     |    |    file you created   |    |     |
|     |    |       is loaded       |    |     |
|     |    |                       |    |     |
|     |    |                       |    |     |
|     |    |                       |    |     |
|     |    |                       |    |     |
|     |    |                       |    |     |
|     |    +-----------------------+    |     |
|     |                                 |     |
|     |                                 |     |
|     +---------------------------------+     |
|                                             |
|                                             |
|                                             |
+---------------------------------------------+

You're right. Most of the errors are due to  the iframe sandboxing done by Google. To answer your question,

*

*Your window is located in a iframe with id: userHtmlFrame with  it's src set to /blank.

*This frame is nested inside another frame with src: *.googleusercontent.com and id sandboxFrame.

*Finally, The sandboxFrame is nested inside the main frame: script.google.com
Notes:

*

*window in your  published app refers to the inner most frame.

*This inner most frame has it's own cookies, storage and most other attributes unique to a window.

*Unfortunately, this inner frame cannot be navigated elsewhere.

*All window navigation must be done on the outermost frame: script.google.com.  This is why the documentation asks you to set base or anchor's target to the top frame.

*Forms  without action are submitted to the inner frame /blank. Therefore, you're redirected to a blank page. The documentation states,

With IFRAME mode however HTML forms are allowed to submit, and if a form element has no action attribute specified it will submit to a blank page. Worse, the inner iframe will redirect to the blank page before the onclick handler has a chance to finish.

The solution is to add JavaScript code to your page that prevents the form elements from actually submitting, so that the click handlers have time to function

*

*The origin of your iframe userHtmlFrame is inherited from sandboxFrame and set to *.googleusercontent.com. For all intents and purposes(cors, whitelisting origins, fetch requests), this is the  effective origin.

*The sandboxFrame currently has the following  feature policy: allow
accelerometer *; ambient-light-sensor *; autoplay *; camera *; encrypted-media *; fullscreen *; geolocation *; gyroscope *; magnetometer *; microphone *; midi *; payment *; picture-in-picture *; speaker *; usb *; vibrate *; vr *

*

*Currently, It has the following sandbox attributes, which limit what you can  do to other frames:

allow-downloads allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation

*

*The outer windows/other windows can be  referenced using window.top or window.parent or window.opener from the inner frame. But, There are multiple restrictions imposed due to same origin policy. Cross origin access is limited mostly. Of particular note would be the window.postMessage, which allows communication between frames.

            SIDEBAR/MODAL DIALOG
+---------------------------------------------+
|              docs.google.com                |
|  +--------------------------------------+   |<------- [#0] window.top The top frame
|  |      /macros/.../iframedAppPanel     |<--+-------- [#1] Frame1 Same origin
|  |  +---------------------------------+ |   |
|  |  |     *.googleusercontent.com     |<|---+-------- [#2] Outer Sandboxed Iframe
|  |  |         sandboxFrame            | |   |
|  |  |    +-----------------------+    | |   |
|  |  |    |        /blank         |    | |   |
|  |  |    |    userHtmlFrame      |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |     Where the html    |<---+-|---+-------- [#3] Inner Sandboxed Iframe
|  |  |    |    file you created   |    | |   |
|  |  |    |       is loaded       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    |                       |    | |   |
|  |  |    +-----------------------+    | |   |
|  |  |                                 | |   |
|  |  |                                 | |   |
|  |  +---------------------------------+ |   |
|  |                                      |   |
|  +--------------------------------------+   |
|                                             |
+---------------------------------------------+

All the above notes for web app stands true also for webcontent published using HtmlService in sidebar or modal dialogs. However,

*

*There is a extra nested layer of iframe here.

*The allow-top-navigation is  missing from the sandbox attributes. Therefore, It is not possible to change/navigate the top frame(docs.google.com) here.

Changelog:

*

*Sep 1, 2021: allow-top-navigation is removed and allow-top-navigation-by-user-activation is added instead. Security  for the end user is increased at the cost of convenience for the developers.


text:
Q: Query about disadvantage of Reentrant locks over synchronized block I am reading comparison between Reentrant locks and synchronization blocks in java. I am going through the various resources on internet. One disadvantage that I discovered using Reentrant locks over synchronization blocks is that in previous one, you have to explicitly use try finally block to call unlock method on the acquired lock in the finally block, as it might be possible that your critical section of code might throw exception and it can cause big trouble, if thread doesn't releases the lock, While in the latter one, JVM itself takes care of releasing the lock in case of exception.
I am not very much convinced with this disadvantage, because it's not a big deal to use try finally block.As we have been using it for long time for ex(stream closing etc). Can somebody tell me some other disadvantages of Re-entrant locks over synchronized blocks?

A: A ReentrantLock is a different tool for a different use-case. While you can use both for most synchronization issues (that's what they are made for), the come with different advantages and disadvantages.
Synchronized is at most simple: you write synchronized and that's it. With modern JVMs it is reasonable fast, but has the drawback that it puts all threads that try to enter a synchronized block on hold, whether they actually need to or not. If you use synchronized too often, this can dramatically reduce the speed of multi-threading, worst case down to a point where single-threaded execution would have been faster.
As threading issues only occur if someone is writing while someone else is reading/writing the same data section, programs often run into the problem, that they could theoretically run without synchronization, because most threads just read, but there is this one occasional write, which enforces the synchronized block. This is what the Locks were made for: you have a finer control over when you actually synchronize.
The basic ReentrantLock allows - beside a fair parameter in the constructor - that you can decide when you release the lock, and you can do it at multiple points, so when it suits you best. Other variations of it like the ReentrantReadWriteLock allow you to have many unsynchronized reads, except if there is a write. The downside is that this is solved in Java code, which makes it noticeably slower than the "native" synchronized block. That said: you should only use it, if you know that the optimization gain using this lock is bigger than the loss.
Under normal situations you can only tell the difference in speed if you actually monitor it, by running a profiler to check the speed before and afterwards in a sophisticated way.

A: synchronized is almost always faster for low or minimal contention, because it allows JVM to perform some optimizations such as biased locking, lock elision and others. Here are some more details how it works:
Let's assume some monitor is held by thread A, and thread B requests this monitor. In that case monitor will change its state to inflated. Saying short, it means that all threads trying to acquire this monitor, will be put to wait set at OS level, which is quite expensive.
Now, if thread A released monitor before thread B requested it, so-called rebias operation will be performed by cheap (on modern CPU) compare-and-swap operation.
Let's take a look at ReentrantLock now. Each thread calls lock() or lockInterruptibly() method cause locking attempt done via CAS operation.
Conclusion: in low contention cases, prefer synchronized. In high contention cases, prefer ReentrantLock. For all cases between, it is hard to say for sure, consider performing benchmarks to find out which solution is faster.


text:
Q: unable to call Azure Service Bus from Python Trying to run the hello world example to put something on the queue, create a queue ... anytime I call azure I get an error.
Here is the code:
from azure.servicebus import *

bus_service = ServiceBusService(service_namespace='testtest', account_key='my_access_token', issuer='my_issuer')
bus_service.create_topic('mytopic')

Here is the error I get back:
$ /c/Python27/python pythontest.py
Traceback (most recent call last):
  File "pythontest.py", line 4, in <module>
    bus_service.create_topic('mytopic')
  File "c:\Python27\lib\site-packages\azure\servicebus\servicebusservice.py", line 1
42, in create_topic
    request.headers = _update_service_bus_header(request, self.account_key, self.iss
uer)
  File "c:\Python27\lib\site-packages\azure\servicebus\__init__.py", line 185, in _u
pdate_service_bus_header
    request.headers.append(('Authorization', _sign_service_bus_request(request, acco
unt_key, issuer)))
  File "c:\Python27\lib\site-packages\azure\servicebus\__init__.py", line 192, in _s
ign_service_bus_request
    return 'WRAP access_token="' + _get_token(request, account_key, issuer) + '"'
  File "c:\Python27\lib\site-packages\azure\servicebus\__init__.py", line 233, in _g
et_token
    connection.send(request_body)
  File "c:\Python27\lib\site-packages\azure\http\winhttp.py", line 313, in send
    self._httprequest.send(request_body)
  File "c:\Python27\lib\site-packages\azure\http\winhttp.py", line 198, in send
    ctypes.memmove(safearray.pvdata, request, len(request))
WindowsError: exception: access violation writing 0x0000000000000000

It always gives me the same error whether I put something on a queue or create a queue, create a topic, send message to a topic, etc.
any ideas?

A: Is this the exact code you are using? At least the account_key is not right, it should be in base64 format
bus_service = ServiceBusService(service_namespace='testtest', account_key='my_access_token', issuer='my_issuer')

A: This is an issue with the azure library when used from 64-bit Python.
The changes to make it work are small, so I have listed them here for you.  The fix will be pushed to github + pypi shortly as well.
Make the following changes to azure/http/winhttp.py:
Add c_size_t to the import statement
from ctypes import c_void_p, c_long, c_ulong, c_longlong, c_ulonglong, c_short, c_ushort, c_wchar_p, c_byte, c_size_t

Replace CoInitialize(0) with
CoInitialize(None)

Replace the Com related APIs section with this
_ole32 = oledll.ole32
_oleaut32 = WinDLL('oleaut32')
_CLSIDFromString = _ole32.CLSIDFromString
_CoInitialize = _ole32.CoInitialize
_CoInitialize.argtypes = [c_void_p]

_CoCreateInstance = _ole32.CoCreateInstance

_SysAllocString = _oleaut32.SysAllocString
_SysAllocString.restype = c_void_p
_SysAllocString.argtypes = [c_wchar_p]

_SysFreeString = _oleaut32.SysFreeString
_SysFreeString.argtypes = [c_void_p]

_SafeArrayDestroy = _oleaut32.SafeArrayDestroy
_SafeArrayDestroy.argtypes = [c_void_p]

_CoTaskMemAlloc = _ole32.CoTaskMemAlloc
_CoTaskMemAlloc.restype = c_void_p
_CoTaskMemAlloc.argtypes = [c_size_t]


text:
Q: Add dynamic Text update to pyQt script I would like to add the ability to update a data field (number) on my current pyqt script. I was trying to use "addLabel" but I can't update their content dynamically.
Any suggestion on how to make it? I am using addPlot function to create the plots which will be processing some data from a UDP packet. In some cases, I want to just show the value dynamically. Not sure what will be the best widget to use for this purpose?
Current script:
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
import struct
from struct import pack, unpack
import socket

app = QtGui.QApplication([])

data = []
data_throttle = []
data_brake = []
data_steering = []
data_state = []
data_error = []

pg.setConfigOption('background', (0,0,0))
#pg.setConfigOption(antialias=True)
win = pg.GraphicsWindow()
win.resize(500,200)
p1 = win.addPlot(title="Sequence")
p1.setWindowTitle('Sequence')
p1.setRange(QtCore.QRectF(0, 0, 100, 150))
#p1.setLabel('bottom', 'Packet', units=' ')
p1.showGrid(True, True)

p2 = win.addPlot(title="Throttle")
p2.setWindowTitle('Throttle')
p2.setRange(QtCore.QRectF(0, 0, 100, 255))
#p2.setLabel('bottom', 'Packet', units=' ')
p2.showGrid(True, True)

p3 = win.addPlot(title="Brake")
p3.setWindowTitle('Brake')
p3.setRange(QtCore.QRectF(0, 0, 100, 255))
#p3.setLabel('bottom', 'Packet', units=' ')
p3.showGrid(True, True)

p4 = win.addPlot(title="Steering")
p4.setWindowTitle('Steering')
p4.setRange(QtCore.QRectF(0, -1, 100, 2))
#p4.setLabel('bottom', 'Packet', units=' ')git
p4.showGrid(True, True)

p5 = win.addPlot(title="Vehicle State")
p5.setWindowTitle('Vehicle State')
p5.setRange(QtCore.QRectF(0, 0, 100, 10))
#p5.setLabel('bottom', 'Packet', units=' ')
p5.showGrid(True, True)

p6 = win.addPlot(title="Errors")
p6.setWindowTitle('Errors')
p6.setRange(QtCore.QRectF(0, 0, 100, 10))
#p6.setLabel('bottom', 'Packet', units=' ')
p6.showGrid(True, True)

top_label = "Percent"
bottom_label = "85"
l_labels = win.addLayout(col=1, colspan=1)
l_labels.addLabel(top_label, row=0, col=0, rowspan=1, colspan=1, size='30pt', bold=True)
l_labels.addLabel(bottom_label, row=2, col=0, rowspan=4, colspan=1, size='200pt', color='606060')
l_labels.setContentsMargins(0, 0, 0, 100)

curve = p1.plot(pen='r')
curve2 = p2.plot(pen='b')
curve3 = p3.plot(pen='g')
curve4 = p4.plot(pen='y')
curve5 = p5.plot(pen='r')
curve6 = p6.plot(pen='b')

# Receive UDP packets transmitted by a broadcasting service

RECEIVE_IP = ''
RECEIVE_PORT = 2337
RECEIVE_ADDRESS = (RECEIVE_IP, RECEIVE_PORT)

recv_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recv_socket.bind(RECEIVE_ADDRESS)
JOY_CODE = '=HBBBhHQQB'
ACK_CODE = '=HHBBHBBhBqB'

ptr = 0
lastTime = time()
fps = None
def update():
    global recv_socket, fScale
    global curve, data, data_throttle, data_brake, data_steering, ptr, p, lastTime, fps, data_state, data_error
    recv_message, address = recv_socket.recvfrom(22)
    message_id, ack_payload, ack_seq, vehicle_state, vehicle_speed, throttle, brake, steering, error, timestamp, checksum =  struct.unpack(ACK_CODE, recv_message)
    #data = throttle
    data.append(ack_seq)
    data =  data[-100:]

    data_throttle.append(throttle)
    data_throttle =  data_throttle[-100:]

    data_brake.append(brake)
    data_brake =  data_brake[-100:]

    data_steering.append(steering / 32768)
    data_steering =  data_steering[-100:]

    vehicle_state = vehicle_state & 0x07
    data_state.append(vehicle_state)
    data_state = data_state[-100:]

    data_error.append(error)
    data_error = data_error[-100:]

    #print(throttle)
    #print("got data", data, "  ", lastTime, "\n")
    # print data
    #curve.setData(fScale,data,_callSync='off')
    curve.setData(data,_callSync='off')
    curve2.setData(data_throttle,_callSync='off')
    curve3.setData(data_brake,_callSync='off')
    curve4.setData(data_steering,_callSync='off')
    curve5.setData(data_state, _callSync='off')
    curve6.setData(data_error, _callSync='off')
    bottom_label = vehicle_state

    now = time()
    dt = now - lastTime
    lastTime = now

    app.processEvents()  ## force complete redraw for every plot
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)

## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

A: I was able to figure the solution by using TextItem inside a Plot
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
import struct
from struct import pack, unpack
import socket

app = QtGui.QApplication([])

data = []
data_throttle = []
data_brake = []
data_steering = []
data_state = []
data_error = []

pg.setConfigOption('background', (0,0,0))
#pg.setConfigOption(antialias=True)
win = pg.GraphicsWindow()
win.resize(1600,1000)
p1 = win.addPlot(title="Sequence",row=0, col=1)
p1.setWindowTitle('Sequence')
p1.setRange(QtCore.QRectF(0, 0, 100, 150))
p1.showGrid(True, True)

p2 = win.addPlot(title="Throttle",row=0, col=2)
p2.setWindowTitle('Throttle')
p2.setRange(QtCore.QRectF(0, 0, 100, 255))
p2.showGrid(True, True)

p3 = win.addPlot(title="Brake",row=0, col=3)
p3.setWindowTitle('Brake')
p3.setRange(QtCore.QRectF(0, 0, 100, 255))
p3.showGrid(True, True)

p4 = win.addPlot(title="Steering",row=1, col=1)
p4.setWindowTitle('Steering')
p4.setRange(QtCore.QRectF(0, -1, 100, 2))
p4.showGrid(True, True)

p5 = win.addPlot(title="Vehicle State",row=1, col=2)
p5.setWindowTitle('Vehicle State')
p5.setRange(QtCore.QRectF(0, 0, 100, 10))
p5.showGrid(True, True)

p6 = win.addPlot(title="Errors",row=1, col=3)
p6.setWindowTitle('Errors')
p6.setRange(QtCore.QRectF(0, 0, 100, 10))
p6.showGrid(True, True)

p7 = win.addPlot(title="Counter",row=0, col=4)
p8 = win.addPlot(title="Counter",row=1, col=4)

font=QtGui.QFont()
font.setPixelSize(300)

anchor = pg.TextItem()
anchor.setText("0")
anchor.setColor(QtGui.QColor(255, 255, 255))
anchor.setFont(font)

anchor1 = pg.TextItem()
anchor1.setText("0")
anchor1.setColor(QtGui.QColor(255, 255, 255))
anchor1.setFont(font)

p7.addItem(anchor)
p7.showGrid(False, False)
p7.hideAxis('bottom')
p7.hideAxis('left')

p8.addItem(anchor1)
p8.showGrid(False, False)
p8.hideAxis('bottom')
p8.hideAxis('left')

curve = p1.plot(pen='r')
curve2 = p2.plot(pen='b')
curve3 = p3.plot(pen='g')
curve4 = p4.plot(pen='y')
curve5 = p5.plot(pen='r')
curve6 = p6.plot(pen='b')

# Receive UDP packets transmitted by a broadcasting service

RECEIVE_IP = ''
RECEIVE_PORT = 2337
RECEIVE_ADDRESS = (RECEIVE_IP, RECEIVE_PORT)

recv_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
recv_socket.bind(RECEIVE_ADDRESS)

JOY_CODE = '=HBBBhHQQB'

ACK_CODE = '=HHBBHBBhBqB'

ptr = 0
lastTime = time()
fps = None
def update():
    global recv_socket, fScale
    global curve, data, data_throttle, data_brake, data_steering, ptr, p, lastTime, fps, data_state, data_error
    recv_message, address = recv_socket.recvfrom(22)
    message_id, ack_payload, ack_seq, vehicle_state, vehicle_speed, throttle, brake, steering, error, timestamp, checksum =  struct.unpack(ACK_CODE, recv_message)
    #data = throttle
    data.append(ack_seq)
    data =  data[-100:]

    data_throttle.append(throttle)
    data_throttle =  data_throttle[-100:]

    data_brake.append(brake)
    data_brake =  data_brake[-100:]

    data_steering.append(steering / 32768)
    data_steering =  data_steering[-100:]

    vehicle_state = vehicle_state & 0x07
    data_state.append(vehicle_state)
    data_state = data_state[-100:]

    data_error.append(error)
    data_error = data_error[-100:]

    curve.setData(data,_callSync='off')
    curve2.setData(data_throttle,_callSync='off')
    curve3.setData(data_brake,_callSync='off')
    curve4.setData(data_steering,_callSync='off')
    curve5.setData(data_state, _callSync='off')
    curve6.setData(data_error, _callSync='off')

    #Updating Text Value
    anchor.setText(str(vehicle_state))
    anchor1.setText(str(vehicle_state))

    now = time()
    dt = now - lastTime
    lastTime = now
    app.processEvents()  ## force complete redraw for every plot

timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)

## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()


text:
Q: Drag event for nodes in Cytoscape.js I'm looking for an event that fires as a node is being dragged. I thought that tapdrag looked like what I wanted, but tapdrag fires whenever the mouse moves over the node only when the mouse button is not down (so the node's not being dragged, basically mouseover). I've tried several other events, but none seem to do what I need.
How can I fire an event as a node is being dragged? Specifically, I want to move another node while the first is being dragged, which I'd rather do without using a compound node.

A: Use the drag event.
The events are all listed and documented: http://js.cytoscape.org/#events/collection-events
You can manually .position() on the second node when the drag happens on the first node.
To set rules for node placement, like moving two nodes in lockstep, use the automove extension:
https://github.com/cytoscape/cytoscape.js-automove


text:
Q: Exception type: TaskCanceledException -On startup File -WebAPI We are facing very wired situation on the WEBAPI Project Created, the production we getting teh error on event Viewer window "
on the startup File we are implemented Microsoft Qwin , with the following code
var accessTimeOut = 60;
var allowInsecureHttp = false;
            if (ConfigurationManager.AppSettings["accessTokenTimeout"] != null)
                accessTimeOut = Int32.Parse(ConfigurationManager.AppSettings["accessTokenTimeout"]);
            var isHarbingerFlag = ConfigurationManager.AppSettings["IsHarbingerDev"];
            if (isHarbingerFlag != null && isHarbingerFlag == "true")
                allowInsecureHttp = true;

            var OAuthOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp = allowInsecureHttp,
                TokenEndpointPath = new PathString("/Token"),

                AccessTokenExpireTimeSpan = new TimeSpan(0, accessTimeOut, 0),
                Provider = new OwinsAuthorizationServerProvider(),
                RefreshTokenProvider = new RefreshTokenProvider(),
            };

            app.UseOAuthBearerTokens(OAuthOptions);
            app.UseOAuthAuthorizationServer(OAuthOptions);
            // app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //var properties = new AppProperties(app.Properties);
            //CancellationToken token = properties.OnAppDisposing;

            HttpConfiguration config = new HttpConfiguration();
            WebApiConfig.Register(config);

I am not sure what is wrong on the production peek hour my application start logging the error like : xception information:
Exception type: TaskCanceledException
Exception message: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.
Can anybody help me on this ?


text:
Q: What does "correctly noded" mean? I've never seen this term, and I'm wondering what it means, with regard to ST_Polygonize

NOTE: Input linework must be correctly noded for this function to work properly

A: this page helpfully shows some of the edge cases where this function would fail and return NULL. To summarise some examples...

*

*two linestring geometries which touch/cross at one point. but don't loop back on each other to touch/cross at another point

*two disjoint lines

*a single linestring which does't form a complete loop

or any case where the set/array of geometries doesn't form one or more polygons. Also, rounding/precision errors might come into play, and it may be that linestrings need to align in a consistent direction.
there may be other definitions of 'incorrectly noded' :)


text:
Q: How can I show fullscreen image from web using Intent on Android? Is it possible to show fullscreen image from web using Intent on Android?

A: Yes, you can use ImageView,
here is an example:
http://www.androidpeople.com/android-imageview-scaletype-example
You need to use ScaleType.FIT_XY

A: Currently i use something like this:
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/png");
startActivity(intent);


text:
Q: Equivalent of getCurrentUser().getUid() of a Google log in on Firebase I'm using something like this to get the UID from a Google logged in user on Firebase.
 private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        String idGoogle = account.getId();
}
....

But this is giving me some headaches because then I have to pass that String through intents. Isn't there a getCurrentUser().getUid() like when one use the email and password log in? Everytime I check on the documentation there's only instructions for email and password log in, but not how to handle google accounts when already logged in.


text:
Q: Picking out peaks that fit a pattern I've got data with time (seconds) on the x axis and intensity (in relative fluorescent units, or rfu) on the y-axis. It's generated by watching fragments of DNA pass a camera - the bigger the DNA fragment the bigger the time. There are 23 fragments of known size (in DNA base pair units, bp), and therefore there should be 23 peaks. As I know the size of the DNA fragments in bp, I want to recalibrate the x-axis from time (seconds) to base pairs (bp) using a linear model.
Unfortunately there is quite a lot of noise in the data that produces spurious peaks. The only way to confidently tell the true ones from the false ones is that the false ones don't fit the expected pattern in DNA base pairs.
I've provided data from one sample at this link in a data frame called demo. Unfortunately it's too large to paste below.
https://1drv.ms/t/s!AvBi5ipmBYfrhf0v_kvWuN2foLyBgg?e=RWfdXZ
I can pick out all the peaks as follows.
library(ggplot2)
library(ggpmisc)
ggplot(demo, aes(x=time, y=rfu)) +
geom_line(size=0.1) +
stat_peaks(col = "red", span=5, ignore_threshold=0.1) +
theme_bw()

However, these are the expected DNA fragment sizes (in bp):
ladder <- c(50, 75, 100, 125, 150, 200, 250, 300, 350, 400, 450, 475, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000)

And here is a plot with the correct peaks picked out:

Is there any way to get a peak finder such as stat_peak or ggpmisc:::find_peaks to take an pattern of peaks into account when selecting peaks to achieve the second plot??
Addendum:
The false peaks may be within the same rfu range as the true peaks, so peak height can't be used to exclude them (see example from a different sample below)

A: For the given data, we can isolate the peaks by looking for local maxima between 1000 to 6000. This identifies the 23 peaks.
I used the slider package to identify the maximum value within a 21 bp (time - 10 to time +10) range, and then excluded points outside the rfu range of 1000-6000 or which matched the point prior.
library(tidyverse); library(slider)
demo %>%
  mutate(peak = rfu == slider::slide(
    rfu, max, .before = 10, .after = 10) &
      rfu > 1000 & rfu < 6000 & rfu != lag(rfu)) %>%
  ggplot(aes(time, rfu, color = peak, alpha = peak)) +
  geom_point()

I explored whether it might be possible to find a brute-force "best fit", which might make this more automatic and robust to noise that is within the same ranges as the underlying signals. I'm sure it's possible, but it's more difficult than I expected, since the "time stretch" varies across the range, so a simple offset + scaling model with two parameters won't suffice. The "time stretch" between the ladder and the data varies gradually from a little over 10x (ie the 25 dif from 50 to 75 on ladder translates to 253 dif in data 1578 to 1831) at the start, to under 5x at the end.
In this case, it looks like a quadratic fit would probably do well, but that might not translate to other data that is time-distorted differently.

If the distortion were totally uniform between runs, it might be more useful to define the ladder with the distortion built-in, like the "ladder_scaled" column below. Then the question would be reduced to finding a single offset value with best fit to the data, in the case of your example +1528.
ladder_scaled <- tibble::tribble(
      ~ladder, ~ladder_scaled,
   50 ,          50,
   75 ,         303,
  100 ,         557,
  125 ,         811,
  150 ,        1068,
  200 ,        1580,
  250 ,        2104,
  300 ,        2630,
  350 ,        3159,
  400 ,        3684,
  450 ,        4204,
  475 ,        4451,
  500 ,        4705,
  550 ,        5203,
  600 ,        5683,
  650 ,        6143,
  700 ,        6574,
  750 ,        6983,
  800 ,        7357,
  850 ,        7701,
  900 ,        8010,
  950 ,        8283,
  1000,         8523
  )

If we can rely on consistent time alignment between runs, we can solve for the timing offset which provides the best alignment with the data, even if there are overlapping noisy peaks within our data. One tricky thing about this particular example is that the ladder "signature" is not very unique -- the spacing is similar between most steps on the ladder, so you get a decent fit in most lost functions even if you're offset by one or two "steps" of the ladder.
Here's one approach where I brute force the fit on a bunch of offset values. I am relying on the assumption (perhaps unwarranted) that the ladder has a consistent time length, and the only variable to solve for is time offset. I believe the problem becomes exponentially more difficult if this cannot be assumed.
To start with, I use a much wider range of plausible values which include 6 noisy peaks in addition to the 23 real ones:
demo %>%
  mutate(peak = rfu == slider::slide(
    rfu, max, .before = 10, .after = 10) &
      rfu > 500 & rfu < 30000 & rfu != lag(rfu)) -> demo_labels
# includes 29 "peaks": 23 real + 6 noisy

Then I cross with a range of possible offsets from 0:5000, and fuzzy join each peak to the possible ladder peaks that are within 200 time units. For each possible offset and peak, I pick the closest fit, and then for each possible offset, I pick the 23 closest fits. Finally, I plot the worst alignment for each offset value. This shows that in the original data, an offset of around 1528 provides the best fit. But a difficult thing about this particular "ladder signature" is that an offset of 1976, ~450 higher,  doesn't look tremendously worse by this measure, even though it's definitely wrong. So it probably will take some more domain knowledge to identify a better function than "worst fit" for picking good matches.
library(fuzzyjoin)
demo_labels %>%
  filter(peak) %>%
  crossing(offset = seq(0, 5000, by = 2)) %>%
  mutate(time_adj = time - offset) %>%
  distance_left_join(ladder_scaled,
                  by = c("time_adj" = "ladder_scaled"),
                  max_dist = 200) %>%
  mutate(time_error = time_adj - ladder_scaled) %>%
  group_by(offset, time_adj) %>%
  slice_min(abs(time_error)) %>%
  group_by(offset) %>%
  slice_min(abs(time_error), n = 23) %>%  ### pick the 23 best fits %>%
  summarise(worst_error = max(abs(time_error)),
            matching_peaks = n()) %>%
  arrange(worst_error) %>%
  ggplot(aes(offset, worst_error, alpha = matching_peaks == 23)) +
  geom_point()

A: Before plotting, doing some data manipulation to pull out the maximum value for each of the 23 DNA fragment groups with base R max function, and adding the max plot with additional geom_ layer for the max values.
Here is small reprex example that plots the max value for each group with "red".
data.frame(x = 1:9) %>%
     mutate(y = rep(LETTERS[1:3], c(3, 3, 3) )) %>%
     group_by(y) %>%
     mutate(max = max(x), .groups = "drop") %>%
ggplot(aes(x = y, y = x)) +
     geom_point() +
     geom_point(aes(x = y, y = max), col = "red")

A: I am able to id each pick for the 18 fragments. The code starts the time greater than 3000 seconds and removes the noise bellow 2000 rfu. The code id and gives pattern for each fragment, then extract the picks (maxs) for each fragmen.  Here are the codes and the plot.
library(tidyverse)
# identify/build pattern for each fragment (1,2,0)
df_1 <-
demo %>%
        # remove the noise
        filter(time > 3000, rfu >= 2000) %>%
        mutate(frag = ifelse(rfu >= 2900, 1, 0),
               lbl = ifelse(frag == 0, 1, 2))  %>%
        as_tibble() %>%
        mutate(lbl_z = lag(frag))

# grab the repeat pattern and  add incrmental unique labels
df_2 <-
df_1 %>%
     filter(frag == 1, lbl == 2, lbl_z == 0) %>%
     mutate(patrn  = 1:n(),
            patrn = paste0("a", "_",patrn))

# Extract each pick or maxes per group matching the picks on the plot
df_maxs <-
df_1 %>%
     left_join(df_2, by = c("time", "rfu")) %>%
     select(1:3,9) %>%
     tidyr::fill(patrn) %>%
     filter(frag.x == 1) %>%
     group_by(patrn) %>%
     mutate(maxs = max(rfu)) %>%
     inner_join(df_2)

# Viz
demo %>%
          as.tibble() %>%
          filter(time > 3000) %>% #18
ggplot(aes(x = time, y = rfu)) +
          geom_line() +
          geom_point(data = df_maxs, aes(x = time, y = maxs), col = "red") +
          geom_text(data  = df_maxs, aes(x = time, y = maxs, label = maxs), vjust = -1, col = "blue")


text:
Q: Fitting dictionary into normal distribution curve Here is the dictionary:
l= {31.2: 1,35.1: 4,39.0: 13,42.9: 33,46.8: 115,50.7: 271,54.6: 363,58.5:381,62.4:379,66.3:370,70.2:256,74.1: 47,78.0: 2}

So this means that 31.2 has occurred 1 time, 35.1 has occurred 4 times and so on.
I tried:
fig, ax = plt.subplots(1, 1)

ax.scatter(l.keys(), l.values)
ax.set_xlabel('Key')
ax.set_ylabel('Length of value')

Also I found mean and std by
np.mean([k for k in l.keys()])
np.std([k for k in l.keys()])

Is this the way to find mean and std for that data. I doubt that because it does not take into account of number of occurences of each data. I want to see the normal curve on this data. Also is there a way to know how often a value occurs. For example if I extend the curve to touch 0 on x axis , and if I want to know how many data points are involved for an occurrence of 0(can also be probability).

A: Here's a way to get the mean and std:
l= {31.2: 1,35.1: 4,39.0: 13,42.9: 33,46.8: 115,50.7: 271,54.6: 363,58.5:381,62.4:379,66.3:370,70.2:256,74.1: 47,78.0: 2}
ll=[[i]*j for i,j in zip(l.keys(),l.values())]
flat_list = [item for sublist in ll for item in sublist]
np.mean(flat_list), np.std(flat_list)

which prints (59.559194630872476, 7.528353520785996).
You could do a histogram with np.histogram(flat_list) to evaluate the frequency of each occurrence.

A: Here is a way to draw a normal gauss curve to fit the data:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats

l = {31.2: 1, 35.1: 4, 39.0: 13, 42.9: 33, 46.8: 115, 50.7: 271, 54.6: 363, 58.5: 381, 62.4: 379, 66.3: 370, 70.2: 256, 74.1: 47, 78.0: 2}
# convert the dictionary to a list
l_list = [k for k, v in l.items() for _ in range(v)]

fig, ax = plt.subplots(1, 1)

ax.scatter(l.keys(), l.values())
ax.set_xlabel('Key')
ax.set_ylabel('Length of value')

mu = np.mean(l_list)
sigma = np.std(l_list)

u = np.linspace(mu - 4 * sigma, mu + 4 * sigma, 100)
ax2 = ax.twinx()
ax2.plot(u, stats.norm.pdf(u, mu, sigma), color='crimson')
ax2.set_ylabel('normal curve')

plt.show()


text:
Q: What's the simplest way to bind a list of checkboxes to a list of checked values I have a list of AvailableItems that I want to display as a list of checkboxes, so that users can pick which items to generate, which are then stored in another list called ItemsToGenerate (my lists are actually just lists of strings).
Showing all available items with corresponding checkboxes is easy:
<ItemsControl ItemsSource="{Binding Path=AvailableItems}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

But now I need to bind each Checkbox.IsChecked property, to the fact that the item is in the ItemsToGenerate list. I thought of making a ListContainmentToBoolConverter like this:
IsChecked="{Binding Path=ItemsToGenerate,
            Converter={StaticResource ListContainmentToBoolConverter}}"

But that doesn't work because I'm missing a ConverterParameter to pass the value of each item, but I can't do that, because ConverterParameter does not support binding.
Any ideas?

A: I've found a solution to my problem.
I've changed my ItemsControl to a ListBox, and added a binding between the SelectedItems with my ItemsToGenerate collection using the technique described here. It basically allows me to synchronize any custom collection to ListBox.SelectedItems using a simple attached property.
<ListBox ItemsSource="{Binding AvailableItems}"
         Behaviors:MultiSelectorBehaviours.SynchronizedSelectedItems=
             "{Binding ItemsToGenerate}"
         SelectionMode="Multiple"
         Background="{x:Null}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}"
                      Margin="3"
                      IsChecked="{Binding RelativeSource=
                           {RelativeSource Mode=FindAncestor,
                            AncestorType={x:Type ListBoxItem}},
                           Path=IsSelected}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ListBox>

I'm still able to display this as I initially wanted (a list of checkboxes), by adding a data template to change each ListBoxItem to a checkbox and binding each Checkbox.IsChecked to ListBoxItem.IsSelected.
I had this pattern in so many places in my application that this is the ideal solution for me, because now I just need to specify one attached property, and the rest is all handled by the data bindings, and I don't need any additional code.

A: I honestly would create a list of objects containing both the string and a boolean indicating if it is checked.
With a little Linq you can generate your list of objects and bind it to itemSource  instead of binding the list of strings.
It will be simpler in the end, especially if you actually need to update something if the user is allowed to check/uncheck the checkboxes.
== update ==
in answer to the comment, my take on this because I'm not sure I understand what the actual problem would be: provided we have the full list (AvailableItems) and the list of selected items (ItemsToGenerate):
public class ItemEntry
{
  public string Name { get; set; }
  public bool IsSelected {get; set; }
}

...
_Items = from item in AvailableItems
            select new ItemEntry() {
                    Name = item,
                    IsSelected = ItemsToGenerate.contains(item)
                  }).ToList();

You can then bind your list like so, by exposing _Items as a property named Items:
<ItemsControl ItemsSource="{Binding Path=Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

You can at a later time select from _Items where IsSelected is true to get the selected items if you need to.
Also, if ItemsToGenerate can get big, you should create a HashSet of the values and use it in the query, that should make it faster if need be.


text:
Q: How can I convert my json object into postgres table I am trying to insert bulk data into postgres. So I have converted my data into json object and now I want to insert that data into a physical table the json object can contain over 100k records. So I want to do it dynamically by using postgres function. My question is how can I query my sample data as a table
This is the sample json data
[
  {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  },
  {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  },
 {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  }
]

A: You can use create a table (e.g.tab) with json column (e.g.jsondata) and by using json_array_elements() function :
create table tab as
with tab as
(
 select '[
  {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  },
  {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  },
 {
    "sequence": 123123.0,
    "Card number ": "12312qwe",
    "Tracking number": 1231233.0,
    "Expiry Date": 43741.0
  }
]'::json as jsondata
)
select js ->> 'sequence' as sequence, js ->> 'Card number ' as Cardnumber,
       js ->> 'Tracking number' as Trackingnumber, js ->> 'Expiry Date' as ExpiryDate
  from
  (
    select json_array_elements(jsondata) as js
      from tab
  ) q1

Demo


text:
Q: cannot setup apache 2.2 with mod_wsgi and python 3.3? This is error log when i'm trying to setup with Python 3.3, Apache 2.2 and use mod_wsgi-3.4.ap22.win32-py3.3.zip at http://www.lfd.uci.edu/~gohlke/pythonlibs/
 mod_wsgi (pid=4940): Target WSGI script 'C:/www/h.wsgi' cannot be loaded as Python module.
 mod_wsgi (pid=4940): Exception occurred processing WSGI script 'C:/www/h.wsgi'.
 Traceback (most recent call last):\r
   File "C:\\Python33\\Lib\\pkgutil.py", line 504, in find_loader\r
     return importlib.find_loader(fullname, path)\r
   File "C:\\Python33\\Lib\\importlib\\__init__.py", line 64, in find_loader\r
     loader = sys.modules[name].__loader__\r
 AttributeError: 'module' object has no attribute '__loader__'\r
 \r
The above exception was the direct cause of the following exception:\r
 \r
 Traceback (most recent call last):\r
   File "C:/www/h.wsgi", line 5, in <module>\r
     application = Flask(__name__)\r
   File "C:\\Python33\\lib\\site-packages\\flask\\app.py", line 331, in __init__\r
     instance_path = self.auto_find_instance_path()\r
   File "C:\\Python33\\lib\\site-packages\\flask\\app.py", line 622, in auto_find_instance_path\r
     prefix, package_path = find_package(self.import_name)\r
   File "C:\\Python33\\lib\\site-packages\\flask\\helpers.py", line 661, in find_package\r
     loader = pkgutil.get_loader(root_mod_name)\r
   File "C:\\Python33\\Lib\\pkgutil.py", line 482, in get_loader\r
     return find_loader(fullname)\r
   File "C:\\Python33\\Lib\\pkgutil.py", line 510, in find_loader\r
     raise ImportError(msg.format(fullname, type(ex), ex)) from ex\r
 ImportError: Error while finding loader for '_mod_wsgi_293471048e599ca28a13db229cd884c8' (<class 'AttributeError'>: 'module' object has no attribute '__loader__')\r

and Browser show "Internal Server Error".
I don't know why because when i'm trying to setup with Python 2.7, Apache 2.2 and mod_wsgi-3.4.ap22.win32-py2.7.zip, it's OK
Somebody help me, thank so much!
P.s:
httpd.conf settings
<VirtualHost *:80>
        ServerName webmaster@localhost
        WSGIScriptAlias / C:/www/h.wsgi
        <Directory "C:/www">
                Order allow,deny
                Allow from all
        </Directory>
</VirtualHost>

and my app
from flask import Flask

application = Flask(__name__)

@application.route('/')
def hello_world():
    return "Hello"

if __name__ == '__main__':
    application.run()

it's work okay when i change to python 2.7

A: I would suggest asking about this on the #pocoo IRC channel:

*

*http://flask.pocoo.org/community/irc/
as that is where the Flask developers are. Flask appears dependent on the __loader__ attribute of the module under Python 3.3, but mod_wsgi doesn't currently add one. It is possible Apache/mod_wsgi needs to start adding one due to how the new module importer works, but also not sure if Flask should be tolerant of it not existing.
Provides any details back here.

A: I encountered the same problem and it seems to be a problem related to Python 3.3 as the following patch indicates:
https://mail.python.org/pipermail/python-checkins/2014-March/128573.html
Updating to Python 3.4 seems to be an option. I also found this workaround, which seems to work for now:
http://librelist.com/browser//flask/2013/9/18/problem-debugging-flask-under-python-3-3/


text:
Q: Multiple HTTP POST over single socket I am trying to send multiple HTTP POST over single socket connection , but EPIPE broken once I read inputstream.
mBufferedWriter.write("POST " + "/base/mypath" + " HTTP/1.1" + "\r\n");
mBufferedWriter.write("Host: " + mIp + "\r\n");
mBufferedWriter.write("Content-Length: " + json.toString().length()"\r\n");
mBufferedWriter.write("Content-Type: application/json\r\n");
mBufferedWriter.write("Connection: Keep-Alive\r\n\r\n");
mBufferedWriter.write(json.toString() + "\r\n");
mBufferedWriter.flush();

My first POST will reach server. Am trying to achieve pipelining. Set keep-alive for socket also

A: HTTP Pipelining involves more than just re-using an existing connection (HTTP Keep-Alive).  Pipelining involves having multiple HTTP requests in flight over a single connection at the same time, where a client sends an HTTP request but does not wait for its response before sending the next HTTP request on the same connection.  Both client and server have to implement support for pipelining in order to use it effectively.  Even then, there are issues related to pipelining POST requests, so they should nver be pipelined.  HTTP Pipelining is discussed in RFC 2616 Sections 8.1.1 and 8.1.2.2.
If you are not actually implementing Pipelining, only Keep-Alive, then you have to pay attention to the server's Connection response header, as it tells you whether you are allowed to send a new HTTP request over the same connection or not.  For an HTTP 1.1 response, if the server sends a Connection: close header, then the socket is going to be closed by the server after it sends the response, so you will have to create a new connection before sending the next HTTP request.

A: You can use Apache HTTP client (http://hc.apache.org/httpcomponents-client-ga/) or http://developer.android.com/reference/org/apache/http/client/package-summary.html and set an Thread safe client connection manager.


text:
Q: Factoring and solving trinomials Has the problem of factoring (over the rationals) the general trinomial $ax^n+bx^k+c$ with $a,b,c\in\mathbb{Z}$, $n,k\in\mathbb{N}, n>k>1$ been solved?  By solved I mean a classification theorem which will either give the factors or give a certificate that it is irreducible.
One could ask the same question, but about finding expressions for the roots of a trinomial.  I am aware that long ago this problem was worked on, but I have been unable to find a modern treatment of this problem.
The question which actually motivates this one is: given a trinomial which factors, consider the number of terms in each of the factors.  Further, assume that the trinomial is not cyclotomic.  How many terms can the factors have?  [The cyclotomic case is conjectured to be special].
[Edit: clarified that I am interested in this special case, not the general case, where the algorithms of M. van Hoeij are the current best, much superior to Cantor-Zassenhaus].

A: One can of course apply general algorithms for irreducibility testing and factorization, so I presume you are asking if there is something more efficient or more explicit that can be said in the case of trinomials. Except for special cases I don't believe that is the case.
While it is known that every binomial in $\mathbb{Q}(x)$ must have an irreducible factor that is either binomial or trinomial, no analogous bound is known in the trinomial case. It is at least 8 terms due to the known [1] example
$$f(x)f(-x) = - x^{14} - 27180501562500 x^2 + 1244325625000000$$
for $f(x) = x^7 + 20 x^6 + 200 x^5 + 2450 x^4 + 29000 x^3 + 545000 x^2 + 8101250 x + 35275000$
1 Choudhry and A. Schinzel (1992).
On the number of terms in the irreducible factors of a polynomial over $\mathbb Q$.
Glasgow Mathematical Journal (1992), 34, 11-15.
To dig deeper I suggest starting with the work of Schinzel - who has studied these and related factorization problems intensively for almost half a century, e.g. see

MR1254093 (95d:11146) 11R09 (12E05 12E10)
  Schinzel, Andrzej.
  On reducible trinomials.
  Dissertationes Math. (Rozprawy Mat.) 329 (1993), 83 pp.
Let $K$ be a field. It is well known
  that a binomial $x^n+a\in K[x]$ is
  reducible iff it has the form
  $x^{pk}-b^p$ ($p$ prime) or
  $x^{4k}+4b^4$. In this treatise the
  reducibility of trinomials
  $x^n+ax^m+b$ $(a,b\neq 0)$ is
  investigated. It turns out that the
  situation is very complicated. A
  satisfactory answer is obtained if $K$
  is a rational function field. For
  algebraic function fields in one
  variable and for algebraic number
  fields, less complete results are
  proved. It is assumed throughout that
  the characteristic of $K$ does not
  divide $mn(n-m)$.
It is easy to find trinomials with
  linear or quadratic factors. Table 1
  of this paper provides additional
  families of reducible trinomials if
  $(n,m)$ belongs to a list of 12 pairs,
  the largest being $(15,5)$. Perhaps
  the simplest example is
  $$x^6+4(v+1)x^2-v^2=(x^3+2x^2+2x-v)(x^3-2x^2+2x+v).$$ Every reducible trinomial
  $f(x)=x^n+ax^m+b$ gives rise to
  additional examples by considering
  $u^nf(x^l/u)$ (with $u\in K^\times$
  and $l\geq 1$) or $x^nf(1/x)/b$.
  Theorem 1 essentially states that
  every reducible trinomial arises in
  this manner from the examples
  indicated before if $K$ is a rational
  function field. (More precisely, it is
  assumed that $a^{-n}b^{n-m}$ is not a
  constant.) Table 2 lists $7$ families
  of reducible trinomials
  $x^n+A(v,w)x^m+B(v,w)$ with $(v,w)\in
> E(K)$, where $A$, $B$ are polynomials
  over $\mathbb Z$ and $E$ is an
  elliptic curve defined by an equation
  $z^2=C(w)$, where $C$ is a monic
  polynomial over $\mathbb Z$. The
  polynomials $A,B$ and the
  corresponding factorizations of the
  trinomials are too complicated to be
  included in this review. (For the
  largest pair $(n,m)=(21,7)$ the
  corresponding $A$ fills 10 lines in
  the paper.) In Theorem 2 it is assumed
  that $K$ is a finite extension of a
  rational function field $F(t)$ such
  that $\overline FK$ has genus $g>0$
  and $a^{-n}b^{n-m}\notin
> \overline{F}$. If $g=1$ then there are
  no additional examples of reducible
  trinomials. If $g>1$ then essentially
  new examples with $n<24g$ may exist.
  Theorem 3 reduces the case where $K$
  is a finite separable extension of
  $F(t)$ and $a^{-n}b^{n-m}\in\overline
> F$ to studying reducibility over
  $K\cap\overline F$. If $K$ is an
  algebraic number field then for fixed
  $n$, $m$ a finite number of
  essentially new examples of reducible
  trinomials $x^n+ax^m+b$ may exist
  (Theorem 6). The author conjectures
  that for every $K$ there is only a
  finite number of these ``sporadic
  trinomials''. If the conjecture holds
  then there exists a constant $c(K)$
  such that every trinomial over $K$ has
  an irreducible factor with at most
  $c(K)$ nonzero coefficients
  (Consequence 2). Table 5 contains all
  52 sporadic trinomials over $\mathbb
> Q$ known to the author. Their degrees
  lie in the range from $8$ to $52$. The
  rest of the paper is devoted to
  studying the reducibility of
  $ax^n+bx^m+c\in\mathbb Z[x]$. Theorem
  9 (refining a result of Nagell)
  derives necessary conditions, which in
  the case $(m,n)=1$ yield an explicit
  bound for $b$ in terms of $a,c,m,n$.
  For every positive integer $d$ there
  exist only finitely many $n,m,b$ with
  $n/(m,n)>d$ and $|b|>2$ such that
  $x^n+bx^m\pm 1$ has a factor of degree
  $d$; and these can be effectively
  computed. Theorem 10 derives necessary
  conditions from the existence of a
  factor (of $ax^n+bx^m+c)$ of given
  degree $d$. These imply that there
  exists $n_0(d)$ such that $x^n+bx^m+1$
  is irreducible if $n\geq n_0(d)$,
  $n\neq 2m$, $|b|>2$. By Theorem 8, for
  every $n$ there exist only finitely
  many reducible trinomials $x^n+bx^m+1$
  with $n\neq 2m$.
The proof of Theorem 10 does not
  depend on the other results of the
  paper. The same applies to Theorem 9.
  All other theorems except for Theorem
  3 are based on lower estimates for the
  genus of certain function fields.
  These estimates show that the
  existence of a factor of degree $k$ of
  $x^n+ax^m+b\in K[x]$ imposes severe
  restrictions on $k,m,n,a,b$ provided
  $K$ is a function field. The remaining
  cases are treated in a long series of
  lemmas applying to every field $K$
  whose characteristic does not divide
  $mn(n-m)$. In several cases the proofs
  require extensive manipulations (with
  polynomials in several variables)
  which were performed by means of
  computer algebra systems. Faltings'
  theorem (solving Mordell's conjecture)
  is invoked in the proof of Theorem 6
  (dealing with number fields). Theorems
  7 and 8 (concerning
  $ax^n+bx^m+c\in\mathbb Z[x])$ are
  proved by using the corresponding
  theorems for rational function fields
  together with a lemma which may be
  viewed as a refinement of Hilbert's
  irreducibility theorem. The proof of
  this lemma is based on Siegel's
  theorem (on integral points of curves
  of positive genus) and on a result of
  Maillet (1919) dealing with rational
  functions over $\mathbb Q$ taking
  infinitely many integral values at
  rational points.
{Reviewer's remarks: In Theorem 2 the
  term $u^{\nu-\mu}$ in the expression
  for $B$ has to be replaced by $u^\nu$.
  The proof of Lemma 27 employs Lemma
  2(c) although this lemma only applies
  to separable extensions. In order to
  prove Lemma 49 one has to know that
  every finite separable extension $L$
  of $K(t)$ with $L\subseteq \overline
> K(t)$ is contained in $K'(t)$ for some
  separable extension $K'$ of $K$. (One
  can in fact prove that $L=K'(t)$ for
  suitable $K'$. This need not be true
  for inseparable $L$.) The proof of
  Theorem 6 is apparently based on the
  incorrect assumption that a divisor
  $P$ of a function field $L=K(t,y)$ has
  degree $1$ or is ramified with respect
  to $K(t)$ if $t$ and $y$ are congruent
  to elements of $K\bmod P$.}
REVISED (1995)
Reviewed by G. Turnwald

A: Factor where? Over the rationals? Take a look to Berlekamp algorith.
http://en.wikipedia.org/wiki/Berlekamp%27s_algorithm
The right link is http://en.wikipedia.org/wiki/Berlekamp%E2%80%93Zassenhaus_algorithm
to Berlekamp–Zassenhaus algorithm.


text:
Q: how to do the transition of rectangle width change? lets just say theoreticaly, that I have
Rectangle {
    id: testRect
    width: 100
}

and once i start the timer with interval tick 50ms, it should just extend the width of Rect:
Timer {
    id: testTimer
    interval: 50
    onTriggered: testRect.width += 50
}

which works fine, but even when its onlz 50ms, its still seems to be quite not smooth transition.
Any idea how to smoothen the width change?
Please note this is only for learning purposes, what I will learn here will use in different situations, therefore please dont ask what is the puspose of the code...
Thank you!

A: You should rely on the animation features available in QtQuick to animate property changes.
In your case, you can define different states, with transitions between states where you define how an item should behave when going from one state to another. (See relevant documentation about states)
import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Rectangle {
        id: rect
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.margins: 100
        height: 200
        color: "red"

        state: "default"

        states: [
            State {
                name: "default"

                PropertyChanges {
                    target: rect
                    width: 200
                }
            },
            State {
                name: "bigger"

                PropertyChanges {
                    target: rect
                    width: 250
                }
            }
        ]

        transitions: Transition {
            NumberAnimation {
                duration: 500 //ms
                target: rect
                properties: "width"
            }
        }

        // Just there to trigger the state change by clicking on the Rectangle
        MouseArea {
            anchors.fill: parent
            onClicked: {
                if (rect.state === "default")
                    rect.state = "bigger"
                else
                    rect.state = "default"
            }
        }
    }
}

Or you can define a behavior, which is more simple to define when you only act on a single property:
import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Rectangle {
        id: rect
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.margins: 100
        height: 200
        width: 200
        color: "red"

        Behavior on width {
            NumberAnimation {
                duration: 500 //ms
            }
        }

        // Just there to trigger the width change by clicking on the Rectangle
        MouseArea {
            anchors.fill: parent
            onClicked: {
                if (rect.width === 200)
                    rect.width = 250
                else
                    rect.width = 200
            }
        }
    }
}

Finally, if you really want a smooth animation, you can use SmoothedAnimation instead of NumberAnimation (which is a linear animation by default)


text:
Q: XMPP last activity time shows in strange form. How to fix it? I have added to the Bridging file XMPPLastActivity.h file and in Swift file I did the next:
let abc = XMPPLastActivity()
let a = abc.sendLastActivityQueryToJID(user.jid)
print("A is: \(a)")

but it returns me response like
1686F740-C50C-477B-BAE2-02C897826B97

How can I return it in human readable format?
UPDATE
Please, join to chat to help me: https://chat.stackoverflow.com/rooms/90972/ios-errors-fixing

A: You will get a response via the XMPP delegate. You need to implement:
func xmppLastActivityDidReceiveResponse(sender:XMPPLastActivity, response:XMPPIQ)

And get the time lag to now in seconds with:
let time : NSUInteger = response.lastActivitySeconds

Then it's NSDate all the way.


text:
Q: Long bounty descriptions
This is not a duplicate of Reduce Character Limit for Bounty Custom Text. Here's why:
I'm suggesting a 150-char limit, not a 600-char one.

I hate seeing long bounty descriptions like this one:

List of first n prime numbers most efficiently and in shortest code
Generally, this is a language documentation in a bounty. Can we impose a limit on the size of bounty descriptions, please? I think the image speaks by itself, but, if you can't see it, here is the whole bounty remark:

Perform this in Wentelx87. github.com/CrazyPython/wentelx87. Here is a short description of Wentel. A little birdie told me I should bounty an existing question instead of making a new one. So here goes. > Wentel consists of, at the basic level, a memory pointer and an instruction pointer. Instructions are stored loaded into memory. The execution pointer moves to the right after executing the instruction at that memory pointer. > The program is loaded into rightmost slot of memory. For example, if your program is 0010 0000 0101 0100, then the virtual machine will look like this when started: 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0010 0000 0101 0100 (memory) ^ (execution pointer) ^ (memory pointer) (from [README][1]) --- --- Wentel documentation examples, thorough and clear explanation [here][2]. Wentel is language that is very hard to program in. Unlike brain**k, functions and GOTOs can be implemented. It emulates real machine code/assembly much better than brainf**k. Wentel is a simple language. 1. instructions are held in the rightmost cells, one cell = one instruction 2. execution pointer starts out on first instruction 3. execution pointer moves right 4. the same cells that hold memory hold instructions. 5. these are the opcodes:  0000 - no-op  0001 - if the current address's value is equal to the value stored by the adress defined by the next word, move the execution pointer to the address pointed to the next word after the word after the current address.  0010 - move memory pointer to address specified by next word.  0011 - deposit the current address of the execution pointer into the current memory address  0100 - increment current memory address  0101 - decrement current memory address 0110 - move memory pointer left  0111 - move memory pointer right 6. and here are the specialized opcodes for output.  1000 - output 0 1001 - output 1

Started at: 2016-10-10 22:06:73Z
Author: Agent CrazyPython (41088)
Reason: Canonical answer required
Reputation: 150


text:
Q: Stopping edit session at start of ArcPy script? I have a simple script that I use to select features from a ArcSDE database and export them to a personal.gdb.
Currently, I have to manually save and stop my edit session in the MXD so that the script can get a schema lock.
I have been trying to use arcpy.da.Editor at the start of the script to automatically end the edit session, but I have not been able to achieve that thus far.
Is this the correct way to end an edit session in the MXD I am running the script in? I would also like to be able to restart my edit session after the script runs.
import arcpy
import os
from arcpy import env
env.overwriteOutput = True

edit = arcpy.da.Editor
edit.startEditing(False, True)
print 'Stopping Edit'

# Delete Feature class from file Geodatabase
arcpy.Delete_management('C:\GIS\BlairMailer\Mailer.mdb\AddressPoint')
print 'Feature Class Deleted'

# Select by attribute
arcpy.SelectLayerByAttribute_management ( "AddressPoint", "NEW_SELECTION", "   [DISTRICT] = 'Y'" or "[DISTRICT] = 'y'")

# Export selected feature to Geodatabase
arcpy.FeatureClassToGeodatabase_conversion("AddressPoint",'C:\GIS\BlairMailer\Mailer.mdb')
print 'feature Class Exported'

# Open Mailer
os.startfile(r'C:\GIS\BlairMailer\Mailer.docx')

This is the returned error when I try to run the script with an active edit session.
Runtime error
Traceback (most recent call last):
File "<string>", line 7, in <module>
TypeError: descriptor 'startEditing' requires a 'Workspace Editor' object   but received a 'bool'

A: As commented by @GISGe, the

arcpy.da.Editor [class] takes a workspace as argument: arcpy.da.Editor(workspace)

whereas you have:
edit = arcpy.da.Editor

See the Syntax section of the Editor class Help