问:
how can I configure swashbuckle to display the api version instead of the v{version} variable?
I'm using Swashbuckle to document my Web API 2.2 API. When I load the Swagger page, the uri's display with a version placeholder variable instead of the actual version.  For example:

```<code>/api/v{version}/authentication
</code>```

Instead of:

```<code>/api/v2/authentication
</code>```

How can I configure my app or Swashbuckle to display the version number instead of the version variable?

答:
This is one of the ways to implement versioning. I have a custom header and custom root url function, you can ignore that part.  This code is asking Swagger to build two different versions from the xml provided.</p>

```<code>public class SwaggerConfig
{
    public static void Register()
    {

        var customHeader = new SwaggerHeader  //you can ignore this one
        {
            Description = "Custom header description",
            Key = "customHeaderId",
            Name = "customHeaderId"
        };

        var versionSupportResolver = new Func<ApiDescription, string, bool>((apiDescription, version) =>
        {
            var path = apiDescription.RelativePath.Split('/');
            var pathVersion = path[1];
            return string.Equals(pathVersion, version, StringComparison.OrdinalIgnoreCase);
        });

        var versionInfoBuilder = new Action<VersionInfoBuilder>(info => {
            info.Version("v2", "My API v2");
            info.Version("v1", "My API v1");
        });

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
            {
                //c.RootUrl(ComputeHostAsSeenByOriginalClient);  //you can ignore this custom function
                c.Schemes(new[] { "http", "https" });
                customHeader.Apply(c);
                c.MultipleApiVersions(versionSupportResolver, versionInfoBuilder);
                c.IgnoreObsoleteActions();
                c.IncludeXmlComments(GetXmlCommentsPath());
                c.DescribeAllEnumsAsStrings();
            })
            .EnableSwaggerUi("swagger/ui/{*assetPath}", c =>
            {
                c.DisableValidator();
                c.SupportedSubmitMethods("GET", "POST");
            });
    }

    private static Func<XPathDocument> GetXmlCommentsPath()
    {
        return () =>
        {
            var xapixml = GetXDocument("My.API.xml");
            var xElement = xapixml.Element("doc");
            XPathDocument xPath = null;
            if (xElement != null)
            {
                using (var ms = new MemoryStream())
                {
                    var xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false };
                    using (var xw = XmlWriter.Create(ms, xws))
                    {
                        xElement.WriteTo(xw);
                    }
                    ms.Position = 0;
                    xPath = new XPathDocument(ms);
                }
            }
            return xPath;
        };
    }

    private static XDocument GetXDocument(string file)
    {
        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
        var xDoc = XDocument.Load(path + "\\" + file);
        return xDoc;
    }

    //ComputeHostAsSeenByOriginalClient function code

}
</code>```

Body:
I'm using Swashbuckle to document my Web API 2.2 API. When I load the Swagger page, the uri's display with a version placeholder variable instead of the actual version.  For example:

/api/v{version}/authentication

Instead of:

/api/v2/authentication

How can I configure my app or Swashbuckle to display the version number instead of the version variable?

Body:
This is one of the ways to implement versioning. I have a custom header and custom root url function, you can ignore that part.  This code is asking Swagger to build two different versions from the xml provided.

public class SwaggerConfig
{
    public static void Register()
    {

        var customHeader = new SwaggerHeader  //you can ignore this one
        {
            Description = "Custom header description",
            Key = "customHeaderId",
            Name = "customHeaderId"
        };

        var versionSupportResolver = new Func<ApiDescription, string, bool>((apiDescription, version) =>
        {
            var path = apiDescription.RelativePath.Split('/');
            var pathVersion = path[1];
            return string.Equals(pathVersion, version, StringComparison.OrdinalIgnoreCase);
        });

        var versionInfoBuilder = new Action<VersionInfoBuilder>(info => {
            info.Version("v2", "My API v2");
            info.Version("v1", "My API v1");
        });

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
            {
                //c.RootUrl(ComputeHostAsSeenByOriginalClient);  //you can ignore this custom function
                c.Schemes(new[] { "http", "https" });
                customHeader.Apply(c);
                c.MultipleApiVersions(versionSupportResolver, versionInfoBuilder);
                c.IgnoreObsoleteActions();
                c.IncludeXmlComments(GetXmlCommentsPath());
                c.DescribeAllEnumsAsStrings();
            })
            .EnableSwaggerUi("swagger/ui/{*assetPath}", c =>
            {
                c.DisableValidator();
                c.SupportedSubmitMethods("GET", "POST");
            });
    }

    private static Func<XPathDocument> GetXmlCommentsPath()
    {
        return () =>
        {
            var xapixml = GetXDocument("My.API.xml");
            var xElement = xapixml.Element("doc");
            XPathDocument xPath = null;
            if (xElement != null)
            {
                using (var ms = new MemoryStream())
                {
                    var xws = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false };
                    using (var xw = XmlWriter.Create(ms, xws))
                    {
                        xElement.WriteTo(xw);
                    }
                    ms.Position = 0;
                    xPath = new XPathDocument(ms);
                }
            }
            return xPath;
        };
    }

    private static XDocument GetXDocument(string file)
    {
        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
        var xDoc = XDocument.Load(path + "\\" + file);
        return xDoc;
    }

    //ComputeHostAsSeenByOriginalClient function code

}


来源: stackexchange

问:
Does HTML Encoding a mailto tag stop spammers
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

```<code><a href="mailto:newbi...">email me</a>
</code>```

Also, are there any other techniques that I've left out?  Which is the best method?

答: I have been using simple Javascript string concatenation and substring operations to obfuscate the email address for years on several websites. This seems to have worked well, since I got minimal spam on these addresses. This cannot mean that it will still work in the future.</p>

OwnerDisplayName: bendewey

ContentLicense: CC BY-SA 3.0

Body:
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

email me

Also, are there any other techniques that I've left out?  Which is the best method?

LastEditorDisplayName: bendewey

OwnerDisplayName: cdonner

ContentLicense: CC BY-SA 2.5


问:
ClassCastException when inflating a FrameLayout in a GridView
I'm trying to inflate a FrameLayout in a GridView and I'm getting an exception. Here is the getView method from the adapter (a subclass of BaseAdapter):

```<code>public View getView(int position, View convertView, ViewGroup parent) {
    // TODO: Create compound view with image and name overlayed on top
    FrameLayout personFrame;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        personFrame = (FrameLayout)inflater.inflate(R.layout.thumbnail, null);
        //personFrame = (FrameLayout)View.inflate(mContext, R.layout.thumbnail, null);
        personFrame.setLayoutParams(new GridView.LayoutParams(85,85));
    } else {
        personFrame = (FrameLayout) convertView;
    }
</code>```

.... and so on

Here's the layout I'm inflating:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="85px"
android:layout_height="85px">
<ImageView
    android:id="@+id/thumbnail_image"
    android:layout_height="85px"
    android:padding="2px"
    android:layout_width="85px"
    android:scaleType="centerCrop" />
<TextView
    android:id="@+id/person_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="2dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Me" />
</FrameLayout>
</code>```

I've tried with and without setting the LayoutParams explicitly and I get the same exception each time, which is:

```<code>E/AndroidRuntime(  420): java.lang.ClassCastException:        android.widget.FrameLayout$LayoutParams
E/AndroidRuntime(  420):    at android.widget.GridView.onMeasure(GridView.java:934)
E/AndroidRuntime(  420):    at android.view.View.measure(View.java:8171)
E/AndroidRuntime(  420):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
E/AndroidRuntime(  420):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
E/AndroidRuntime(  420):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
E/AndroidRuntime(  420):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
E/AndroidRuntime(  420):    at android.view.View.measure(View.java:8171)
E/AndroidRuntime(  420):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
E/AndroidRuntime(  420):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
E/AndroidRuntime(  420):    at android.view.View.measure(View.java:8171)
E/AndroidRuntime(  420):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
E/AndroidRuntime(  420):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
E/AndroidRuntime(  420):    at android.view.View.measure(View.java:8171)
E/AndroidRuntime(  420):    at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
E/AndroidRuntime(  420):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
E/AndroidRuntime(  420):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(  420):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(  420):    at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime(  420):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(  420):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(  420):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(  420):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime(  420):    at dalvik.system.NativeStart.main(Native Method)
</code>```

Can anyone point out where I've gone wrong here?
Many thanks

答: Actually returning the wrong object from getView (as you mentioned you were doing) is what caused the Exception. For example if you returned a button from within your FrameLayout instead of the FrameLayout itself this will cause the problem you describe. The GridView code is taking the View object you return and walking one step up the View hierarchy. There it expects to find an AbsListView (which it wraps each grid view item in). Because you returned a sub-element of your FrameLayout, the GridView class found a FrameLayout where it expected an AbsListView.</p>

Body:
I'm trying to inflate a FrameLayout in a GridView and I'm getting an exception. Here is the getView method from the adapter (a subclass of BaseAdapter):

public View getView(int position, View convertView, ViewGroup parent) {
    // TODO: Create compound view with image and name overlayed on top
    FrameLayout personFrame;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        personFrame = (FrameLayout)inflater.inflate(R.layout.thumbnail, null);
        //personFrame = (FrameLayout)View.inflate(mContext, R.layout.thumbnail, null);
        personFrame.setLayoutParams(new GridView.LayoutParams(85,85));
    } else {
        personFrame = (FrameLayout) convertView;
    }

.... and so on

Here's the layout I'm inflating:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="85px"
android:layout_height="85px">
<ImageView
    android:id="@+id/thumbnail_image"
    android:layout_height="85px"
    android:padding="2px"
    android:layout_width="85px"
    android:scaleType="centerCrop" />
<TextView
    android:id="@+id/person_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="2dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Me" />
</FrameLayout>

I've tried with and without setting the LayoutParams explicitly and I get the same exception each time, which is:

E/AndroidRuntime(  420): java.lang.ClassCastException:        android.widget.FrameLayout$LayoutParams
E/AndroidRuntime(  420):    at android.widget.GridView.onMeasure(GridView.java:934)
E/AndroidRuntime(  420):    at android.view.View.measure(View.java:8171)
E/AndroidRuntime(  420):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
E/AndroidRuntime(  420):    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
E/AndroidRuntime(  420):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
E/AndroidRuntime(  420):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
E/AndroidRuntime(  420):    at android.view.View.measure(View.java:8171)
E/AndroidRuntime(  420):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
E/AndroidRuntime(  420):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
E/AndroidRuntime(  420):    at android.view.View.measure(View.java:8171)
E/AndroidRuntime(  420):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
E/AndroidRuntime(  420):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
E/AndroidRuntime(  420):    at android.view.View.measure(View.java:8171)
E/AndroidRuntime(  420):    at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
E/AndroidRuntime(  420):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
E/AndroidRuntime(  420):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(  420):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(  420):    at android.app.ActivityThread.main(ActivityThread.java:4627)
E/AndroidRuntime(  420):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(  420):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(  420):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
E/AndroidRuntime(  420):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
E/AndroidRuntime(  420):    at dalvik.system.NativeStart.main(Native Method)

Can anyone point out where I've gone wrong here?
Many thanks


问:
How do I specify parameters in a KQL query?
I am trying to execute a KQL query against an Azure Data Explorer cluster using query parameters and the .NET Kusto SDK.

I have tried placing the parameters inside braces {} and without braces.

I have read the documentation about passing parameters to the query, but I can't find any examples of how the query should look when passed to Azure Data Explorer via the .NET SDK.

My query works in the Kusto.Explorer tool when I set the parameters in the tool but I'm having no luck when using the SDK.

```<code>var queryParameters = new Dictionary<string, string>()
            {
                { "myscope", "scope001" },
                { "startdate", "2019-01-01" },
                { "enddate", "2019-01-30" },
                { "author", "Bob Jammo" }
            };

var query = @"declare query_parameters (myscope:string, startdate:string, enddate:string, author:string);
                            Events
                            | where Scope == ""{myscope}""
                                and EventTime between (datetime({startdate}) .. datetime({enddate}))
                                and EventType == ""product""
                                and User.Email <> """"
                            | mv-expand Payload.products
                            | where Payload_products.authors contains ""{author}""
                            | distinct DeviceId
                            | count";

using (var client = KustoClientFactory.CreateCslQueryProvider(ConfigurationManager.AppSettings["AdxConnectionString"]))
{
    var clientRequestProperties = new Kusto.Data.Common.ClientRequestProperties(
        options: null,
        parameters: queryParameters);

    clientRequestProperties.ClientRequestId = StepsBase.ScenarioScope;

    using (var reader = client.ExecuteQuery(query, clientRequestProperties))
    {
        reader.Read();
        return Convert.ToInt32(reader[0]);
    }
}
</code>```

I get an error that indicates to me that the parameter value has not been set: "Syntax error: Query could not be parsed: Failed to parse datetime literal: 'datetime(startdate)'"

答:
Judging by the error message, it's cause you're using datetime({startdate}) instead of todatetime({startdate}).

Regardless, you could also consider changing the type of startdate and enddate to be datetime instead of string to begin with (and adjust their definition in the .NET dictionary)

ContentLicense: CC BY-SA 4.0

Body:
I am trying to execute a KQL query against an Azure Data Explorer cluster using query parameters and the .NET Kusto SDK.

I have tried placing the parameters inside braces {} and without braces.

I have read the documentation about passing parameters to the query, but I can't find any examples of how the query should look when passed to Azure Data Explorer via the .NET SDK.

My query works in the Kusto.Explorer tool when I set the parameters in the tool but I'm having no luck when using the SDK.

var queryParameters = new Dictionary<string, string>()
            {
                { "myscope", "scope001" },
                { "startdate", "2019-01-01" },
                { "enddate", "2019-01-30" },
                { "author", "Bob Jammo" }
            };

var query = @"declare query_parameters (myscope:string, startdate:string, enddate:string, author:string);
                            Events
                            | where Scope == ""{myscope}""
                                and EventTime between (datetime({startdate}) .. datetime({enddate}))
                                and EventType == ""product""
                                and User.Email <> """"
                            | mv-expand Payload.products
                            | where Payload_products.authors contains ""{author}""
                            | distinct DeviceId
                            | count";

using (var client = KustoClientFactory.CreateCslQueryProvider(ConfigurationManager.AppSettings["AdxConnectionString"]))
{
    var clientRequestProperties = new Kusto.Data.Common.ClientRequestProperties(
        options: null,
        parameters: queryParameters);

    clientRequestProperties.ClientRequestId = StepsBase.ScenarioScope;

    using (var reader = client.ExecuteQuery(query, clientRequestProperties))
    {
        reader.Read();
        return Convert.ToInt32(reader[0]);
    }
}

I get an error that indicates to me that the parameter value has not been set: "Syntax error: Query could not be parsed: Failed to parse datetime literal: 'datetime(startdate)'"


问:
Laravel JSON Where Clauses with number in key
I have table with json column "options".
Exemple:

```<code> {"language":"en" }
</code>```

When i doing query, it's OK:

```<code>DB::table('users')->where('options->language', 'en')->get();
</code>```

But if i have number key:

```<code>{"221":"en" }
</code>```

I get empty array:

```<code>DB::table('users')->where('options->221', 'en')->get();
</code>```

How i can get true query?
Laravel 5.2

答:
This has been fixed in later versions of Laravel.

In Laravel 5.2, you can use a raw expression:

```<code>DB::table('users')->whereRaw('`options`->\'$."221"\' = ?', ['en'])->get();
</code>```

Body:
I have table with json column "options".
Exemple:

 {"language":"en" }

When i doing query, it's OK:

DB::table('users')->where('options->language', 'en')->get();

But if i have number key:

{"221":"en" }

I get empty array:

DB::table('users')->where('options->221', 'en')->get();

How i can get true query?
Laravel 5.2

Body:
This has been fixed in later versions of Laravel.

In Laravel 5.2, you can use a raw expression:

DB::table('users')->whereRaw('`options`->\'$."221"\' = ?', ['en'])->get();


问:
difference between caeser cipher and a simple substitution cipher
I am very confused: I have been browsing through the Internet, searched some blogs etc, but I'm really getting confused.  My question is about a Caesar cipher and a simple substitution cipher -- is there any difference? Some blogs when I search simple substitution cipher I get Caesar cipher.  Is there anyone who can explain to me if they are the same or not? I really want to make a program that will work as a simple substitution cipher.

答:
plain text: A B C D E F G H I J K L

Cipher    : X Y Z A B C D E F G H I

So in Caesar Cipher we use left shift of 3, so that after encryption 'A' will be 'X'.


问:
Need to check for specific key presses in Javascript
I am having troubles understanding why the code below works, and I think my confusing arises with the callback to "event" in this case. I have a few images that when clicked or a corresponding keypress is logged, a sound will play. While everything works, I can't understand why the below code uses "event" instead of just using an empty function and call to "this" (ie: this.key)

I have tried to use the "this" method but it didn't work. A bit of research and I found I had to use "event" in my function.

```<code>function addListenerToAllDrums() {
    //store buttons in array
    var buttonArray = document.querySelectorAll(".drum");
    //iterate thru each btn
    for (var i = 0; i < buttonArray.length; i++) {
        //add a listener each iter.
        buttonArray[i].addEventListener("click", function () {
            //store html of button (ie: `w`) to variable
            var buttonInnerHTML = this.innerHTML;
            //the stored html is passed to the checkSound function
            checkSound(buttonInnerHTML); //ie: `w` = case w
        });
    }
}
</code>```

```<code>//check for keypress
document.addEventListener(`keydown`, function (event) {
    //store the key in a variable
    var pressedKey = event.key
    //passes pressedKey as string (ie: `w`) to checkSound(`w`)
    checkSound(pressedKey);
});
</code>```

```<code>//make a sound dependant on button press or keypress functions
function checkSound(input) {
    //Create Switch Statement based on keypress/button click input
    switch (input) {
        case `w`:
            var snare = new Audio('sounds/snare.mp3');
            snare.play();
        case `a`:
            var tom1 = new Audio('sounds/tom-1.mp3');
            tom1.play();
            break;
        case `s`:
            var tom3 = new Audio('sounds/tom-3.mp3');
            tom3.play();
            break;
        case `d`:
            var kick = new Audio('sounds/kick-bass.mp3');
            kick.play();
            break;
        case `j`:
            var tom4 = new Audio('sounds/tom-4.mp3');
            tom4.play();
            break;
        case 'k':
            var tom2 = new Audio('sounds/tom-2.mp3');
            tom2.play();
            break;
        case `l`:
            var crash = new Audio('sounds/crash.mp3');
            crash.play();
            break;

        default:
            console.log(this.innerHTML)
    }
}

addListenerToAllDrums();
</code>```

How can my clicks work with "this" but keypresses need "event"?

答:
this refers to the object that the event is called on. For the "click" event, that's a button. For the "keydown" event that's the whole document.

So, with the click event, this.innerHTML gets the text on the buttons. For the document, this.innerHTML would get nothing, which is not what you want.

Luckily, the event argument for the "keydown" event stores the key that was pressed (in the key property), so you can get the information that way.

Body:
I am having troubles understanding why the code below works, and I think my confusing arises with the callback to "event" in this case. I have a few images that when clicked or a corresponding keypress is logged, a sound will play. While everything works, I can't understand why the below code uses "event" instead of just using an empty function and call to "this" (ie: this.key)

I have tried to use the "this" method but it didn't work. A bit of research and I found I had to use "event" in my function.

function addListenerToAllDrums() {
    //store buttons in array
    var buttonArray = document.querySelectorAll(".drum");
    //iterate thru each btn
    for (var i = 0; i < buttonArray.length; i++) {
        //add a listener each iter.
        buttonArray[i].addEventListener("click", function () {
            //store html of button (ie: `w`) to variable
            var buttonInnerHTML = this.innerHTML;
            //the stored html is passed to the checkSound function
            checkSound(buttonInnerHTML); //ie: `w` = case w
        });
    }
}

//check for keypress
document.addEventListener(`keydown`, function (event) {
    //store the key in a variable
    var pressedKey = event.key
    //passes pressedKey as string (ie: `w`) to checkSound(`w`)
    checkSound(pressedKey);
});

//make a sound dependant on button press or keypress functions
function checkSound(input) {
    //Create Switch Statement based on keypress/button click input
    switch (input) {
        case `w`:
            var snare = new Audio('sounds/snare.mp3');
            snare.play();
        case `a`:
            var tom1 = new Audio('sounds/tom-1.mp3');
            tom1.play();
            break;
        case `s`:
            var tom3 = new Audio('sounds/tom-3.mp3');
            tom3.play();
            break;
        case `d`:
            var kick = new Audio('sounds/kick-bass.mp3');
            kick.play();
            break;
        case `j`:
            var tom4 = new Audio('sounds/tom-4.mp3');
            tom4.play();
            break;
        case 'k':
            var tom2 = new Audio('sounds/tom-2.mp3');
            tom2.play();
            break;
        case `l`:
            var crash = new Audio('sounds/crash.mp3');
            crash.play();
            break;

        default:
            console.log(this.innerHTML)
    }
}

addListenerToAllDrums();

How can my clicks work with "this" but keypresses need "event"?


问:
Calculating Percentages in Postgres
I'm completely new to PostgreSQL. I have the following table called my_table:

```<code>a    b    c        date
1    0    good     2019-05-02
0    1    good     2019-05-02
1    1    bad      2019-05-02
1    1    good     2019-05-02
1    0    bad      2019-05-01
0    1    good     2019-05-01
1    1    bad      2019-05-01
0    0    bad      2019-05-01
</code>```

I want to calculate the percentage of 'good' from column c for each date. I know how to get the number of 'good':

```<code>SELECT COUNT(c), date FROM my_table WHERE c != 'bad' GROUP BY date;
</code>```

That returns:

```<code>count    date
3        2019-05-02
1        2019-05-01
</code>```

My goal is to get this:

```<code>date         perc_good
2019-05-02   25
2019-05-01   75
</code>```

So I tried the following:

```<code>SELECT date,
       (SELECT COUNT(c)
        FROM my_table
        WHERE c != 'bad'
        GROUP BY date) / COUNT(c) * 100 as perc_good
FROM my_table
GROUP BY date;
</code>```

And I get an error saying

more than one row returned by a subquery used as an expression.

I found this answer but not sure how to or if it applies to my case:

Calculating percentage in PostgreSql

How do I go about calculating the percentage for multiple rows?

答:
You could use  a conditional sum for get the good value and count for total

below an exaustive code sample

```<code>  select  date
    , count(c) total
    , sum(case when c='good' then 1 else 0 end)  total_good
    , sum(case when c='bad' then 1 else 0 end)  total_bad
    , (sum(case when c='good' then 1 else 0 end) / count(c))* 100 perc_good
    , (sum(case when c='bad' then 1 else 0 end) / count(c))* 100 perc_bad
  from my_table
  group by  date
</code>```

and for your result

```<code>  select  date
    , (sum(case when c='good' then 1 else 0 end) / count(c))* 100 perc_good
  from my_table
  group by  date
</code>```

or as suggested  by a_horse_with_no_name using count(*) filter()

```<code>select  date
  , ((count(*) filter(where c='good'))/count(*))* 100 perc_good
from my_table
group by  date
</code>```

Title: Calculating Percentages in Postgres

Body:
I'm completely new to PostgreSQL. I have the following table called my_table:

a    b    c        date
1    0    good     2019-05-02
0    1    good     2019-05-02
1    1    bad      2019-05-02
1    1    good     2019-05-02
1    0    bad      2019-05-01
0    1    good     2019-05-01
1    1    bad      2019-05-01
0    0    bad      2019-05-01

I want to calculate the percentage of 'good' from column c for each date. I know how to get the number of 'good':

SELECT COUNT(c), date FROM my_table WHERE c != 'bad' GROUP BY date;

That returns:

count    date
3        2019-05-02
1        2019-05-01

My goal is to get this:

date         perc_good
2019-05-02   25
2019-05-01   75

So I tried the following:

SELECT date,
       (SELECT COUNT(c)
        FROM my_table
        WHERE c != 'bad'
        GROUP BY date) / COUNT(c) * 100 as perc_good
FROM my_table
GROUP BY date;

And I get an error saying

more than one row returned by a subquery used as an expression.

I found this answer but not sure how to or if it applies to my case:

Calculating percentage in PostgreSql

How do I go about calculating the percentage for multiple rows?

Body:
You could use  a conditional sum for get the good value and count for total

below an exaustive code sample

  select  date
    , count(c) total
    , sum(case when c='good' then 1 else 0 end)  total_good
    , sum(case when c='bad' then 1 else 0 end)  total_bad
    , (sum(case when c='good' then 1 else 0 end) / count(c))* 100 perc_good
    , (sum(case when c='bad' then 1 else 0 end) / count(c))* 100 perc_bad
  from my_table
  group by  date

and for your result

  select  date
    , (sum(case when c='good' then 1 else 0 end) / count(c))* 100 perc_good
  from my_table
  group by  date

or as suggested  by a_horse_with_no_name using count(*) filter()

select  date
  , ((count(*) filter(where c='good'))/count(*))* 100 perc_good
from my_table
group by  date


问:
How can you find out if a specific HTML 5 feature is implemented in a specific browser version?
I imagine there must be out there a website that collects information about HTML 5 feature and what browsers version started to support them.

This might be a good way to decide based on your website profile, if you can apply that HTML 5 feature without a fallback for your visitors.

Do you know such a site/resource ?

For example I want to know what browsers support the multiple upload feature for inputs and what browser version was the first.

Update

I'm not pleased with the sites suggested so I'm opening a bounty.

Suggestions so far:
Html5Test,
Caniuse,
modernizr.com,
QuirksMode

Update 2

Some people don't understand the question. I need to implement the multiple upload feature. I know from analytics what browser are they using ( I know this is not 100% correct ).

I'm willing to sacrifice some of the visitors by not offering some advance features but I need to understand how big is this procent. I'm NOT trying to DETECT in anyway the browser. It's a similar approach with other sites that dropped IE 6 support.

So please don't talk about bad practice.

答:
My vote is for:

http://www.findmebyip.com/litmus

Which i found via this blog:

http://www.deepbluesky.com/blog/-/browser-support-for-css3-and-html5_72/


问:
How to call those who have more data? json
Good day, as I can call from an array of a json those that contain more data, I am creating a graph and must contain those with more data, I have this code where I send my data

```<code>vehiculoPorColores = () => {
const _this = this
fetch("/live/graph/color")
  .then(response => response.json())
  .then(datos => {
    const vehicleKey = Object.keys(datos)
    console.log(vehicleKey)
    _this.setState(
      {
        vehiculosC: vehicleKey.splice(0, 5).map((i, e) => ({
          name: vehicleKey[e],
          colores: datos[i]
        }))
      },
      () => {
        setTimeout(this.vehiculoPorColores, 1000)
      }
    )
  })
  }
</code>```

JSON:

```<code>{
  "lavender": 3,
  "white": 12,
  "dimgrey": 4,
  "seagreen": 2,
  "lightslategrey": 6,
  "slategrey": 7,
  "indianred": 2,
  "snow": 1,
  "darkslategrey": 1,
  "khaki": 1,
  "gainsboro": 3,
  "palevioletred": 1,
  "darkgrey": 1
}
</code>```

to be more specific: json

I need to sort the data and choose the 5 records with the highest values, right now I only send a call to 5 but they are not the ones that have more data, and I need that and that they are only 5, aahh and I work in react

答:
If you want to sort an array in JS you can do...

Having an object shaped as:
{
 key1: 10,
 key2: "a string"
}

Then having an array:

[{
 key1: 10,
 key2: "a string"
},
{
 key1: 20,
 key2: "a string"
}]
```

<p>You can do this:</p>

```[{
 key1: 10,
 key2: "a string"
},
{
 key1: 20,
 key2: "a string"
}].sort((elemN, elemNplus)=> elemN.key1 - elemNplus.key1) :: output => [{
 key1: 10,
 key2: "a string"
},
{
 key1: 20,
 key2: "a string"
}]
```

<p>and Greater first: </p>

<pre class="lang-js prettyprint-override"><code>[{
 key1: 10,
 key2: "a string"
},
{
 key1: 20,
 key2: "a string"
}].sort((elemN, elemNplus)=> elemNplus.key1 - elemN.key1) :: output => [{
 key1: 20,
 key2: "a string"
},
{
 key1: 10,
 key2: "a string"
}]
</code>```

Body:
Good day, as I can call from an array of a json those that contain more data, I am creating a graph and must contain those with more data, I have this code where I send my data

vehiculoPorColores = () => {
const _this = this
fetch("/live/graph/color")
  .then(response => response.json())
  .then(datos => {
    const vehicleKey = Object.keys(datos)
    console.log(vehicleKey)
    _this.setState(
      {
        vehiculosC: vehicleKey.splice(0, 5).map((i, e) => ({
          name: vehicleKey[e],
          colores: datos[i]
        }))
      },
      () => {
        setTimeout(this.vehiculoPorColores, 1000)
      }
    )
  })
  }

JSON:

{
  "lavender": 3,
  "white": 12,
  "dimgrey": 4,
  "seagreen": 2,
  "lightslategrey": 6,
  "slategrey": 7,
  "indianred": 2,
  "snow": 1,
  "darkslategrey": 1,
  "khaki": 1,
  "gainsboro": 3,
  "palevioletred": 1,
  "darkgrey": 1
}

to be more specific: json

I need to sort the data and choose the 5 records with the highest values, right now I only send a call to 5 but they are not the ones that have more data, and I need that and that they are only 5, aahh and I work in react

Body:
If you want to sort an array in JS you can do...

Having an object shaped as:
{
 key1: 10,
 key2: "a string"
}

Then having an array:

[{
 key1: 10,
 key2: "a string"
},
{
 key1: 20,
 key2: "a string"
}]

You can do this:

[{
 key1: 10,
 key2: "a string"
},
{
 key1: 20,
 key2: "a string"
}].sort((elemN, elemNplus)=> elemN.key1 - elemNplus.key1) :: output => [{
 key1: 10,
 key2: "a string"
},
{
 key1: 20,
 key2: "a string"
}]

and Greater first:

[{
 key1: 10,
 key2: "a string"
},
{
 key1: 20,
 key2: "a string"
}].sort((elemN, elemNplus)=> elemNplus.key1 - elemN.key1) :: output => [{
 key1: 20,
 key2: "a string"
},
{
 key1: 10,
 key2: "a string"
}]


问:
How can I swap the axes on an eCharts bar chart with javascript
I have created an eCharts barchart and I just want to swap the x and y axes

I have tried just swapping the data objects for the axes but that doesn't work and googling hasn't turned up much at all.

This is the initialisation script for the bar chart

```<code>var chart = echarts.init(document.getElementById('chart'));
var option = {
    yAxis: {
        name: '',
        data: ''
    },

    xAxis: {
        name: '',
        data: ["CARH"  , "CDFR"  , "HGA"  , "O2RG"  , "SHLA"  , "SHWS"]
    },

    series: {
        name: '',
        type: 'bar',
        data: [100.29, 101.05, 100.78, 96.3, 101.8, 99.9]
    }
};
chart.setOption(option);
</code>```

答:
It seems all the properties of option must be wrapped in arrays, and xAxis should be left empty:

```<code>option = {
    yAxis: [{
        name: '',
        data: ["CARH"  , "CDFR"  , "HGA"  , "O2RG"  , "SHLA"  , "SHWS"]
    }],

    xAxis: [{}],

    series: [{
        name: '',
        type: 'bar',
        data: [100.29, 101.05, 100.78, 96.3, 101.8, 50]
    }]
}
</code>```

I found the solution by finding an example of an echart horizontal barchart, and removing options that did not alter the "horizontalness" of the chart. Then I compared this minimal set of options to the one given in the question.

Body:
I have created an eCharts barchart and I just want to swap the x and y axes

I have tried just swapping the data objects for the axes but that doesn't work and googling hasn't turned up much at all.

This is the initialisation script for the bar chart

var chart = echarts.init(document.getElementById('chart'));
var option = {
    yAxis: {
        name: '',
        data: ''
    },

    xAxis: {
        name: '',
        data: ["CARH"  , "CDFR"  , "HGA"  , "O2RG"  , "SHLA"  , "SHWS"]
    },

    series: {
        name: '',
        type: 'bar',
        data: [100.29, 101.05, 100.78, 96.3, 101.8, 99.9]
    }
};
chart.setOption(option);

Body:
It seems all the properties of option must be wrapped in arrays, and xAxis should be left empty:

option = {
    yAxis: [{
        name: '',
        data: ["CARH"  , "CDFR"  , "HGA"  , "O2RG"  , "SHLA"  , "SHWS"]
    }],

    xAxis: [{}],

    series: [{
        name: '',
        type: 'bar',
        data: [100.29, 101.05, 100.78, 96.3, 101.8, 50]
    }]
}

I found the solution by finding an example of an echart horizontal barchart, and removing options that did not alter the "horizontalness" of the chart. Then I compared this minimal set of options to the one given in the question.


问:
Use an overlay network for standalone containers is throwing context deadline exceeded
I have 2 servers where I tryed to create 1 container in each one and tryed to connect them via an overlay network, the servers specs are the folowing ones:

Server 1

Centos 7

docker 17.06.1-ce

Server 2

Centos 7

Docker 18.09.3

I followed the guide of this link (Use an overlay network for standalone containers), but when I executed the command docker run -dit --name alpine2 --network test-net alpine on server 2 it throws the error docker: Error response from daemon: attaching to network failed, make sure your network options are correct and check manager logs: context deadline exceeded., Can someone help me with this issue?

答: I needed to update the version of docker of server 1 from 17.06.1-ce to 18.09.3 and later follow the same guide, now everything works great.</p>


问:
Force Maven Wagon plugin to POST instead of PUT
We're trying to use the Nexus APT plugin, but sending artifacts to it requires them to be POSTed not PUTed. The default Wagon implementation wants to HTTP Put it seems, because we're getting a 405 error back.

Is there a way to tell wagon to POST instead of PUT? I can't find it in the docs.

Thanks!

```<code>                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>wagon-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>upload-deb-to-nexus</id>
                            <phase>deploy</phase>
                            <goals>
                                <goal>upload-single</goal>
                            </goals>
                            <configuration>
                                <serverId>xxx-nexus-apt</serverId>
                                <fromFile>${project.build.directory}/${jdeb.name}</fromFile>
                                <url>https://xxx.xxx.com/repository/xxx-nexus-apt</url>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
</code>```

答: Looked at the code for the Wagon http provider, PUT is hardcoded.

Body:
We're trying to use the Nexus APT plugin, but sending artifacts to it requires them to be POSTed not PUTed. The default Wagon implementation wants to HTTP Put it seems, because we're getting a 405 error back.

Is there a way to tell wagon to POST instead of PUT? I can't find it in the docs.

Thanks!

                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>wagon-maven-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>upload-deb-to-nexus</id>
                            <phase>deploy</phase>
                            <goals>
                                <goal>upload-single</goal>
                            </goals>
                            <configuration>
                                <serverId>xxx-nexus-apt</serverId>
                                <fromFile>${project.build.directory}/${jdeb.name}</fromFile>
                                <url>https://xxx.xxx.com/repository/xxx-nexus-apt</url>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>


问:
How to get DayOfWeek from an Instant.now()
Assuming the following code...

```<code>Instant x = Instant.now();
</code>```

How do I get day of week from x?

答:
```<code>Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
</code>```

will give you the same result

Body:
Assuming the following code...

Instant x = Instant.now();

How do I get day of week from x?

Body:
Calendar.getInstance().get(Calendar.DAY_OF_WEEK);

will give you the same result


问:
How can i output to console my request's body
Can't output to console "POST" requests body

```<code>HttpClient client= HttpClientBuilder.create().build();
HttpPost request=new HttpPost("https://reqres.in/api/register");
 List<NameValuePair> params= new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("email","eve.holt@reqres.in"));
    params.add(new BasicNameValuePair("password","pistol"));
    request.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(request);
</code>```

I want to see the body of requests(email, password).

I've tried
    System.out.println(request.getEntity())
but it's not exactly same
thx

答:
Apache httpclient creates a model in the form of HttpPost, which isn't a raw request. When you execute(), this is internally transformed into a HTTP payload and processed, and you are presented with the response again as a modeled object.

You can log the requests and responses though using the Wire logger: org.apache.http.wire. More information here: https://hc.apache.org/httpcomponents-client-4.5.x/logging.html.

The raw data seems to be available in org.apache.commons.httpclient.HttpConnection, but you'd have to override quite a few components of httpclient to get it out.

Body:
Can't output to console "POST" requests body

HttpClient client= HttpClientBuilder.create().build();
HttpPost request=new HttpPost("https://reqres.in/api/register");
 List<NameValuePair> params= new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("email","eve.holt@reqres.in"));
    params.add(new BasicNameValuePair("password","pistol"));
    request.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(request);

I want to see the body of requests(email, password).

I've tried
    System.out.println(request.getEntity())
but it's not exactly same
thx


问:
How is it possible to assign in list values that I can use as reference and increase or decrease accordingly
Example:

```<code>abc = ["a", "b", "c"]
</code>```

a should have the value 2, b 4 and c 7

How could I add this value to each of those and adjust them accordingly?
My goal is to make something that uses first the letter with the highest count and then goes lower and each time a letter is used correctly it should increase the value +1
Thank you in advance.

答:
Use a dictionary and increment the values up or down:</p>

```<code>d = {'a':2,'b':4,'c':7}

# more code

d['a'] += 1

print(d)
# {'a':3,'b':4,'c':7}

# more code

d['c'] -= 1
print(d)
# {'a':3,'b':4,'c':6}

</code>```

Body:
Example:

abc = ["a", "b", "c"]

a should have the value 2, b 4 and c 7

How could I add this value to each of those and adjust them accordingly?
My goal is to make something that uses first the letter with the highest count and then goes lower and each time a letter is used correctly it should increase the value +1
Thank you in advance.

Body:
Use a dictionary and increment the values up or down:

d = {'a':2,'b':4,'c':7}

# more code

d['a'] += 1

print(d)
# {'a':3,'b':4,'c':7}

# more code

d['c'] -= 1
print(d)
# {'a':3,'b':4,'c':6}


问:
Java - Mapping DTOs with Circular Dependencies
Currently settings up classic mappers, converting Entities to DTOs.
Some of the entities (and thus DTOs) reference each other (after specific JPA entity definition).

Let's say:

```<code>public class Person {
  private String name;
  private List<State> states; // All states with this person
  // Getters & Setters
}

public class State {
  private String name;
  private List<Person> persons; // All persons with this state
   // Getters & Setters
}
</code>```

With such circular dependencies I have to set up mappers like so:

```<code>public class PersonMapper {
   public PersonDTO toDTO(Person p) { // not null
     PersonDTO dto = new PersonDTO();
     dto.setName(p.getName());
     dto.setStates(p.States().stream().map(stateMapper::toDTO).collect(Collectors.toList());
     return dto;
   }

public class StateMapper {
   public StateDTO toDTO(State s) { // not null
     StateDTO dto = new StateDTO();
     dto.setName(s.getName());
     dto.setPersons(s.getPersons().stream().map(personMapper::toDTO).collect(Collectors.toList());
     return dto;
   }
</code>```

One way to easily avoid this is to create a new method in PersonMapper or StateMapper and make it NOT map the persons or states. But I was wondering if there was a known design pattern or a more generic way of doing this?

Thanks

答:
The only way is to construct one side first:

```<code>public class PersonMapper {
   public PersonDTO toDTO(Person p) { // not null
     PersonDTO dto = new PersonDTO();
     dto.setName(p.getName());
     dto.setStates(new ArrayList<>());
     states.forEach(state -> state.getPersons().add(dto)) //todo: uniqueness check
     return dto;
   }
}

public class StateMapper {
   //todo: maybe Person.name is better than the whole Person object in the map
   public StateDTO toDTO(State s, Map<Person, PersonDTO> personMapping) {
     StateDTO dto = new StateDTO();
     dto.setName(s.getName());

     List<PersonDTO> persons = s.getPersons().stream().map(personMapping::get)
                               .collect(Collectors.toList();
     persons.forEach(p -> p.getStates().add(dto)) //todo: uniqueness check for states or use a set
     dto.setPersons(persons);

     return dto;
  }
}
</code>```

Everything else would use some Reference<State> like data structure but I don't think thats worth it. You could also break the circular dependency by removing one side and correlate a Person to its States when needed or store a Map<State, List<Person>> on another level. But I still prefer the approach outlined at the start of my post.

On a side-note: Maybe try datus (disclaimer: I am the author) and see if it fits your other conversion tasks and ease your work :)

Body:
Currently settings up classic mappers, converting Entities to DTOs.
Some of the entities (and thus DTOs) reference each other (after specific JPA entity definition).

Let's say:

public class Person {
  private String name;
  private List<State> states; // All states with this person
  // Getters & Setters
}

public class State {
  private String name;
  private List<Person> persons; // All persons with this state
   // Getters & Setters
}

With such circular dependencies I have to set up mappers like so:

public class PersonMapper {
   public PersonDTO toDTO(Person p) { // not null
     PersonDTO dto = new PersonDTO();
     dto.setName(p.getName());
     dto.setStates(p.States().stream().map(stateMapper::toDTO).collect(Collectors.toList());
     return dto;
   }

public class StateMapper {
   public StateDTO toDTO(State s) { // not null
     StateDTO dto = new StateDTO();
     dto.setName(s.getName());
     dto.setPersons(s.getPersons().stream().map(personMapper::toDTO).collect(Collectors.toList());
     return dto;
   }

One way to easily avoid this is to create a new method in PersonMapper or StateMapper and make it NOT map the persons or states. But I was wondering if there was a known design pattern or a more generic way of doing this?

Thanks

Body:
The only way is to construct one side first:

public class PersonMapper {
   public PersonDTO toDTO(Person p) { // not null
     PersonDTO dto = new PersonDTO();
     dto.setName(p.getName());
     dto.setStates(new ArrayList<>());
     states.forEach(state -> state.getPersons().add(dto)) //todo: uniqueness check
     return dto;
   }
}

public class StateMapper {
   //todo: maybe Person.name is better than the whole Person object in the map
   public StateDTO toDTO(State s, Map<Person, PersonDTO> personMapping) {
     StateDTO dto = new StateDTO();
     dto.setName(s.getName());

     List<PersonDTO> persons = s.getPersons().stream().map(personMapping::get)
                               .collect(Collectors.toList();
     persons.forEach(p -> p.getStates().add(dto)) //todo: uniqueness check for states or use a set
     dto.setPersons(persons);

     return dto;
  }
}

Everything else would use some Reference<State> like data structure but I don't think thats worth it. You could also break the circular dependency by removing one side and correlate a Person to its States when needed or store a Map<State, List<Person>> on another level. But I still prefer the approach outlined at the start of my post.

On a side-note: Maybe try datus (disclaimer: I am the author) and see if it fits your other conversion tasks and ease your work :)


问:
Can't Query Single CloudKit Record by recordName UUID
I have a CloudKit app where records are stored locally in CoreData. When creating the CoreData record, a UUID is generated and populated to the system recordName field. The app creates and saves records in CoreData then uploads the records to CloudKit. This works fine.

However, I am now coding to modify a record and am not able to fetch a record by the recordName UUID. I have not been successful setting a predicate to search for only that record. I can retrieve all records with TRUEPREDICATE and I can also retrieve a single record from a field I created in the CloudKit record type. I created a field called myRecordName where I store the same UUID as the CloudKit recordName. A query using the myRecordName works fine.

I have shown three methods below for the predicates. If p1 and p2 are not both commented out the app crashes on running. I assume I am missing something really simple here. Any guidance would be appreciated. Xcode 10.2.1, iOS 12.2, testing on a real device.

If either p1 or p2 or both are not commented out, the console shows:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CKReference rangeOfString:]:
  unrecognized selector sent to instance 0x280878520'

```<code>func queryDatabase() {

    let recordZone = CKRecordZone(zoneName: "PrimaryZone")
    let recName = "0E763775-5AD3-4A50-BFB8-AC310180E8A2"

    let recID = CKRecord.ID(recordName: recName, zoneID: recordZone.zoneID)
    let searchRecord = CKRecord(recordType: "Patient", recordID: recID)

    let p1 = NSPredicate(format: "%K == %@", CKRecord.Reference(recordID: recID, action: CKRecord_Reference_Action.none))
    let p2 = NSPredicate(format: "%K == %@", CKRecord.Reference(record: searchRecord, action: CKRecord_Reference_Action.none))

    //let predicate = NSPredicate(format: "TRUEPREDICATE")
    let p3 = NSPredicate(format: "myRecordName = %@", recName)

    let query = CKQuery(recordType: "Patient", predicate: p3)
    let sortDescriptor = NSSortDescriptor(key: "lastNameText", ascending: true)
    query.sortDescriptors = [sortDescriptor]

    privateDatabase.perform(query, inZoneWith: recordZone.zoneID) { (results, error) in
        if error != nil {
            print("error querying database\(String(describing: error?.localizedDescription))")
        } else {

            DVC.ckRecords = results!
            //print(results!)
            print(DVC.ckRecords.first!)

        }//if error else
    }//perform query block

}//queryDatabase
</code>```

答:
I've never used CloudKit, so maybe I'm wrong, but…

The two problem lines of code, p1= and p2=, attempt to create a NSPredicate using a format string.  Each format string contains two var arg substitutions, aka placeholders: %K and %@.  So for this to work, that format string argument must be followed by two more arguments: first a key path, which should be a string (%K), and second a object for its value (%@).  For your purposes here, the key path is probably just an attribute name.

But you have only provided one more argument, a CKRecord.Reference object, which the system tries to parse for the first (attribute name, string) argument.  The error you are getting is typical of what happens when the system tries to parse an object such as CKRecord.Reference when it was expecting a string.  Swift may be quite type safe but old-fashioned NSPredicate var args functions are not :)

To fix this problem (and move on to the next one), you should provide the key path (argument name) argument, something like this:

```<code>let p1 = NSPredicate(format: "%K == %@", "recordID", CKRecord.Reference(recordID: recID, action: CKRecord_Reference_Action.none))
let p2 = NSPredicate(format: "%K == %@", "recordID", CKRecord.Reference(record: searchRecord, action: CKRecord_Reference_Action.none))
</code>```

Since I don't understand exactly what you are doing, you may need to tweak those two lines a bit.  But the point is that, given your format string, you need three arguments to NSPredicate(format:), and the middle one needs to be a string representing a key path or attribute name.

Body:
I have a CloudKit app where records are stored locally in CoreData. When creating the CoreData record, a UUID is generated and populated to the system recordName field. The app creates and saves records in CoreData then uploads the records to CloudKit. This works fine.

However, I am now coding to modify a record and am not able to fetch a record by the recordName UUID. I have not been successful setting a predicate to search for only that record. I can retrieve all records with TRUEPREDICATE and I can also retrieve a single record from a field I created in the CloudKit record type. I created a field called myRecordName where I store the same UUID as the CloudKit recordName. A query using the myRecordName works fine.

I have shown three methods below for the predicates. If p1 and p2 are not both commented out the app crashes on running. I assume I am missing something really simple here. Any guidance would be appreciated. Xcode 10.2.1, iOS 12.2, testing on a real device.

If either p1 or p2 or both are not commented out, the console shows:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CKReference rangeOfString:]:
  unrecognized selector sent to instance 0x280878520'

func queryDatabase() {

    let recordZone = CKRecordZone(zoneName: "PrimaryZone")
    let recName = "0E763775-5AD3-4A50-BFB8-AC310180E8A2"

    let recID = CKRecord.ID(recordName: recName, zoneID: recordZone.zoneID)
    let searchRecord = CKRecord(recordType: "Patient", recordID: recID)

    let p1 = NSPredicate(format: "%K == %@", CKRecord.Reference(recordID: recID, action: CKRecord_Reference_Action.none))
    let p2 = NSPredicate(format: "%K == %@", CKRecord.Reference(record: searchRecord, action: CKRecord_Reference_Action.none))

    //let predicate = NSPredicate(format: "TRUEPREDICATE")
    let p3 = NSPredicate(format: "myRecordName = %@", recName)

    let query = CKQuery(recordType: "Patient", predicate: p3)
    let sortDescriptor = NSSortDescriptor(key: "lastNameText", ascending: true)
    query.sortDescriptors = [sortDescriptor]

    privateDatabase.perform(query, inZoneWith: recordZone.zoneID) { (results, error) in
        if error != nil {
            print("error querying database\(String(describing: error?.localizedDescription))")
        } else {

            DVC.ckRecords = results!
            //print(results!)
            print(DVC.ckRecords.first!)

        }//if error else
    }//perform query block

}//queryDatabase

Body:
I've never used CloudKit, so maybe I'm wrong, but…

The two problem lines of code, p1= and p2=, attempt to create a NSPredicate using a format string.  Each format string contains two var arg substitutions, aka placeholders: %K and %@.  So for this to work, that format string argument must be followed by two more arguments: first a key path, which should be a string (%K), and second a object for its value (%@).  For your purposes here, the key path is probably just an attribute name.

But you have only provided one more argument, a CKRecord.Reference object, which the system tries to parse for the first (attribute name, string) argument.  The error you are getting is typical of what happens when the system tries to parse an object such as CKRecord.Reference when it was expecting a string.  Swift may be quite type safe but old-fashioned NSPredicate var args functions are not :)

To fix this problem (and move on to the next one), you should provide the key path (argument name) argument, something like this:

let p1 = NSPredicate(format: "%K == %@", "recordID", CKRecord.Reference(recordID: recID, action: CKRecord_Reference_Action.none))
let p2 = NSPredicate(format: "%K == %@", "recordID", CKRecord.Reference(record: searchRecord, action: CKRecord_Reference_Action.none))

Since I don't understand exactly what you are doing, you may need to tweak those two lines a bit.  But the point is that, given your format string, you need three arguments to NSPredicate(format:), and the middle one needs to be a string representing a key path or attribute name.


问:
Can someone explain what happens internally in Second for loop?
I understand, that a char can be casted explicitly by me and by compiler implicitly.

In my code in first "for" loop Compiler converts char to int type automatically by implicit type casting. Since char is of size 2 bytes, it get fit into size of 4 bytes.

I am confused, how a integer number be assigned to char variable without explicit casting, since int is of 4 bytes and without explicitly casting it to char using cast operator.

```<code>// Compiler converts char to int type automatically by implicit type casting.
        for (int i = 'A'; i <= 'Z'; i++) {
            System.out.print(i + " ");
        }   System.out.println();

        for (char c = 65; c <= 90; c++) {
            System.out.print(c + " ");
        }   System.out.println();
</code>```

答:
"It's not assigning an int, it's using UNICODE code for characters."

(eg. A=65 in UNICODE or even ASCII @RealSkeptic)
It's just another way of initialization.

```<code>    char A = 65;
    char a = 'a';
    System.out.println(A); \\A
    System.out.println((int)A); \\65
    System.out.println(a); \\a
    System.out.println((int)a); \\97
</code>```

Def. Oracle for char:

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive)

Kindly look on comments also.

Body:
I understand, that a char can be casted explicitly by me and by compiler implicitly.

In my code in first "for" loop Compiler converts char to int type automatically by implicit type casting. Since char is of size 2 bytes, it get fit into size of 4 bytes.

I am confused, how a integer number be assigned to char variable without explicit casting, since int is of 4 bytes and without explicitly casting it to char using cast operator.

// Compiler converts char to int type automatically by implicit type casting.
        for (int i = 'A'; i <= 'Z'; i++) {
            System.out.print(i + " ");
        }   System.out.println();

        for (char c = 65; c <= 90; c++) {
            System.out.print(c + " ");
        }   System.out.println();

Body:
"It's not assigning an int, it's using UNICODE code for characters."

(eg. A=65 in UNICODE or even ASCII @RealSkeptic)
It's just another way of initialization.

    char A = 65;
    char a = 'a';
    System.out.println(A); \\A
    System.out.println((int)A); \\65
    System.out.println(a); \\a
    System.out.println((int)a); \\97

Def. Oracle for char:

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive)

Kindly look on comments also.


问:
Cant onClick event do
 tag React
I have a sideBar that opens when I click on a button and i have
 items there.

I want do add an onCLick event to those items but, onClick event fires when page is loaded and when ever I click on  elements.

Any information is helpful, thank you.

```<code>const Sidedraw = props => {
  let drawClass = "sideDraw";
  if (props.show) {
    drawClass = "sideDraw open";
  }
  return (
    <nav className={drawClass}>
      <ul>
        <li className="matches" onclick={console.log("work work")}>
          Pro matches
        </li>
        <li className="matches">Public mathes</li>
        <li className="matches">Players</li>
        <li className="matches">Teams</li>
      </ul>
    </nav>
  );
};
</code>```

答:
you must add clickeventhandler to each element you want to perform some actions.

Pro matches

```
<p>and you must add that function ie</p>
```handleValueChange = (e) => {
    // ...
}
```

Title: Cant onClick event do <li> tag React

Body:
I have a sideBar that opens when I click on a button and i have
 items there.

I want do add an onCLick event to those items but, onClick event fires when page is loaded and when ever I click on  elements.

Any information is helpful, thank you.

const Sidedraw = props => {
  let drawClass = "sideDraw";
  if (props.show) {
    drawClass = "sideDraw open";
  }
  return (

          Pro matches

Public mathes

Players

Teams

  );
};

Body:
you must add clickeventhandler to each element you want to perform some actions.

<li className="matches" onClick={handleValueChange}>Pro matches</li>

and you must add that function ie

handleValueChange = (e) => {
    // ...
}


问:
I need to write Regx for text field validation, which start with either 'iqn.yyyy-mm.com.' or 'eqn.'
I need to write Regx for text field validation, which start with either 'iqn.yyyy-mm.com.' or 'eqn.'
After this any number of character or numeric value is allowed
Here 'yyyy-mm' is year and month.</p>

答:
If you mean is "either 'iqn.yyyy-mm.com.' or 'eqn.'":

```<code>pattern = new RegExp('/^(iqn\.\d{4}-\d{2}\.com\.)|(eqn\.)$/');

var str = 'iqn.2019-05.com.';
pattern.test(str); // -> true

var str = 'eqn';
pattern.test(str); // -> true

var str = 'anything else';
pattern.test(str); // -> false
</code>```

or, if you mean is "either 'iqn.yyyy-mm.com.' or 'eqn.yyyy-mm.com.'":

```<code>pattern = new RegExp('/^[ie]qn\.\d{4}-\d{2}\.com\.$/');

var str = 'iqn.2019-05.com.';
pattern.test(str); // -> true

var str = 'eqn.2019-05.com.';
pattern.test(str); // -> true

var str = 'anything else';
pattern.test(str); // -> false
</code>```

Body:
If you mean is "either 'iqn.yyyy-mm.com.' or 'eqn.'":

pattern = new RegExp('/^(iqn\.\d{4}-\d{2}\.com\.)|(eqn\.)$/');

var str = 'iqn.2019-05.com.';
pattern.test(str); // -> true

var str = 'eqn';
pattern.test(str); // -> true

var str = 'anything else';
pattern.test(str); // -> false

or, if you mean is "either 'iqn.yyyy-mm.com.' or 'eqn.yyyy-mm.com.'":

pattern = new RegExp('/^[ie]qn\.\d{4}-\d{2}\.com\.$/');

var str = 'iqn.2019-05.com.';
pattern.test(str); // -> true

var str = 'eqn.2019-05.com.';
pattern.test(str); // -> true

var str = 'anything else';
pattern.test(str); // -> false


问:
Not able to locate web element on chrome browser's settings popup
I am trying to clear browser cache, for which i need to click on clear data button of browser setting popup, but, i am not able to write xpath for the button on chrome browser

i have tried inspecting the element to find out if the button is on a iframe but its not in iframe, so i have decided to try it with an with out iframe snippet, either of ways the element is not traces out in dom

```<code>    public void clearBrowserCache() throws InterruptedException{
    driver.get("chrome://settings/clearBrowserData");
    Thread.sleep(2000);
    System.out.println(driver.getWindowHandles());
    String windowIds=driver.getWindowHandle();

   // driver.switchTo().frame(windowIds);
      driver.findElement(By.cssSelector(
      [id=clearBrowsingDataConfirm]")).click();

    }
</code>```

Expected is that i should be able to click on the clear data button
Actual is that i am not able to find out the xpath for of the emlement

答:
I answered how to reach inside the Shadow DOM in an other question.

You can read the whole thing at the link, but the basics are you create a "starting point" WebElement at the Shadow DOM via JavaScript, then all future look-ups reference it:

```<code>WebElement button = startingPoint.findElement(By.cssSelector("..."));
</code>```

Body:
I am trying to clear browser cache, for which i need to click on clear data button of browser setting popup, but, i am not able to write xpath for the button on chrome browser

i have tried inspecting the element to find out if the button is on a iframe but its not in iframe, so i have decided to try it with an with out iframe snippet, either of ways the element is not traces out in dom

    public void clearBrowserCache() throws InterruptedException{
    driver.get("chrome://settings/clearBrowserData");
    Thread.sleep(2000);
    System.out.println(driver.getWindowHandles());
    String windowIds=driver.getWindowHandle();

   // driver.switchTo().frame(windowIds);
      driver.findElement(By.cssSelector(
      [id=clearBrowsingDataConfirm]")).click();

    }

Expected is that i should be able to click on the clear data button
Actual is that i am not able to find out the xpath for of the emlement

Body:
I answered how to reach inside the Shadow DOM in an other question.

You can read the whole thing at the link, but the basics are you create a "starting point" WebElement at the Shadow DOM via JavaScript, then all future look-ups reference it:

WebElement button = startingPoint.findElement(By.cssSelector("..."));


问:
make textbox value another textbox with checkbox in jquery
I want to assign a textbox value to another textbox when the checkbox is ticked. The values are not showing in the textbox when I click the checkbox.

function filladdress() {
  var address1 = $("#delivery_address").val();
  var suburb1 = $("#delivery_suburb").val();
  var post1 = $("#delivery_postcode").val();
  var textbox = $("#same-address").attr('checked')

  if textbox.attr('checked', true)
  $("#billing_address").val(address1);
  $("#billing_suburb").val(suburb1);
  $("#billing_postcode").val(post1);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Delivery Address</h2>
  <p>Address</p>
  <input id="delivery_address" type="text" name="delivery_address" />
  <p>Suburb</p>
  <input id="delivery_suburb" type="text" name="delivery_suburb" />
  <p>PostCode</p>
  <input id="delivery_postcode" type="text" name="delivery_postcode" />
</div>
<label>
  <input type="checkbox" name="same-address" value="checked">
  same as delivery address
</label>

  <h2>Billing Address</h2>
  <p>Address</p>
  <input id="billing_address" type="text" name="billing_address" />
  <p>Suburb</p>
  <input id="billing_suburb" type="text" name="billing_suburb" />
  <p>PostCode</p>
  <input id="billing_postcode" type="text" name="billing_postcode" />
</div></code>```

答:
There's several issues with your current logic:

You have an unnecessary ) at the end of the JS.

The filladdress() function is never called. Presumably you want to do this when the checkbox is changed.

The if statement syntax is broken. Firstly you need to wrap the condition in parentheses. Secondly, you're using the setter of attr(), not the getter, so the condition would always equate to true due to type coercion of the resulting jQuery object.

The is no #same-address element in the HTML. I assume this should be the checkbox itself.

You're missing the opening
 tags

Once you address all these issues, and add an unobtrusive event handler, the code should look something like this:

$(function() {
  var $delAddress1 = $("#delivery_address");
  var $delSuburb1 = $("#delivery_suburb");
  var $delPostcode = $("#delivery_postcode");

  $("#same-address").change(function() {
    if (this.checked) {
      $("#billing_address").val($delAddress1.val());
      $("#billing_suburb").val($delSuburb1.val());
      $("#billing_postcode").val($delPostcode.val());
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h2>Delivery Address</h2>
  <p>Address</p>
  <input id="delivery_address" type="text" name="delivery_address" />
  <p>Suburb</p>
  <input id="delivery_suburb" type="text" name="delivery_suburb" />
  <p>PostCode</p>
  <input id="delivery_postcode" type="text" name="delivery_postcode" />
</div>
<label>
  <input type="checkbox" name="same-address" id="same-address" value="checked">
  same as delivery address
</label>
<div>
  <h2>Billing Address</h2>
  <p>Address</p>
  <input id="billing_address" type="text" name="billing_address" />
  <p>Suburb</p>
  <input id="billing_suburb" type="text" name="billing_suburb" />
  <p>PostCode</p>
  <input id="billing_postcode" type="text" name="billing_postcode" />
</div></code>```

Body:
I want to assign a textbox value to another textbox when the checkbox is ticked. The values are not showing in the textbox when I click the checkbox.

function filladdress() {
  var address1 = $("#delivery_address").val();
  var suburb1 = $("#delivery_suburb").val();
  var post1 = $("#delivery_postcode").val();
  var textbox = $("#same-address").attr('checked')

  if textbox.attr('checked', true)
  $("#billing_address").val(address1);
  $("#billing_suburb").val(suburb1);
  $("#billing_postcode").val(post1);
})

Delivery Address

Address

  <input id="delivery_address" type="text" name="delivery_address" />

Suburb

  <input id="delivery_suburb" type="text" name="delivery_suburb" />

PostCode

  <input id="delivery_postcode" type="text" name="delivery_postcode" />

  <input type="checkbox" name="same-address" value="checked">
  same as delivery address

Billing Address

Address

  <input id="billing_address" type="text" name="billing_address" />

Suburb

  <input id="billing_suburb" type="text" name="billing_suburb" />

PostCode

  <input id="billing_postcode" type="text" name="billing_postcode" />

Body:
There's several issues with your current logic:

You have an unnecessary ) at the end of the JS.

The filladdress() function is never called. Presumably you want to do this when the checkbox is changed.

The if statement syntax is broken. Firstly you need to wrap the condition in parentheses. Secondly, you're using the setter of attr(), not the getter, so the condition would always equate to true due to type coercion of the resulting jQuery object.

The is no #same-address element in the HTML. I assume this should be the checkbox itself.

You're missing the opening <div> tags

Once you address all these issues, and add an unobtrusive event handler, the code should look something like this:

$(function() {
  var $delAddress1 = $("#delivery_address");
  var $delSuburb1 = $("#delivery_suburb");
  var $delPostcode = $("#delivery_postcode");

  $("#same-address").change(function() {
    if (this.checked) {
      $("#billing_address").val($delAddress1.val());
      $("#billing_suburb").val($delSuburb1.val());
      $("#billing_postcode").val($delPostcode.val());
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <h2>Delivery Address</h2>
  <p>Address</p>
  <input id="delivery_address" type="text" name="delivery_address" />
  <p>Suburb</p>
  <input id="delivery_suburb" type="text" name="delivery_suburb" />
  <p>PostCode</p>
  <input id="delivery_postcode" type="text" name="delivery_postcode" />
</div>
<label>
  <input type="checkbox" name="same-address" id="same-address" value="checked">
  same as delivery address
</label>
<div>
  <h2>Billing Address</h2>
  <p>Address</p>
  <input id="billing_address" type="text" name="billing_address" />
  <p>Suburb</p>
  <input id="billing_suburb" type="text" name="billing_suburb" />
  <p>PostCode</p>
  <input id="billing_postcode" type="text" name="billing_postcode" />
</div>


问:
My data doesnt prevails on my sql azure database, after login
I'm using Azure Mobile App SDK, and I have 4 tables Account, personal, Labor and Subscription.
I'll leave the code here of my models:

```<code>public class Account : TableData
{
    [JsonProperty(PropertyName ="userid")]
    public string UserId { get; set; }
    [JsonProperty(PropertyName = "personalid")]
    public string PersonalId { get; set; }
    [JsonProperty(PropertyName = "subscriptionid")]
    public string SubscriptionId { get; set; }
    [JsonProperty(PropertyName = "subscriptionappleid")]
    public string SubscriptionAppleId { get; set; }
    [JsonProperty(PropertyName = "subscriptiongoogleid")]
    public string SubscriptionGoogleId { get; set; }
    [JsonProperty(PropertyName = "laborid")]
    public string LaborId { get; set; }

    public override bool Equals(object obj)
    {
        return Equals<Account>(obj, this);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

public class Personal : TableData
{
    [Required]
    [StringLength(50)]
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }
    [Required]
    [StringLength(50)]
    [JsonProperty(PropertyName = "dadlastname")]
    public string DadLastName { get; set; }
    [Required]
    [StringLength(50)]
    [JsonProperty(PropertyName = "momlastname")]
    public string MomLastName { get; set; }
    [Required]
    [StringLength(50)]
    [JsonProperty(PropertyName = "email")]
    public string Email { get; set; }
    [Required]
    [JsonProperty(PropertyName = "sex")]
    public Gender Sex { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "birthdate")]
    public DateTime? BirthDate { get; set; }

    public override bool Equals(object obj)
    {
        return Equals<Personal>(obj, this);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

public class Subscription : TableData
{
    [Required]
    [JsonProperty(PropertyName = "subscriptiontype")]
    public SubscriptionType SubscriptionType { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "subscriptiondate")]
    public DateTime? SubscriptionDate { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "expirationdate")]
    public DateTime? ExpirationDate { get; set; }
    [Required]
    [JsonProperty(PropertyName = "standardsubscriptiontype")]
    public SubscriptionType StandardSubscriptionType { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "standardsubscriptiondate")]
    public DateTime? StandardSubscriptionDate { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "standardexpirationdate")]
    public DateTime? StandardExpirationDate { get; set; }

    public override bool Equals(object obj)
    {
        return Equals<Subscription>(obj, this);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}
</code>```

now as you can see Account model has Foreing Keys to Personal, Labor and Subscription.
whenever I make a change on Personal, labor or susbcription i updated my table and I can see at my cloud that the information has been changed, for example.

at Personal model I make a change on my birthdate from Oct 5th, 1981 to Oct. 6th 1981. and it updates successfully, but if I close my app and after 30 mins or 20 minutes I open the app again as soon as I login using the login method who has nothing to do with Sql Azure, the database information goes back to the previous values, and I have to wait like 20 or 30 minutes for this to happend I close my app and the reopen it inmediately the database or the record doesnt get affected.

Now this only happens with the table I mentioned before, If I make edition to other tables, they dont get affected by the situation I mentioned before.

Am I doing something wrong??? this didnt happened before, I have tried retiring offline support for this tables thinking that might be an issue with sqlLite but the issue still prevails.

I ignore the reason, of why is this happening.

Hopefully you can help me with some ideas, I dont have any clue about it.
Should I get rid of Foreing Keys???Should I delete the whole record and create a new one a reassign a new PersonalId or LaborId to the Account Model??? as a workaround.

答:
Firstable I just solved it. I want to apologize because it was MY MISTAKE, it turns out that I hard coded my account data at the Configuration seeding method of  my cloud which run everytime someone login, the Azure Mobile Apps SDK has no flaws on it.

I had just deleted the data that rollback my information, or better said to updated my information.
It was a hard error to find because my code was fine, it was the behavior of my cloud that was wrong due to hardcoded the account information because I had an issue months ago, were i need to hardcode my account information in my cloud.

anyways I think this issue can be close now!!!

Body:
I'm using Azure Mobile App SDK, and I have 4 tables Account, personal, Labor and Subscription.
I'll leave the code here of my models:

public class Account : TableData
{
    [JsonProperty(PropertyName ="userid")]
    public string UserId { get; set; }
    [JsonProperty(PropertyName = "personalid")]
    public string PersonalId { get; set; }
    [JsonProperty(PropertyName = "subscriptionid")]
    public string SubscriptionId { get; set; }
    [JsonProperty(PropertyName = "subscriptionappleid")]
    public string SubscriptionAppleId { get; set; }
    [JsonProperty(PropertyName = "subscriptiongoogleid")]
    public string SubscriptionGoogleId { get; set; }
    [JsonProperty(PropertyName = "laborid")]
    public string LaborId { get; set; }

    public override bool Equals(object obj)
    {
        return Equals<Account>(obj, this);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

public class Personal : TableData
{
    [Required]
    [StringLength(50)]
    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }
    [Required]
    [StringLength(50)]
    [JsonProperty(PropertyName = "dadlastname")]
    public string DadLastName { get; set; }
    [Required]
    [StringLength(50)]
    [JsonProperty(PropertyName = "momlastname")]
    public string MomLastName { get; set; }
    [Required]
    [StringLength(50)]
    [JsonProperty(PropertyName = "email")]
    public string Email { get; set; }
    [Required]
    [JsonProperty(PropertyName = "sex")]
    public Gender Sex { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "birthdate")]
    public DateTime? BirthDate { get; set; }

    public override bool Equals(object obj)
    {
        return Equals<Personal>(obj, this);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

public class Subscription : TableData
{
    [Required]
    [JsonProperty(PropertyName = "subscriptiontype")]
    public SubscriptionType SubscriptionType { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "subscriptiondate")]
    public DateTime? SubscriptionDate { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "expirationdate")]
    public DateTime? ExpirationDate { get; set; }
    [Required]
    [JsonProperty(PropertyName = "standardsubscriptiontype")]
    public SubscriptionType StandardSubscriptionType { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "standardsubscriptiondate")]
    public DateTime? StandardSubscriptionDate { get; set; }
    [Required]
    [Column(TypeName = "datetime2")]
    [JsonProperty(PropertyName = "standardexpirationdate")]
    public DateTime? StandardExpirationDate { get; set; }

    public override bool Equals(object obj)
    {
        return Equals<Subscription>(obj, this);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

now as you can see Account model has Foreing Keys to Personal, Labor and Subscription.
whenever I make a change on Personal, labor or susbcription i updated my table and I can see at my cloud that the information has been changed, for example.

at Personal model I make a change on my birthdate from Oct 5th, 1981 to Oct. 6th 1981. and it updates successfully, but if I close my app and after 30 mins or 20 minutes I open the app again as soon as I login using the login method who has nothing to do with Sql Azure, the database information goes back to the previous values, and I have to wait like 20 or 30 minutes for this to happend I close my app and the reopen it inmediately the database or the record doesnt get affected.

Now this only happens with the table I mentioned before, If I make edition to other tables, they dont get affected by the situation I mentioned before.

Am I doing something wrong??? this didnt happened before, I have tried retiring offline support for this tables thinking that might be an issue with sqlLite but the issue still prevails.

I ignore the reason, of why is this happening.

Hopefully you can help me with some ideas, I dont have any clue about it.
Should I get rid of Foreing Keys???Should I delete the whole record and create a new one a reassign a new PersonalId or LaborId to the Account Model??? as a workaround.


问:
start playing audio from a background task via AVAudioPlayer in Xcode
I am trying to start playing a sound from a background task via an AVAudioPlayer that is instantiated then, so here's what I've got.

For readability I cut out all user selected values.

```<code>- (void)restartHandler {
    bg = 0;
    bg = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:bg];
    }];
    tim = [NSTimer timerWithTimeInterval:.1 target:self selector:@selector(upd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:tim forMode:NSRunLoopCommonModes];
}

- (void)upd {
    if ([[NSDate date] timeIntervalSinceDate:startDate] >= difference) {
        [self playSoundFile];
        [tim invalidate];
        [[UIApplication sharedApplication] endBackgroundTask:bg];
    }
}

- (void)playSoundFile {

    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];

    // new player object
    _player = [[AVQueuePlayer alloc] init];
    [_player insertItem:[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"Manamana" withExtension:@"m4a"]] afterItem:nil];

    [_player setVolume:.7];
    [_player play];

    NSLog(@"Testing");
}
</code>```

Explanation: bg, tim, startDate, difference and _player are globally declared variables. I call - (void)restartHandler from a user-fired method and inside it start a 10Hz repeating timer for - (void)upd. When a pre-set difference is reached, - (void)playSoundFile gets called and initiates and starts the player. The testing NSLog at the end of the method gets called.

Now the strange thing is if I call - (void)playSoundFile when the app is active, everything works out just fine, but if I start it from the background task it just won't play any sound.

Edit

So I tried using different threads at runtime and as it seems, if the Player is not instantiated on the Main Thread this same problem will appear.
I also tried using AVPlayer and AVAudioPlayer where the AVAudioPlayer's .playing property did return YES and still no sound was playing.

答:
What fixed it for me was to start playing some audio just as application quits, so I added 1sec blank audio in applicationWillResignActive in the AppDelegate</p>

```<code>func applicationWillResignActive(_ application: UIApplication) {

        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            self.endBackgroundUpdateTask(true)
        })

        let secSilence = URL(fileURLWithPath: Bundle.main.path(forResource: "1secSilence", ofType: "mp3")!)

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: secSilence)
        }
        catch {
            print("Error in loading sound file")
        }

        audioPlayer.prepareToPlay()
        audioPlayer.play()

}
</code>```

Body:
I am trying to start playing a sound from a background task via an AVAudioPlayer that is instantiated then, so here's what I've got.

For readability I cut out all user selected values.

- (void)restartHandler {
    bg = 0;
    bg = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:bg];
    }];
    tim = [NSTimer timerWithTimeInterval:.1 target:self selector:@selector(upd) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:tim forMode:NSRunLoopCommonModes];
}

- (void)upd {
    if ([[NSDate date] timeIntervalSinceDate:startDate] >= difference) {
        [self playSoundFile];
        [tim invalidate];
        [[UIApplication sharedApplication] endBackgroundTask:bg];
    }
}

- (void)playSoundFile {

    NSError *sessionError = nil;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];

    // new player object
    _player = [[AVQueuePlayer alloc] init];
    [_player insertItem:[AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@"Manamana" withExtension:@"m4a"]] afterItem:nil];

    [_player setVolume:.7];
    [_player play];

    NSLog(@"Testing");
}

Explanation: bg, tim, startDate, difference and _player are globally declared variables. I call - (void)restartHandler from a user-fired method and inside it start a 10Hz repeating timer for - (void)upd. When a pre-set difference is reached, - (void)playSoundFile gets called and initiates and starts the player. The testing NSLog at the end of the method gets called.

Now the strange thing is if I call - (void)playSoundFile when the app is active, everything works out just fine, but if I start it from the background task it just won't play any sound.

Edit

So I tried using different threads at runtime and as it seems, if the Player is not instantiated on the Main Thread this same problem will appear.
I also tried using AVPlayer and AVAudioPlayer where the AVAudioPlayer's .playing property did return YES and still no sound was playing.

Body:
What fixed it for me was to start playing some audio just as application quits, so I added 1sec blank audio in applicationWillResignActive in the AppDelegate

func applicationWillResignActive(_ application: UIApplication) {

        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            self.endBackgroundUpdateTask(true)
        })

        let secSilence = URL(fileURLWithPath: Bundle.main.path(forResource: "1secSilence", ofType: "mp3")!)

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: secSilence)
        }
        catch {
            print("Error in loading sound file")
        }

        audioPlayer.prepareToPlay()
        audioPlayer.play()

}


答:
First of your if statement is wrong, second there is nothing triggering the filladdress function

Working demo

function filladdress() {
  var address1 = $("#delivery_address").val();
  var suburb1 = $("#delivery_suburb").val();
  var post1 = $("#delivery_postcode").val();

  if ($("[name=same-address]").prop('checked')) {
    $("#billing_address").val(address1);
    $("#billing_suburb").val(suburb1);
    $("#billing_postcode").val(post1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Delivery Address</h2>
<p>Address</p>
<input id="delivery_address" type="text" name="delivery_address" />
<p>Suburb</p>
<input id="delivery_suburb" type="text" name="delivery_suburb" />
<p>PostCode</p>
<input id="delivery_postcode" type="text" name="delivery_postcode" />
</div>
<label>
  <input type="checkbox" name="same-address" onchange="filladdress()" value="checked">
  same as delivery address
</label>

<h2>Billing Address</h2>
<p>Address</p>
<input id="billing_address" type="text" name="billing_address" />
<p>Suburb</p>
<input id="billing_suburb" type="text" name="billing_suburb" />
<p>PostCode</p>
<input id="billing_postcode" type="text" name="billing_postcode" />
</div></code>```

Title: make textbox value another textbox with checkbox in jquery

Body:
First of your if statement is wrong, second there is nothing triggering the filladdress function

Working demo

function filladdress() {
  var address1 = $("#delivery_address").val();
  var suburb1 = $("#delivery_suburb").val();
  var post1 = $("#delivery_postcode").val();

  if ($("[name=same-address]").prop('checked')) {
    $("#billing_address").val(address1);
    $("#billing_suburb").val(suburb1);
    $("#billing_postcode").val(post1);
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Delivery Address</h2>
<p>Address</p>
<input id="delivery_address" type="text" name="delivery_address" />
<p>Suburb</p>
<input id="delivery_suburb" type="text" name="delivery_suburb" />
<p>PostCode</p>
<input id="delivery_postcode" type="text" name="delivery_postcode" />
</div>
<label>
  <input type="checkbox" name="same-address" onchange="filladdress()" value="checked">
  same as delivery address
</label>

<h2>Billing Address</h2>
<p>Address</p>
<input id="billing_address" type="text" name="billing_address" />
<p>Suburb</p>
<input id="billing_suburb" type="text" name="billing_suburb" />
<p>PostCode</p>
<input id="billing_postcode" type="text" name="billing_postcode" />
</div>