问:
delete lines before and after a string is found using sed
below is my xml file content -

```<code><?xml version="1.0" encoding="UTF-8"?>
<artifactListing>
    <folder id="REPORTMART" path="/Repository Objects" pathAlias="/00"
        modifiedBy="Maria" lastUpdated="1480426973000" description="Hyperion Root Folder"/>
    <folder id="DATASOURCESFOLD"
        path="/Repository Objects/HRInternalFolder/DataSources"
        pathAlias="/00/HRInternal/DataSources" modifiedBy="Maria" lastUpdated="1492814854000"/>
    <folder id="HRINTERNALFOLD"
        path="/Repository Objects/HRInternalFolder"
        pathAlias="/00/HRInternal" modifiedBy="Maria" lastUpdated="1492814854000"/>
    <folder id="00000158e031595b-0000-0782-0ae57730"
        path="/Repository Objects/TRCS" pathAlias="/00/0"
        modifiedBy="demoadmin" lastUpdated="1492814854000" description="TRCS"/>
    <resource id="JavaScriptUpdateResizeOn_dds_js"
        path="/Repository Objects/Administration/Impact Manager/Script Repository"
        pathAlias="/00/Administration/0/Script_Repository"
        modifiedBy="Maria" lastUpdated="1492814880000"
        description="JavaScript Update DDS configuration with Layout Manager"
        name="JavaScriptUpdateResizeOn_dds.js" type="text/im-javascript" size="-1"/>
    <resource id="449cb46e6b4492f3afb8ef693dffb43a90cdd992"
        path="/Security" pathAlias="/02"
        description="Shared Services Administrator"
        name="epm_default_cloud_admin" type="UserPreferences" size="-1"/>
    <resource id="0f62187cf5a8f5aecec7a9879c9e40497d6d8649"
        path="/Security" pathAlias="/02" description="" name="Jacob"
        type="UserPreferences" size="-1"/>
    <resource id="0df02da8548eeef2174c97c2ade67b4c5adc3160"
        path="/Security" pathAlias="/02" description="" name="Henry"
        type="UserPreferences" size="-1"/>
    <resource id="33dca1c0c1c5ae78f67580a76d9c6aba6a172e20"
        path="/Security" pathAlias="/02" description="" name="Susan"
        type="UserPreferences" size="-1"/>
    <resource id="3e182b1ea9376483a38614d916a0b666ef531b6d"
        path="/Security" pathAlias="/02" description="" name="Maria"
        type="UserPreferences" size="-1"/>
    <resource id="0f62187cf5a8f5aecec7a9879c9e40497d6d8649"
        path="/Security" pathAlias="/02" description="" name="Jacques"
        type="UserPreferences" size="-1"/>
    <resource id="0df02da8548eeef2174c97c2ade67b4c5adc3160"
        path="/Security" pathAlias="/02" description="" name="Frank"
        type="UserPreferences" size="-1"/>
    <resource id="PP_3e182b1ea9376483a38614d916a0b666ef531b6d_0"
        path="/Product Preferences" pathAlias="/05"
        description="This is your default Personal Page."
        name="My Personal Page" type="PersonalPageContent" size="-1"/>
</artifactListing>
</code>```

now using sed I would like to delete entire resource tag if "Susan" string is found within it, other non-Susan resource tag's should not be considered.
In this scenario, it's only 1 line before and after string, I've other cases where there are more line within the resource tag.

答:
Using XML parser is the right way for manipulating XML documents.

xmlstarlet solution:

```<code>xmlstarlet ed -d '//resource[@name="Susan"]' yourxmlfile
</code>```

ed - edit mode

-d - delete action

//resource[@name="Susan"] - xpath expression

Body:
below is my xml file content -

<?xml version="1.0" encoding="UTF-8"?>
<artifactListing>
    <folder id="REPORTMART" path="/Repository Objects" pathAlias="/00"
        modifiedBy="Maria" lastUpdated="1480426973000" description="Hyperion Root Folder"/>
    <folder id="DATASOURCESFOLD"
        path="/Repository Objects/HRInternalFolder/DataSources"
        pathAlias="/00/HRInternal/DataSources" modifiedBy="Maria" lastUpdated="1492814854000"/>
    <folder id="HRINTERNALFOLD"
        path="/Repository Objects/HRInternalFolder"
        pathAlias="/00/HRInternal" modifiedBy="Maria" lastUpdated="1492814854000"/>
    <folder id="00000158e031595b-0000-0782-0ae57730"
        path="/Repository Objects/TRCS" pathAlias="/00/0"
        modifiedBy="demoadmin" lastUpdated="1492814854000" description="TRCS"/>
    <resource id="JavaScriptUpdateResizeOn_dds_js"
        path="/Repository Objects/Administration/Impact Manager/Script Repository"
        pathAlias="/00/Administration/0/Script_Repository"
        modifiedBy="Maria" lastUpdated="1492814880000"
        description="JavaScript Update DDS configuration with Layout Manager"
        name="JavaScriptUpdateResizeOn_dds.js" type="text/im-javascript" size="-1"/>
    <resource id="449cb46e6b4492f3afb8ef693dffb43a90cdd992"
        path="/Security" pathAlias="/02"
        description="Shared Services Administrator"
        name="epm_default_cloud_admin" type="UserPreferences" size="-1"/>
    <resource id="0f62187cf5a8f5aecec7a9879c9e40497d6d8649"
        path="/Security" pathAlias="/02" description="" name="Jacob"
        type="UserPreferences" size="-1"/>
    <resource id="0df02da8548eeef2174c97c2ade67b4c5adc3160"
        path="/Security" pathAlias="/02" description="" name="Henry"
        type="UserPreferences" size="-1"/>
    <resource id="33dca1c0c1c5ae78f67580a76d9c6aba6a172e20"
        path="/Security" pathAlias="/02" description="" name="Susan"
        type="UserPreferences" size="-1"/>
    <resource id="3e182b1ea9376483a38614d916a0b666ef531b6d"
        path="/Security" pathAlias="/02" description="" name="Maria"
        type="UserPreferences" size="-1"/>
    <resource id="0f62187cf5a8f5aecec7a9879c9e40497d6d8649"
        path="/Security" pathAlias="/02" description="" name="Jacques"
        type="UserPreferences" size="-1"/>
    <resource id="0df02da8548eeef2174c97c2ade67b4c5adc3160"
        path="/Security" pathAlias="/02" description="" name="Frank"
        type="UserPreferences" size="-1"/>
    <resource id="PP_3e182b1ea9376483a38614d916a0b666ef531b6d_0"
        path="/Product Preferences" pathAlias="/05"
        description="This is your default Personal Page."
        name="My Personal Page" type="PersonalPageContent" size="-1"/>
</artifactListing>

now using sed I would like to delete entire resource tag if "Susan" string is found within it, other non-Susan resource tag's should not be considered.
In this scenario, it's only 1 line before and after string, I've other cases where there are more line within the resource tag.

Body:
Using XML parser is the right way for manipulating XML documents.

xmlstarlet solution:

xmlstarlet ed -d '//resource[@name="Susan"]' yourxmlfile

ed - edit mode

-d - delete action

//resource[@name="Susan"] - xpath expression


来源: stackexchange

问:
How to deploy Azure service fabric project on to a remote cluster(Azure)
I have Created a cluster in Azure http://******.######.cloudapp.azure.com:19080
but don't know how to deploy my service fabric project on to it.
Link to application manifest
ApplicationManifest.xml</p>

答:
It's pretty well documented, unless you are getting specific errors, which you then will need to reference to get some worthwhile help

https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-publish-app-remote-cluster

ContentLicense: CC BY-SA 3.0


问:
How to get progress information inside a range based for loop?
I have a very long running for loop and I would like to print out some progress information.

With a normal for loop this is easy, since you can divide the loop-variable by the maximum to get a progress indicator, i.e. do something like this:

```<code>for(int i = 0; i<container.size(); i++) {
  if(i%10==0) System.out.println("Progress " +  Double.toString(i/container.size()*100.0) + "%.")
}
</code>```

Is there a way to do something like this without adding a counter variable (which somehow defeats the purpose of the range based for loop)?

```<code>//... Foreach loop over all elements in arr.
for (type var : arr) {
    body-of-loop
    // print progress info here?
}
</code>```

答:
Regarding the core of the question: You cannot derive any progress information from a range-based for-loop. Mainly because there may not be any. You could easily create an Iterable for which

```<code>for (T t : iterable) {
    ...
}
</code>```

is an infinite loop. You have to know the number of elements that you're iterating over.

The solution may then depend on the type of the container. If it is a List, then you could use the indexed access

```<code>for (int i=0; i<list.size(); i++) {
    if (i%10==0) System.out.println("Step "+i+" of "+list.size());

    T t = list.get(i);
    doSomethingWith(t);
}
</code>```

Otherwise, you'll probably have to introduce a counter variable:

```<code>int step = 0;
for (T t : set) {
    if (step%10==0) System.out.println("Step "+step+" of "+set.size());

    doSomethingWith(t);
}
</code>```

From a more high-level point of view: I'd strongly recommend to think about whether you don't need to generalize this kind of progress information. If this is not only intended for debugging, then you should/could at least extract it into a function:

```<code>int step = 0;
for (T t : set) {
    reportProgress(step, set.size());

    doSomethingWith(t);
}

private static void reportProgress(int step, int total) {
    if (step%10==0) System.out.println("Step "+step+" of "+total);
}
</code>```

Even more generic could be to use a (functional) interface, like

```<code>interface ProgressReporter {
    void reportProgress(String message, int step, int total);
}

// Using it:
int step = 0;
for (T t : set) {
    progressReporter.reportProgress("My loop", step, set.size());

    doSomethingWith(t);
}
</code>```

This allows you, for example, to show the progress in a ProgressBar in the future, redirecting the progress to a Logger, or changing the report interval (e.g. from step%10 to step%100 or step%(total/10+1) generically.

Body:
I have a very long running for loop and I would like to print out some progress information.

With a normal for loop this is easy, since you can divide the loop-variable by the maximum to get a progress indicator, i.e. do something like this:

for(int i = 0; i<container.size(); i++) {
  if(i%10==0) System.out.println("Progress " +  Double.toString(i/container.size()*100.0) + "%.")
}

Is there a way to do something like this without adding a counter variable (which somehow defeats the purpose of the range based for loop)?

//... Foreach loop over all elements in arr.
for (type var : arr) {
    body-of-loop
    // print progress info here?
}

Body:
Regarding the core of the question: You cannot derive any progress information from a range-based for-loop. Mainly because there may not be any. You could easily create an Iterable for which

for (T t : iterable) {
    ...
}

is an infinite loop. You have to know the number of elements that you're iterating over.

The solution may then depend on the type of the container. If it is a List, then you could use the indexed access

for (int i=0; i<list.size(); i++) {
    if (i%10==0) System.out.println("Step "+i+" of "+list.size());

    T t = list.get(i);
    doSomethingWith(t);
}

Otherwise, you'll probably have to introduce a counter variable:

int step = 0;
for (T t : set) {
    if (step%10==0) System.out.println("Step "+step+" of "+set.size());

    doSomethingWith(t);
}

From a more high-level point of view: I'd strongly recommend to think about whether you don't need to generalize this kind of progress information. If this is not only intended for debugging, then you should/could at least extract it into a function:

int step = 0;
for (T t : set) {
    reportProgress(step, set.size());

    doSomethingWith(t);
}

private static void reportProgress(int step, int total) {
    if (step%10==0) System.out.println("Step "+step+" of "+total);
}

Even more generic could be to use a (functional) interface, like

interface ProgressReporter {
    void reportProgress(String message, int step, int total);
}

// Using it:
int step = 0;
for (T t : set) {
    progressReporter.reportProgress("My loop", step, set.size());

    doSomethingWith(t);
}

This allows you, for example, to show the progress in a ProgressBar in the future, redirecting the progress to a Logger, or changing the report interval (e.g. from step%10 to step%100 or step%(total/10+1) generically.


问:
Breaking bash script execution if passed file is of wrong extension
I have a small bash file that I used to compress PDFs and undertake some other file manipulations. I would like to break execution of this bash script if the passed file name does not have .pdf or .PDF extension.

Current approach:

```<code># Take file name
fle_nme=$1

# Check if passed PDF file
# -ne - not equal
if ["${fle_nme: -4}" -ne ".pdf"] ||  ["${fle_nme: -4}" -ne ".PDF"]; then
        echo "Incorrect file."
        exit
fi
</code>```

Current output

The script fails but without the desired message:

```<code>[me@onthebox bashStuff ERR]$ compressPDF ~/bashFun/failWithThisExtension.bad
compressPDF.sh: line 16: [.bad: command not found
compressPDF.sh: line 16: [.bad: command not found
</code>```

Desired results

Execution of the script should finish

Message Incorrect file should be printed to console

答:
That is not the correct syntax.  It should be:

```<code>if [ "${fle_nme: -4}" != ".pdf" -a "${fle_nme: -4}" != ".PDF" ]; then
</code>```

As Inian said, you need spaces.  Also, -ne is for numeric comparisons.  Finally, use -a for the and inside the brackets.

Inian's second option is best, if you also want to allow .Pdf and .pDf and all other such capitalation.

Body:
I have a small bash file that I used to compress PDFs and undertake some other file manipulations. I would like to break execution of this bash script if the passed file name does not have .pdf or .PDF extension.

Current approach:

# Take file name
fle_nme=$1

# Check if passed PDF file
# -ne - not equal
if ["${fle_nme: -4}" -ne ".pdf"] ||  ["${fle_nme: -4}" -ne ".PDF"]; then
        echo "Incorrect file."
        exit
fi

Current output

The script fails but without the desired message:

[me@onthebox bashStuff ERR]$ compressPDF ~/bashFun/failWithThisExtension.bad
compressPDF.sh: line 16: [.bad: command not found
compressPDF.sh: line 16: [.bad: command not found

Desired results

Execution of the script should finish

Message Incorrect file should be printed to console

Body:
That is not the correct syntax.  It should be:

if [ "${fle_nme: -4}" != ".pdf" -a "${fle_nme: -4}" != ".PDF" ]; then

As Inian said, you need spaces.  Also, -ne is for numeric comparisons.  Finally, use -a for the and inside the brackets.

Inian's second option is best, if you also want to allow .Pdf and .pDf and all other such capitalation.


问:
64 bits apps supporting 32 bits and new appstore
So ios 11 will break support for 32 apps, thus the older iphones will not be able to upgrade to it.

But what about apps that run in both 64 and 32bits, will they be able to download the app updates or will they be stuck with the last release available at the time of ios 11 release?

I want to know if for a build there is two versions of the app or one version supporting both 32bits and 64bits.
Basically will people with an iphone inferior to 5s be completly cut out of the appstore at this year fall or not.

答:
To recap, No older 32 bit devices will not be locked out of the AppStore.

Since iOS 11 will drop support for 32bit, Xcode 9 with the iOS 11 SDK will not. Just don't use any new methods or classes that only exist on iOS 11 if you are also targeting iOS <= 10.


问:
How to read the json string through C# code in runtime?
```<code>{
    "StudentInformation": {
        "rollNumber": null,
        "isClassLeader": false,
        "result": "Pass"

    },

    "CollegeInformation": {
        "allClass": ["A", "B"],
        "currencyAccepted": "INR",
        "calendarDates": [],
        "currencyCode": "INR",
        "collegeCode": null,
        "hasBulidingFundPrices": false,
        "hasHostel": false,
        "hasSecurityFares": false

    },

    "Collegetrips": [{
        "tripsdate": [{
                "departureTripDate": "2017-08-15 00:00:00",
                    "Places": [{
                            "destination": "Bombay",
                            "price": [{
                                "priceAmount": 1726
                                    }]
                                }]
                        }]
             }]
}
</code>```

In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?

答:
I use:
http://json2csharp.com/
to get a class representing the Json Object.

```<code>public class StudentInformation
{
    public object rollNumber { get; set; }
    public bool isClassLeader { get; set; }
    public string result { get; set; }
}

public class CollegeInformation
{
    public List<string> allClass { get; set; }
    public string currencyAccepted { get; set; }
    public List<object> calendarDates { get; set; }
    public string currencyCode { get; set; }
    public object collegeCode { get; set; }
    public bool hasBulidingFundPrices { get; set; }
    public bool hasHostel { get; set; }
    public bool hasSecurityFares { get; set; }
}

public class Price
{
    public int priceAmount { get; set; }
}

public class Place
{
    public string destination { get; set; }
    public List<Price> price { get; set; }
}

public class Tripsdate
{
    public string departureTripDate { get; set; }
    public List<Place> Places { get; set; }
}

public class Collegetrip
{
    public List<Tripsdate> tripsdate { get; set; }
}

public class JsonResponse
{
    public StudentInformation StudentInformation { get; set; }
    public CollegeInformation CollegeInformation { get; set; }
    public List<Collegetrip> Collegetrips { get; set; }
}
</code>```

After that I use Newtonsoft.Json to fill the Class:

```<code>using Newtonsoft.Json;

namespace GitRepositoryCreator.Common
{
    class JObjects
    {
        public static string Get(object p_object)
        {
            return JsonConvert.SerializeObject(p_object);
        }
        internal static T Get<T>(string p_object)
        {
            return JsonConvert.DeserializeObject<T>(p_object);
        }
    }
}
</code>```

You can call it like that:

```<code>JsonResponse jsonClass = JObjects.Get<JsonResponse>(stringJson);

string stringJson = JObjects.Get(jsonClass);
</code>```

PS:
If your json variable name is no valid C# name you can fix that like this:

```<code>public class Exception
{
   [JsonProperty(PropertyName = "$id")]
   public string id { get; set; }
   public object innerException { get; set; }
   public string message { get; set; }
   public string typeName { get; set; }
   public string typeKey { get; set; }
   public int errorCode { get; set; }
   public int eventId { get; set; }
}
</code>```

Body:
{
    "StudentInformation": {
        "rollNumber": null,
        "isClassLeader": false,
        "result": "Pass"

    },

    "CollegeInformation": {
        "allClass": ["A", "B"],
        "currencyAccepted": "INR",
        "calendarDates": [],
        "currencyCode": "INR",
        "collegeCode": null,
        "hasBulidingFundPrices": false,
        "hasHostel": false,
        "hasSecurityFares": false

    },

    "Collegetrips": [{
        "tripsdate": [{
                "departureTripDate": "2017-08-15 00:00:00",
                    "Places": [{
                            "destination": "Bombay",
                            "price": [{
                                "priceAmount": 1726
                                    }]
                                }]
                        }]
             }]
}

In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?

Body:
I use:
http://json2csharp.com/
to get a class representing the Json Object.

public class StudentInformation
{
    public object rollNumber { get; set; }
    public bool isClassLeader { get; set; }
    public string result { get; set; }
}

public class CollegeInformation
{
    public List<string> allClass { get; set; }
    public string currencyAccepted { get; set; }
    public List<object> calendarDates { get; set; }
    public string currencyCode { get; set; }
    public object collegeCode { get; set; }
    public bool hasBulidingFundPrices { get; set; }
    public bool hasHostel { get; set; }
    public bool hasSecurityFares { get; set; }
}

public class Price
{
    public int priceAmount { get; set; }
}

public class Place
{
    public string destination { get; set; }
    public List<Price> price { get; set; }
}

public class Tripsdate
{
    public string departureTripDate { get; set; }
    public List<Place> Places { get; set; }
}

public class Collegetrip
{
    public List<Tripsdate> tripsdate { get; set; }
}

public class JsonResponse
{
    public StudentInformation StudentInformation { get; set; }
    public CollegeInformation CollegeInformation { get; set; }
    public List<Collegetrip> Collegetrips { get; set; }
}

After that I use Newtonsoft.Json to fill the Class:

using Newtonsoft.Json;

namespace GitRepositoryCreator.Common
{
    class JObjects
    {
        public static string Get(object p_object)
        {
            return JsonConvert.SerializeObject(p_object);
        }
        internal static T Get<T>(string p_object)
        {
            return JsonConvert.DeserializeObject<T>(p_object);
        }
    }
}

You can call it like that:

JsonResponse jsonClass = JObjects.Get<JsonResponse>(stringJson);

string stringJson = JObjects.Get(jsonClass);

PS:
If your json variable name is no valid C# name you can fix that like this:

public class Exception
{
   [JsonProperty(PropertyName = "$id")]
   public string id { get; set; }
   public object innerException { get; set; }
   public string message { get; set; }
   public string typeName { get; set; }
   public string typeKey { get; set; }
   public int errorCode { get; set; }
   public int eventId { get; set; }
}


问:
Using StatusStrip in C#
Consider System.Windows.Forms.StatusStrip. I have added a StatusStrip to my Windows Forms application, but I am having a few problems.

I would like to have a label anchored at the left and a progressbar anchored on the right in the StatusStrip, but I can't find a way to set these properties.

I then thought that I may need to create two StatusStrips and anchor them on either side of the bottom of the form... That didn't pan out; besides that, it just doesn't feel right.

答:
What you have to do is set the alignment property of your progressbar to right.  Then set the LayoutStyle of the StatusStrip to HorizontalStackWithOverflow.</p>

```<code>    private void InitializeComponent()
    {
        this.statusStrip1 = new System.Windows.Forms.StatusStrip();
        this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
        this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
        this.statusStrip1.SuspendLayout();
        this.SuspendLayout();
        //
        // statusStrip1
        //
        this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
    this.toolStripStatusLabel1,
    this.toolStripProgressBar1});
        this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
        this.statusStrip1.Location = new System.Drawing.Point(0, 250);
        this.statusStrip1.Name = "statusStrip1";
        this.statusStrip1.Size = new System.Drawing.Size(467, 22);
        this.statusStrip1.TabIndex = 0;
        this.statusStrip1.Text = "statusStrip1";
        //
        // toolStripStatusLabel1
        //
        this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
        this.toolStripStatusLabel1.Size = new System.Drawing.Size(117, 17);
        this.toolStripStatusLabel1.Text = "toolStripStatusLabel1";
        //
        // toolStripProgressBar1
        //
        this.toolStripProgressBar1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
        this.toolStripProgressBar1.Name = "toolStripProgressBar1";
        this.toolStripProgressBar1.Size = new System.Drawing.Size(100, 16);

    }

    private System.Windows.Forms.StatusStrip statusStrip1;
    private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
    private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1;
</code>```

OwnerDisplayName: Brad

Title: Using StatusStrip in C#

Body:
What you have to do is set the alignment property of your progressbar to right.  Then set the LayoutStyle of the StatusStrip to HorizontalStackWithOverflow.

    private void InitializeComponent()
    {
        this.statusStrip1 = new System.Windows.Forms.StatusStrip();
        this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
        this.toolStripProgressBar1 = new System.Windows.Forms.ToolStripProgressBar();
        this.statusStrip1.SuspendLayout();
        this.SuspendLayout();
        //
        // statusStrip1
        //
        this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
    this.toolStripStatusLabel1,
    this.toolStripProgressBar1});
        this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
        this.statusStrip1.Location = new System.Drawing.Point(0, 250);
        this.statusStrip1.Name = "statusStrip1";
        this.statusStrip1.Size = new System.Drawing.Size(467, 22);
        this.statusStrip1.TabIndex = 0;
        this.statusStrip1.Text = "statusStrip1";
        //
        // toolStripStatusLabel1
        //
        this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
        this.toolStripStatusLabel1.Size = new System.Drawing.Size(117, 17);
        this.toolStripStatusLabel1.Text = "toolStripStatusLabel1";
        //
        // toolStripProgressBar1
        //
        this.toolStripProgressBar1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
        this.toolStripProgressBar1.Name = "toolStripProgressBar1";
        this.toolStripProgressBar1.Size = new System.Drawing.Size(100, 16);

    }

    private System.Windows.Forms.StatusStrip statusStrip1;
    private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
    private System.Windows.Forms.ToolStripProgressBar toolStripProgressBar1;

OwnerDisplayName: Steven Behnke

ContentLicense: CC BY-SA 2.5


问:
jquery each div add remove class infinity
want to create infinity loop that adds class to each div with some timeout

for know have like this:

$(document).ready(function() {
  $('.small-bordered-box').each(function(i) {
    var $t = $(this);
    setTimeout(function() {
      $t.addClass('active');
    }, 2000 * i);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}</code>```

  test1

  test2

  test3

```

want to keep effect like this, just that it would go infiny time..
that users would always sees this effect no matter what or where they are on the page..

答:
Change your CSS into:</p>

```<code>.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both infinite;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}
</code>```

Body:
want to create infinity loop that adds class to each div with some timeout

for know have like this:

$(document).ready(function() {
  $('.small-bordered-box').each(function(i) {
    var $t = $(this);
    setTimeout(function() {
      $t.addClass('active');
    }, 2000 * i);
  });
});

.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

  test1

  test2

  test3

want to keep effect like this, just that it would go infiny time..
that users would always sees this effect no matter what or where they are on the page..

Body:
Change your CSS into:

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both infinite;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}


问:
TextView autoSizeTextType is not detecting in xml
I'm looking for changing the TextView Sizes automatically. And I found the solution as well. Here is the official Doc for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file.

Here is the my xml code and gradle code snippets

myactivity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

<include layout="@layout/toolbar" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:autoSizeTextType="uniform"/>

</LinearLayout>
</code>```

Gradle snippet

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:support-v4:25.2.0'//Added support library
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    testCompile 'junit:junit:4.12'
}
</code>```

答: This API is available only from API level 26. </p>

Body:
I'm looking for changing the TextView Sizes automatically. And I found the solution as well. Here is the official Doc for Auto sizing textviews. But Still I'm not able to resolve it. When i paste autoSizeTextType its showing error in xml file.

Here is the my xml code and gradle code snippets

myactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

<include layout="@layout/toolbar" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:autoSizeTextType="uniform"/>

</LinearLayout>

Gradle snippet

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:support-v4:25.2.0'//Added support library
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    testCompile 'junit:junit:4.12'
}


问:
THREE.Color: Unknown color #002dff (warning/error)
I need to update the color after receiving the value from dat.GUI .
But, this

```<code>var colored = new THREE.Color(value.replace("#","0x"));
</code>```

is throwing this warning "THREE.Color: Unknown color 0x002dff" and the 'colored' isn't updating.

value = #002dff (at that time, it keeps on changing, user input)

Edit: I know I can use this as "THREE.Color( #002dff )", but the color is changing at run time according to the user input from controls I've created using dat.GUI, so I won't be knowing the actual value that can be added to the code.

PS: It was replace() which was causing the problem. It's solved.

答: try this ((new THREE.color("#FF00FF")),.if you want to choose a favortie color for your program .check this link out http://www.rapidtables.com/web/color/RGB_Color.htm  ,are got to the photoshop and their you can select the color and it shows the color code .</p>

Body:
I need to update the color after receiving the value from dat.GUI .
But, this

var colored = new THREE.Color(value.replace("#","0x"));

is throwing this warning "THREE.Color: Unknown color 0x002dff" and the 'colored' isn't updating.

value = #002dff (at that time, it keeps on changing, user input)

Edit: I know I can use this as "THREE.Color( #002dff )", but the color is changing at run time according to the user input from controls I've created using dat.GUI, so I won't be knowing the actual value that can be added to the code.

PS: It was replace() which was causing the problem. It's solved.


问:
Laravel 5.4: Redirect::to not working
I want to redirect the user to another page if a certain condition is not true.

This is my first/index view:

```<code>    <html lang="en">
      <head>
      </head>

      <body>

        <?php
        if(5>4) {
        return Redirect::to('controllername@methodname')->with('status','Condition not true!');
        } else {
        ?>
    <p>It is Working</p>

<?php } ?>

    </body>
    </html>
</code>```

If I change the condition to (5<4) then it works fine. but if the condition is true, it shows me a blank page. I want to write the condition in the view not in the controller and route. Please Help

答: You shouldn't redirect in the template. It must be in the Controller. </p>

Title: Laravel 5.4: Redirect::to not working

Body:
I want to redirect the user to another page if a certain condition is not true.

This is my first/index view:

        <?php
        if(5>4) {
        return Redirect::to('controllername@methodname')->with('status','Condition not true!');
        } else {
        ?>

It is Working

<?php } ?>

If I change the condition to (5<4) then it works fine. but if the condition is true, it shows me a blank page. I want to write the condition in the view not in the controller and route. Please Help


问:
Vue Props not working for child component
I have root element that has logged in user data and on user profile component I am passing logged in user data as props.

But when I try to call User object properties in child component it throws error as undefined. I don't see any value in child component.

app.js

```<code>Vue.component("usersmanagment", require("./components/usersmanagment"));

const app = new Vue({
    el: "#app",
    components: {
        'v-select': vSelect
    },
    data() {
        return {
            AuthorizedUser: {
                Email : "",
                FirstName : "",
                LastName : "",
                CreatedUtcDateTime : "",
                IsActive : ""
            }
        };
    },
    mounted() {
        let vm = this;
        vm.getAuthorisedUserProfile();
    },
    methods: {
        getAuthorisedUserProfile() {
            let vm = this;
            // just return auth user data
    }

});
</code>```

Than on child component I am passing props

```<code>module.exports = {
    props : ["AuthorizedUser"],

};
</code>```

and in my view file I am Asp.Net MVC

```<code><usersmanagment inline-template>
        <input type="text" class="form-control" v-model="AuthorizedUser.FirstName">
</usersmanagment>
</code>```

I can see in vue chrome dev tools that Authorized user get updated but its value don't get updated on child component.

答:
This is what solved my problem. I have to bind props with child template.</p>

```<code><profile inline-template v-bind:authorized-user="authorizedUser">
        <div>

            <input type="text" v-model="authorizedUser.FirstName" class="form-control">
        </div>

    </profile>
</code>```

Body:
I have root element that has logged in user data and on user profile component I am passing logged in user data as props.

But when I try to call User object properties in child component it throws error as undefined. I don't see any value in child component.

app.js

Vue.component("usersmanagment", require("./components/usersmanagment"));

const app = new Vue({
    el: "#app",
    components: {
        'v-select': vSelect
    },
    data() {
        return {
            AuthorizedUser: {
                Email : "",
                FirstName : "",
                LastName : "",
                CreatedUtcDateTime : "",
                IsActive : ""
            }
        };
    },
    mounted() {
        let vm = this;
        vm.getAuthorisedUserProfile();
    },
    methods: {
        getAuthorisedUserProfile() {
            let vm = this;
            // just return auth user data
    }

});

Than on child component I am passing props

module.exports = {
    props : ["AuthorizedUser"],

};

and in my view file I am Asp.Net MVC

<usersmanagment inline-template>
        <input type="text" class="form-control" v-model="AuthorizedUser.FirstName">
</usersmanagment>

I can see in vue chrome dev tools that Authorized user get updated but its value don't get updated on child component.

Body:
This is what solved my problem. I have to bind props with child template.

<profile inline-template v-bind:authorized-user="authorizedUser">
        <div>

            <input type="text" v-model="authorizedUser.FirstName" class="form-control">
        </div>

    </profile>


答:
use   $t.toggleClass('active'); keep this inside setInterval()

$(document).ready(function() {
  $('.small-bordered-box').each(function(i) {
    var $t = $(this);
    setInterval(function() {
      $t.toggleClass('active');
    }, 2000 );
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;

}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}</code>```

  test1

  test2

  test3

```

Title: jquery each div add remove class infinity

Body:
use   $t.toggleClass('active'); keep this inside setInterval()

$(document).ready(function() {
  $('.small-bordered-box').each(function(i) {
    var $t = $(this);
    setInterval(function() {
      $t.toggleClass('active');
    }, 2000 );
  });
});

.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;

}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small-bordered-box ">
  <a href="#">test1</a>
</div>
<div class="small-bordered-box ">
  <a href="#">test2</a>
</div>
<div class="small-bordered-box ">
  <a href="#">test3</a>
</div>


问:
Unable to convert connection to SSL when sending e-mail jhipster
I want to send e-mail notification after registration, I do all things according to the jhipster documentation about configuring e-mail:

```<code>mail:
    host: smtp.gmail.com
    port: 587
    username: *******@gmail.com
    password: *****
    protocol: smtp
    tls: true
    properties.mail.smtp:
        auth: true
        starttls.enable: true
        ssl.trust: smtp.gmail.com
</code>```

According to another issue on stackoverflow I allow google account to connect with less secure apps, but still, I got exception about:

```<code>org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Unable to convert connection to SSL (javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed
: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target). Failed messages: javax.mail.MessagingException: Unable to convert connection to SSL (javax.net.ssl.SSLHandshakeException: sun.security.validator
.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target)
</code>```

What should I do to solve this issue?

Thank you in advance.

答: Perhaps you are sending the email from a server without SSL certificate?</p>

Body:
I want to send e-mail notification after registration, I do all things according to the jhipster documentation about configuring e-mail:

mail:
    host: smtp.gmail.com
    port: 587
    username: *******@gmail.com
    password: *****
    protocol: smtp
    tls: true
    properties.mail.smtp:
        auth: true
        starttls.enable: true
        ssl.trust: smtp.gmail.com

According to another issue on stackoverflow I allow google account to connect with less secure apps, but still, I got exception about:

org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Unable to convert connection to SSL (javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed
: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target). Failed messages: javax.mail.MessagingException: Unable to convert connection to SSL (javax.net.ssl.SSLHandshakeException: sun.security.validator
.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target)

What should I do to solve this issue?

Thank you in advance.


问:
How to split the string before the 3rd occurrence of a "/" in Java
I have:

```<code>/xxx/yyy/aaa/bbb/abc.xml (or)
/xxx/yyy/aaa/abc.xml (or)
/xxx/yyy/aaa/bbb/ccc/abc.xml
</code>```

But I need only:

```<code>/xxx/yyyy
</code>```

How do I implement this in Java?
Thanks in advance.

答:
You can use String.split("/") for splitting and concat first 2 elements:

```<code>for(String string: input){
  String[] splitedStrings = string.split("/");
  StringBuilder result = new StringBuilder("/");
  for(int i = 1; i < 3 && i < splitedStrings.length; i++){
    result.append(splitedStrings[i]).append("/");
  }
  System.out.println("Result: " + result.toString());
}
</code>```

https://pastebin.com/kpg5VtMk

Body:
I have:

/xxx/yyy/aaa/bbb/abc.xml (or)
/xxx/yyy/aaa/abc.xml (or)
/xxx/yyy/aaa/bbb/ccc/abc.xml

But I need only:

/xxx/yyyy

How do I implement this in Java?
Thanks in advance.

Body:
You can use String.split("/") for splitting and concat first 2 elements:

for(String string: input){
  String[] splitedStrings = string.split("/");
  StringBuilder result = new StringBuilder("/");
  for(int i = 1; i < 3 && i < splitedStrings.length; i++){
    result.append(splitedStrings[i]).append("/");
  }
  System.out.println("Result: " + result.toString());
}

https://pastebin.com/kpg5VtMk


问:
How to include a method in a string.format syntax inside a console.writeline in C#?
I have a method that displays something like:

```<code>public void display(){

Console.Writeline("Message");
}
</code>```

And I should include it in the console.writeline that use string.format (the one inside <<>> is just how should it look:

```<code>int CodeName = 52;
Console.WriteLine("Mutant Name: {0} ------ Message: {1}", CodeName, <<dispplay()>>);
</code>```

答:
Try calling the display method by making it return a value.

Like this:

```<code>public string display()
{
    return "Message";
}

int CodeName = 52;

Console.WriteLine(string.Format("Mutant Name: {0} ------ Message: {1}", CodeName, display()));
</code>```

Body:
I have a method that displays something like:

public void display(){

Console.Writeline("Message");
}

And I should include it in the console.writeline that use string.format (the one inside <<>> is just how should it look:

int CodeName = 52;
Console.WriteLine("Mutant Name: {0} ------ Message: {1}", CodeName, <<dispplay()>>);

Body:
Try calling the display method by making it return a value.

Like this:

public string display()
{
    return "Message";
}

int CodeName = 52;

Console.WriteLine(string.Format("Mutant Name: {0} ------ Message: {1}", CodeName, display()));


问:
Better Way to use Laravel old and Vue.js
Im working using vue.js 2.0 and Laravel 5.4 I would like to know if exits a better way to send data Controllers -> views  without lost the value, overwrite by the v-model

Because after charge vue.js this take the value in data that is define in this way

```<code>data: {
    ciudad:'',
}
</code>```

If I try to do something like that

```<code> <input  class="form-control"  id="ciudad" name="ciudad" type="text"  v-model="documento.ciudad"  value="{{ $documento->ciudad }}" >
</code>```

I lost the value sending by the controller

答:
Vue really expects you to init data from the view model which then updates the view, however, you want to use data in the view to update the underlying model data.

I think the easiest approach to this is to write a directive that inits the value from the HTML, so you don't need to directly access the DOM:

```<code>Vue.directive('init', {
  bind: function(el, binding, vnode) {
    vnode.context[binding.arg] = binding.value;
  }
});
</code>```

It's a little abstract so it's worth looking at Directive Hook Arguments section of the docs.

This can then be used like:

```<code><input v-model="ciudad" v-init:ciudad="'{{ old('ciudad') }}'">
</code>```

Here's the JSFiddle: https://jsfiddle.net/v5djagta/

Body:
Im working using vue.js 2.0 and Laravel 5.4 I would like to know if exits a better way to send data Controllers -> views  without lost the value, overwrite by the v-model

Because after charge vue.js this take the value in data that is define in this way

data: {
    ciudad:'',
}

If I try to do something like that

 <input  class="form-control"  id="ciudad" name="ciudad" type="text"  v-model="documento.ciudad"  value="{{ $documento->ciudad }}" >

I lost the value sending by the controller

Body:
Vue really expects you to init data from the view model which then updates the view, however, you want to use data in the view to update the underlying model data.

I think the easiest approach to this is to write a directive that inits the value from the HTML, so you don't need to directly access the DOM:

Vue.directive('init', {
  bind: function(el, binding, vnode) {
    vnode.context[binding.arg] = binding.value;
  }
});

It's a little abstract so it's worth looking at Directive Hook Arguments section of the docs.

This can then be used like:

<input v-model="ciudad" v-init:ciudad="'{{ old('ciudad') }}'">

Here's the JSFiddle: https://jsfiddle.net/v5djagta/

ContentLicense: CC BY-SA 4.0


问:
Object id after update command mongoskin
While inserting in mongodb by mongoskin i could get object id by following. Which is working absoultely well

```<code>     db.collection('test').insert({
     version: nc.version,
     }, function (err, result) {
 // This would give me objectID of nre
    console.log('creating new version ', result.ops[0]._id);
         }
   })
</code>```

While update with {upsert:true} in collection i couldn't find anything

```<code>           db.collection('test').update({labId: lab_id},{$set:
            {
            version: nc.version,
        }},{upsert:true}, function (error, result) {

             if (error){
                 // If there is error then
                 console.log("Error occured while adding in system");
             }
            console.log('Result is  ', result);
         })
</code>```

Result what is print is like this one. So i would like to know where i could find my objectid (i.e. _id which we get after object is added in mongodb)

```<code> Result is  {
  result: { n: 1, nModified: 0, upserted: [ [Object] ], ok: 1 },
  connection:
   Connection {
     domain: null,
     _events:
      { error: [Object],
        close: [Object],
        timeout: [Object],
        parseError: [Object] },
     _eventsCount: 4,
     _maxListeners: undefined,
     options:
      { host: 'localhost',
        port: 27017,
        size: 5,
        connectionTimeout: 30000,
        socketTimeout: 30000,
        keepAlive: true,
        keepAliveInitialDelay: 0,
        noDelay: true,
        ssl: false,
        checkServerIdentity: true,
        ca: null,
        cert: null,
        key: null,
        passPhrase: null,
        rejectUnauthorized: false,
        promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false,
        reconnect: true,
        reconnectInterval: 1000,
        reconnectTries: 30,
        domainsEnabled: false,
        disconnectHandler: [Object],
        cursorFactory: [Object],
        emitError: true,
        socketOptions: {},
        clientInfo: [Object],
        readPreference: [Object],
        native_parser: true,
        promiseLibrary: [Function: Promise],
        bson: BSON {} },
     id: 0,
     logger: Logger { className: 'Connection' },
     bson: BSON {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 30000,
     socketTimeout: 30000,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions:
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     flushing: false,
     queue: [],
     connection:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 2134,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        _idleTimeout: 30000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 3254,
        read: [Function],
        _consuming: true },
     writeStream: null,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c',
     workItems: [ [Object] ],
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null },
  message:
   Response {
     parsed: true,
     index: 126,
     raw: <Buffer 7e 00 00 00 c0 90 00 00 03 00 00 00 01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 5a 00 00 00 10 6e 00 01 00 00 00 10 6e 4d ... >,
     data: <Buffer 7e 00 00 00 c0 90 00 00 03 00 00 00 01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 5a 00 00 00 10 6e 00 01 00 00 00 10 6e 4d ... >,
     bson: BSON {},
     opts:
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     length: 126,
     requestId: 37056,
     responseTo: 3,
     responseFlags: 8,
     cursorId: Long { _bsontype: 'Long', low_: 0, high_: 0 },
     startingFrom: 0,
     numberReturned: 1,
     documents: [ [Object] ],
     cursorNotFound: false,
     queryFailure: false,
     shardConfigStale: false,
     awaitCapable: true,
     promoteLongs: true,
     promoteValues: true,
     promoteBuffers: false,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c' } }
</code>```

答:
collection.update() will only report the number of documents that were affected to its own callback.

To retrieve the documents while modifying, you can use collection.findOneAndUpdate() or collection.findAndModify()

collection.findOneAndUpdate:

```<code>db.collection.findOneAndUpdate(
   <filter>,
   <update>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     upsert: <boolean>,
     returnNewDocument: <boolean>
   }
)
</code>```

Refrence : findOneAndUpdate

With your Problem :

```<code>       db.test.findOneAndUpdate(
           {labId: lab_id},
           {$set:{version:nc.version},
           {
             upsert: true,
             returnNewDocument: true // use this key if wanted modified document
           },
           function (error, result) {

             if (error){
                 // If there is error then
                 console.log("Error occured while adding in system");
             }
            console.log('Result is  ', result);
         })
        )
</code>```

collection.findOneAndModify:

```<code>db.collection.findAndModify({
    query: <document>,
    sort: <document>,
    remove: <boolean>,
    update: <document>,
    new: <boolean>,
    fields: <document>,
    upsert: <boolean>,
    bypassDocumentValidation: <boolean>,
    writeConcern: <document>,
    collation: <document>
});
</code>```

Reference : findOneAndModify:

Note : Use findOneAndUpdate and findOneAndModify only if u want to update a single document because multi true is not available in them .

Body:
While inserting in mongodb by mongoskin i could get object id by following. Which is working absoultely well

     db.collection('test').insert({
     version: nc.version,
     }, function (err, result) {
 // This would give me objectID of nre
    console.log('creating new version ', result.ops[0]._id);
         }
   })

While update with {upsert:true} in collection i couldn't find anything

           db.collection('test').update({labId: lab_id},{$set:
            {
            version: nc.version,
        }},{upsert:true}, function (error, result) {

             if (error){
                 // If there is error then
                 console.log("Error occured while adding in system");
             }
            console.log('Result is  ', result);
         })

Result what is print is like this one. So i would like to know where i could find my objectid (i.e. _id which we get after object is added in mongodb)

 Result is  {
  result: { n: 1, nModified: 0, upserted: [ [Object] ], ok: 1 },
  connection:
   Connection {
     domain: null,
     _events:
      { error: [Object],
        close: [Object],
        timeout: [Object],
        parseError: [Object] },
     _eventsCount: 4,
     _maxListeners: undefined,
     options:
      { host: 'localhost',
        port: 27017,
        size: 5,
        connectionTimeout: 30000,
        socketTimeout: 30000,
        keepAlive: true,
        keepAliveInitialDelay: 0,
        noDelay: true,
        ssl: false,
        checkServerIdentity: true,
        ca: null,
        cert: null,
        key: null,
        passPhrase: null,
        rejectUnauthorized: false,
        promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false,
        reconnect: true,
        reconnectInterval: 1000,
        reconnectTries: 30,
        domainsEnabled: false,
        disconnectHandler: [Object],
        cursorFactory: [Object],
        emitError: true,
        socketOptions: {},
        clientInfo: [Object],
        readPreference: [Object],
        native_parser: true,
        promiseLibrary: [Function: Promise],
        bson: BSON {} },
     id: 0,
     logger: Logger { className: 'Connection' },
     bson: BSON {},
     tag: undefined,
     messageHandler: [Function],
     maxBsonMessageSize: 67108864,
     port: 27017,
     host: 'localhost',
     keepAlive: true,
     keepAliveInitialDelay: 0,
     noDelay: true,
     connectionTimeout: 30000,
     socketTimeout: 30000,
     destroyed: false,
     domainSocket: false,
     singleBufferSerializtion: true,
     serializationFunction: 'toBinUnified',
     ca: null,
     cert: null,
     key: null,
     passphrase: null,
     ssl: false,
     rejectUnauthorized: false,
     checkServerIdentity: true,
     responseOptions:
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     flushing: false,
     queue: [],
     connection:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'localhost',
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 8,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 2134,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        _idleTimeout: 30000,
        _idleNext: [Object],
        _idlePrev: [Object],
        _idleStart: 3254,
        read: [Function],
        _consuming: true },
     writeStream: null,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c',
     workItems: [ [Object] ],
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null },
  message:
   Response {
     parsed: true,
     index: 126,
     raw: <Buffer 7e 00 00 00 c0 90 00 00 03 00 00 00 01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 5a 00 00 00 10 6e 00 01 00 00 00 10 6e 4d ... >,
     data: <Buffer 7e 00 00 00 c0 90 00 00 03 00 00 00 01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 5a 00 00 00 10 6e 00 01 00 00 00 10 6e 4d ... >,
     bson: BSON {},
     opts:
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     length: 126,
     requestId: 37056,
     responseTo: 3,
     responseFlags: 8,
     cursorId: Long { _bsontype: 'Long', low_: 0, high_: 0 },
     startingFrom: 0,
     numberReturned: 1,
     documents: [ [Object] ],
     cursorNotFound: false,
     queryFailure: false,
     shardConfigStale: false,
     awaitCapable: true,
     promoteLongs: true,
     promoteValues: true,
     promoteBuffers: false,
     hashedName: '29bafad3b32b11dc7ce934204952515ea5984b3c' } }

Body:
collection.update() will only report the number of documents that were affected to its own callback.

To retrieve the documents while modifying, you can use collection.findOneAndUpdate() or collection.findAndModify()

collection.findOneAndUpdate:

db.collection.findOneAndUpdate(
   <filter>,
   <update>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     upsert: <boolean>,
     returnNewDocument: <boolean>
   }
)

Refrence : findOneAndUpdate

With your Problem :

       db.test.findOneAndUpdate(
           {labId: lab_id},
           {$set:{version:nc.version},
           {
             upsert: true,
             returnNewDocument: true // use this key if wanted modified document
           },
           function (error, result) {

             if (error){
                 // If there is error then
                 console.log("Error occured while adding in system");
             }
            console.log('Result is  ', result);
         })
        )

collection.findOneAndModify:

db.collection.findAndModify({
    query: <document>,
    sort: <document>,
    remove: <boolean>,
    update: <document>,
    new: <boolean>,
    fields: <document>,
    upsert: <boolean>,
    bypassDocumentValidation: <boolean>,
    writeConcern: <document>,
    collation: <document>
});

Reference : findOneAndModify:

Note : Use findOneAndUpdate and findOneAndModify only if u want to update a single document because multi true is not available in them .


问:
How do I sort IList C # by date?
I have an IList:

```<code>IList[] info = new IList[2];
info[0] = Date;      //List<DateTime> item
info[1] = something; //List<double> item
</code>```

So, I want sort info by dates in info[0]. Like that:

```<code> Date.Sort((a, b) => a.CompareTo(b));
</code>```

But when i'm trying to do it:

```<code>IEnumerable[] sortedEnum = info.OrderBy(info[0].Sort((a, b) => a.CompareTo(b)));
</code>```

I get:

'System.Collections.IList' does not contain a definition for 'Sort' and no extension method 'Sort' accepting a first argument of type 'System.Collections.IList' could be found (are you missing a using directive or an assembly reference?).

Can someoene help me with this?

答:
I think this is an X/Y problem. You're trying to solve a complex "sort two lists congruent to each-other". And ... you can do that, but it is very hard. Array.Sort has a suitable method for sorting two arrays in connection, but: not lists. You could try and do that, but frankly I think you're solving the wrong problem. If each DateTime and double is logically connected, then rather than having two lists: have one list with a composite value. For example:

```<code>var list = new List<(DateTime when, double value)>();
list.Add((dateX, valueX)); // your values...
list.Add((dateY, valueY));
list.Add((dateZ, valueZ));

list.Sort((x,y) => x.when.compareTo(y.when));
</code>```

Here I'm using tuple-types, but the same thing can be done by declaring your own type to hold the composite values. You might also want to look into pre-sorted list container types, but that places more demands on the key value (uniquity, etc).

Title: How do I sort IList C # by date?

Body:
I have an IList:

IList[] info = new IList[2];
info[0] = Date;      //List<DateTime> item
info[1] = something; //List<double> item

So, I want sort info by dates in info[0]. Like that:

 Date.Sort((a, b) => a.CompareTo(b));

But when i'm trying to do it:

IEnumerable[] sortedEnum = info.OrderBy(info[0].Sort((a, b) => a.CompareTo(b)));

I get:

'System.Collections.IList' does not contain a definition for 'Sort' and no extension method 'Sort' accepting a first argument of type 'System.Collections.IList' could be found (are you missing a using directive or an assembly reference?).

Can someoene help me with this?

Body:
I think this is an X/Y problem. You're trying to solve a complex "sort two lists congruent to each-other". And ... you can do that, but it is very hard. Array.Sort has a suitable method for sorting two arrays in connection, but: not lists. You could try and do that, but frankly I think you're solving the wrong problem. If each DateTime and double is logically connected, then rather than having two lists: have one list with a composite value. For example:

var list = new List<(DateTime when, double value)>();
list.Add((dateX, valueX)); // your values...
list.Add((dateY, valueY));
list.Add((dateZ, valueZ));

list.Sort((x,y) => x.when.compareTo(y.when));

Here I'm using tuple-types, but the same thing can be done by declaring your own type to hold the composite values. You might also want to look into pre-sorted list container types, but that places more demands on the key value (uniquity, etc).


问:
MySql join multiple select subquery
-SOLUTION-

```<code>SELECT Table1.unvan, Table2.sayi FROM
(SELECT id , unvan FROM unvan WHERE id IN
(SELECT unvani FROM personel WHERE gorev_yeri IN
(SELECT id FROM gorev_yeri WHERE il_id="34") ) ) AS Table1
JOIN
( SELECT unvani as id , count(*) AS sayi FROM personel WHERE gorev_yeri IN (SELECT id FROM gorev_yeri WHERE il_id="34") GROUP BY unvani ) AS Table2
ON Table1.id = Table2.id
</code>```

-EDIT-

When I use join with as I get this error : #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS table1

I have 2 query and I want join them.

It is first.

```<code>SELECT id
     , unvan
  FROM unvan
 WHERE id IN (SELECT unvani
                FROM personel
               WHERE gorev_yeri IN (SELECT id
                                      FROM gorev_yeri
                                     WHERE il_id="34")
              )
</code>```

It is second one.

```<code>SELECT unvani as id
     , count(*) AS sayi
 FROM personel
WHERE gorev_yeri IN (SELECT id
                       FROM gorev_yeri
                        WHERE il_id="34") GROUP BY unvani
</code>```

I need this:

unvan|sayi

--------|----

答:
(SELECT id
     , unvan
  FROM unvan
 WHERE id IN (SELECT unvani
                FROM personel
               WHERE gorev_yeri IN (SELECT id
                                      FROM gorev_yeri
                                     WHERE il_id="34")
              )
)table1

join

(
SELECT unvani as id, count(*) AS sayi FROM personel WHERE gorev_yeri IN (SELECT id FROM gorev_yeri WHERE il_id="34") GROUP BY unvani
)table2

on table1.id=table2.id;

Title: MySql join multiple select subquery

Body:
-SOLUTION-

SELECT Table1.unvan, Table2.sayi FROM
(SELECT id , unvan FROM unvan WHERE id IN
(SELECT unvani FROM personel WHERE gorev_yeri IN
(SELECT id FROM gorev_yeri WHERE il_id="34") ) ) AS Table1
JOIN
( SELECT unvani as id , count(*) AS sayi FROM personel WHERE gorev_yeri IN (SELECT id FROM gorev_yeri WHERE il_id="34") GROUP BY unvani ) AS Table2
ON Table1.id = Table2.id

-EDIT-

When I use join with as I get this error : #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS table1

I have 2 query and I want join them.

It is first.

SELECT id
     , unvan
  FROM unvan
 WHERE id IN (SELECT unvani
                FROM personel
               WHERE gorev_yeri IN (SELECT id
                                      FROM gorev_yeri
                                     WHERE il_id="34")
              )

It is second one.

SELECT unvani as id
     , count(*) AS sayi
 FROM personel
WHERE gorev_yeri IN (SELECT id
                       FROM gorev_yeri
                        WHERE il_id="34") GROUP BY unvani

I need this:

unvan|sayi

--------|----


问:
How can I monkey patch a function or method in groovy?
I want to modify an existing method in some Groovy code (Jenkins Pipeline) in order to extend its behaviour without changing the code that is consuming it.

Example the "sh" function where I do want to do something like (pseudocode):

```<code>  old_sh = sh
  def sh (args) {
    print(1)
    old_sh(args)
    print(2)
  }
</code>```

答:
You can achieve this using metaClass like so (note that the decorator can be used to decorate any method or closure not just sh):

```<code>def sh(Map args) {
    println "sh: $args"
}

sh(a: 'A', b: 'B', c: 2)

def decorator = { c, Map args ->
    println 1
    c(args)
    println 2
}

def decoratedSH = decorator.curry(this.&sh)
this.metaClass.sh = decoratedSH

sh(a: 'A', b: 'B', c: 2)
</code>```

Body:
I want to modify an existing method in some Groovy code (Jenkins Pipeline) in order to extend its behaviour without changing the code that is consuming it.

Example the "sh" function where I do want to do something like (pseudocode):

  old_sh = sh
  def sh (args) {
    print(1)
    old_sh(args)
    print(2)
  }

Body:
You can achieve this using metaClass like so (note that the decorator can be used to decorate any method or closure not just sh):

def sh(Map args) {
    println "sh: $args"
}

sh(a: 'A', b: 'B', c: 2)

def decorator = { c, Map args ->
    println 1
    c(args)
    println 2
}

def decoratedSH = decorator.curry(this.&sh)
this.metaClass.sh = decoratedSH

sh(a: 'A', b: 'B', c: 2)


问:
How to read NVARCHAR2 Data from oracle with php
I have a project where I am using ORACLE Database and CakePHP framework. I have a column where the datatype is NVARCHAR2. If I try to read the data from the database I get "¿¿¿¿¿". The code I am using is

```<code>ociexecute($stid, OCI_DEFAULT);
$i = 0;
$result = array();
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
       foreach ($row as $key => $value) {
                $result[$i][$key] = $value;
            }
            $i++;
}
</code>```

Charset in my Database is -

NLS_LANGUAGE  AMERICAN NLS_TERRITORY  AMERICA
  NLS_CHARACTERSET  WE8MSWIN1252

答:
Ensure that oci_connect is requesting data in UTF-8 like so:

```<code>$conn = oci_connect($username, $password, $conn_string, 'UTF8');
</code>```

As described in the manual, the Oracle client libraries will then handle conversion automatically:

The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set.

As long as you are outputting your results as UTF-8 the characters should render correctly.

Body:
I have a project where I am using ORACLE Database and CakePHP framework. I have a column where the datatype is NVARCHAR2. If I try to read the data from the database I get "¿¿¿¿¿". The code I am using is

ociexecute($stid, OCI_DEFAULT);
$i = 0;
$result = array();
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
       foreach ($row as $key => $value) {
                $result[$i][$key] = $value;
            }
            $i++;
}

Charset in my Database is -

NLS_LANGUAGE  AMERICAN NLS_TERRITORY  AMERICA
  NLS_CHARACTERSET  WE8MSWIN1252

Body:
Ensure that oci_connect is requesting data in UTF-8 like so:

$conn = oci_connect($username, $password, $conn_string, 'UTF8');

As described in the manual, the Oracle client libraries will then handle conversion automatically:

The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set.

As long as you are outputting your results as UTF-8 the characters should render correctly.


问:
Java_why print member variable give actual value?
```<code>class Customer {
    public String name;

    public Customer(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        Customer c = new Customer("Sally");
        System.out.println(c);
        System.out.println(c.name);
    }
}
</code>```

It's a simple question and we all know the output, but there's one quesiton about it

Please see the code above and the Picture here Passing Value

Question:

if I print out a reference of a object like this: System.out.println(c);, the IDE would generate a memory address for me: Customer@60e53b93

But, in the video tutorial(screenshot, see the image link Passing Value)

, the object have a member variable which is a reference to a String -> "Sally", why when I do System.out.println(c.name), trying to print out a reference(name), it give a real String object("Sally "). Shouldn't it print a memory address of the real Object("Sally")???

答:
System.out is a object of class PrintStream. And PrintStream.println() calls String.valueOf() for objects. And String.ValueOf(object) calls object.toString().
And for a String the PrintStream.println() prints out the string. Where as for the Customer class you are defaulting to the Object.toString() causing to the print the Customer@ string.

Body:
class Customer {
    public String name;

    public Customer(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        Customer c = new Customer("Sally");
        System.out.println(c);
        System.out.println(c.name);
    }
}

It's a simple question and we all know the output, but there's one quesiton about it

Please see the code above and the Picture here Passing Value

Question:

if I print out a reference of a object like this: System.out.println(c);, the IDE would generate a memory address for me: Customer@60e53b93

But, in the video tutorial(screenshot, see the image link Passing Value)

, the object have a member variable which is a reference to a String -> "Sally", why when I do System.out.println(c.name), trying to print out a reference(name), it give a real String object("Sally "). Shouldn't it print a memory address of the real Object("Sally")???


问:
How to use wordpress update_option() function to modify medium_large image deafault's width
In recent wordpress versions, a new default intermediate size, "medium_large", has been added to better take advantage of responsive image support. The new size is 768px wide by default, with no height limit.

The medium_large size is not included in the UI when selecting an image to insert in posts, nor are included UI to change the image size from the media settings page. However, developers can modify the width of this new size using the update_option() function, similar to any other default image size.

Usage:

```<code><?php update_option( $option, $new_value, $autoload ); ?>
</code>```

Considering I have already tried to edit default medium_large image size through the following code in functions.php file WITHOUT success, may you please help me building the code through update_option, as explained above?

```<code>function filter_image_resize_dimensions( $payload, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) {
if ( $orig_h > 200 ) {
    $new_w = 200;
    $new_h = auto;
}

return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
</code>```

}
add_filter( 'image_resize_dimensions', 'filter_image_resize_dimensions', 10, 6 );

答:
The filter max_srcset_image_width is not made to change the max width of the image size, but the max width of the srcset when using wp_calculate_image_srcset().

To change the sizes if the WordPress predefined images, you need to use image_resize_dimensions, you can read all the details here

UPDATE
From you given code, here is some correction about it

```<code>function filter_image_resize_dimensions( $payload, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) {
    if ( $orig_h === 300 ) {
        $new_w = 200; // you are checking for height and setting width ??
        $new_h = $orig_h; // you must define it to return a value, but here there's no change...
    }

    return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
}
add_filter( 'image_resize_dimensions', 'filter_image_resize_dimensions', 10, 6 );
</code>```

Hope it helps

Body:
In recent wordpress versions, a new default intermediate size, "medium_large", has been added to better take advantage of responsive image support. The new size is 768px wide by default, with no height limit.

The medium_large size is not included in the UI when selecting an image to insert in posts, nor are included UI to change the image size from the media settings page. However, developers can modify the width of this new size using the update_option() function, similar to any other default image size.

Usage:

<?php update_option( $option, $new_value, $autoload ); ?>

Considering I have already tried to edit default medium_large image size through the following code in functions.php file WITHOUT success, may you please help me building the code through update_option, as explained above?

function filter_image_resize_dimensions( $payload, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) {
if ( $orig_h > 200 ) {
    $new_w = 200;
    $new_h = auto;
}

return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );

}
add_filter( 'image_resize_dimensions', 'filter_image_resize_dimensions', 10, 6 );

Body:
The filter max_srcset_image_width is not made to change the max width of the image size, but the max width of the srcset when using wp_calculate_image_srcset().

To change the sizes if the WordPress predefined images, you need to use image_resize_dimensions, you can read all the details here

UPDATE
From you given code, here is some correction about it

function filter_image_resize_dimensions( $payload, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) {
    if ( $orig_h === 300 ) {
        $new_w = 200; // you are checking for height and setting width ??
        $new_h = $orig_h; // you must define it to return a value, but here there's no change...
    }

    return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
}
add_filter( 'image_resize_dimensions', 'filter_image_resize_dimensions', 10, 6 );

Hope it helps


问:
Could not load file or assembly or one of its dependencies
I changed some names of namespaces, assemblies in one of existing project (C# and ASP.NET). But when I try to debug it; I get this error.

Could not load file or assembly 'HR' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040).

I have replaced DFI with HR in the code.

答:
Sometime I have got such error and began to research how to resolve it. After all I just have added such attribute to web.config compilation node:

```<code><compilation debug="true" tempDirectory="c:\temp" >
</code>```

I hope that this can help and other people.

Body:
Sometime I have got such error and began to research how to resolve it. After all I just have added such attribute to web.config compilation node:

<compilation debug="true" tempDirectory="c:\temp" >

I hope that this can help and other people.


问:
dynamically add suggestion chips on Api.ai for Actions on google
I want to add suggestions for the user in my Google Assistant Bot. I am using API.ai for bot development and using fulfilment, I am communicating with my backend for data.

I am not able to send suggestions using suggestions chips to my bot.

 I have followed as answered here Webhook response with "suggestion chips"
as well as the document at https://developers.google.com/actions/assistant/responses#json.
But still, I only see simple text response at my bot on device as well as on simulator.

I also checked at https://discuss.api.ai/t/google-assistant-rich-message-responses/5134/19. But didn't find any way to switch to V1 or V2. The sample format also didn't work!

Here are my 2 JSONs:

at API.ai

```<code>"fulfillment": {
  "speech": "want to proceed further?",
  "messages": [
    {
      "type": 0,
      "speech": "want to proceed further?"
    }
  ],
  "data": {
    "google": {
      "conversationToken": "[\"AS-PER-JSON-FROM-SIMULATOR\"]",
      "expectedInputs": [
        {
          "inputPrompt": {
            "richInitialPrompt": {
              "items": [
                {
                  "simpleResponse": {
                    "textToSpeech": "want to proceed further?",
                    "displayText": "want to proceed further?"
                  }
                }
              ],
              "suggestions": [
                {
                  "title": "Yes"
                },
                {
                  "title": "No"
                }
              ]
            }
          }
        }
      ]
    }
  }
},
</code>```

at action on Google

```<code>"expectUserResponse": true,
    "expectedInputs": [
        {
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": [
                        {
                            "simpleResponse": {
                                "textToSpeech": "want to proceed?"
                            }
                        }
                    ]
                },
                "noMatchPrompts": [],
                "noInputPrompts": []
            },
            "possibleIntents": [
                {
                    "intent": "assistant.intent.action.TEXT"
                }
            ],
            "speechBiasingHints": [
                "$subject",
                "$answer"
            ]
        }
    ]
</code>```

python server

```<code>return = '{"speech":"want to proceed?", "data": {"google":{"expectedInputs":[{"inputPrompt":{"richInitialPrompt":{"items":[{"simpleResponse":{"textToSpeech":"want to proceed?","displayText":"want to proceed?"}}],"suggestions":[{"title":"Yes"},{"title":"No"}]}}}]}}}'
</code>```

答:
Your JSON is wrong, remove the quotation mark before the data object:

```<code>"data" : { ... }
</code>```

instead of

```<code>"data" : "{ ... }"
</code>```

So basically, you're sending a string containing the object instead of a JSON object.

Body:
I want to add suggestions for the user in my Google Assistant Bot. I am using API.ai for bot development and using fulfilment, I am communicating with my backend for data.

I am not able to send suggestions using suggestions chips to my bot.

 I have followed as answered here Webhook response with "suggestion chips"
as well as the document at https://developers.google.com/actions/assistant/responses#json.
But still, I only see simple text response at my bot on device as well as on simulator.

I also checked at https://discuss.api.ai/t/google-assistant-rich-message-responses/5134/19. But didn't find any way to switch to V1 or V2. The sample format also didn't work!

Here are my 2 JSONs:

at API.ai

"fulfillment": {
  "speech": "want to proceed further?",
  "messages": [
    {
      "type": 0,
      "speech": "want to proceed further?"
    }
  ],
  "data": {
    "google": {
      "conversationToken": "[\"AS-PER-JSON-FROM-SIMULATOR\"]",
      "expectedInputs": [
        {
          "inputPrompt": {
            "richInitialPrompt": {
              "items": [
                {
                  "simpleResponse": {
                    "textToSpeech": "want to proceed further?",
                    "displayText": "want to proceed further?"
                  }
                }
              ],
              "suggestions": [
                {
                  "title": "Yes"
                },
                {
                  "title": "No"
                }
              ]
            }
          }
        }
      ]
    }
  }
},

at action on Google

"expectUserResponse": true,
    "expectedInputs": [
        {
            "inputPrompt": {
                "richInitialPrompt": {
                    "items": [
                        {
                            "simpleResponse": {
                                "textToSpeech": "want to proceed?"
                            }
                        }
                    ]
                },
                "noMatchPrompts": [],
                "noInputPrompts": []
            },
            "possibleIntents": [
                {
                    "intent": "assistant.intent.action.TEXT"
                }
            ],
            "speechBiasingHints": [
                "$subject",
                "$answer"
            ]
        }
    ]

python server

return = '{"speech":"want to proceed?", "data": {"google":{"expectedInputs":[{"inputPrompt":{"richInitialPrompt":{"items":[{"simpleResponse":{"textToSpeech":"want to proceed?","displayText":"want to proceed?"}}],"suggestions":[{"title":"Yes"},{"title":"No"}]}}}]}}}'

Body:
Your JSON is wrong, remove the quotation mark before the data object:

"data" : { ... }

instead of

"data" : "{ ... }"

So basically, you're sending a string containing the object instead of a JSON object.


问:
IVMRWindowlessControl.RepaintVideo causing Attempted to divide by zero
I have developed an C# application with Directshow.NET to show camera preview. All is going well almost on every OS but on some of windows OS 10 machines (not every win OS 10, just some of them) preview get failed due to Exception Attempted to divide by zero. at line hr = vmr9Control.RepaintVideo(hControl.Handle, gHDC); inside Paint event of Control.

I searched a lot to find the cause of this exception, even I formattted one of the machine but issue is still there. Also as per observation this exception will not come at the first attempt of preview, after 5-6 iteration of show preview & stop preview causes this exception.

```<code>private void SetupGraph(DsDevice dev, Control hControl)
{
...
vmr9Control = (IVMRWindowlessControl)vmr9preview;
vmr9Control.SetVideoClippingWindow(hControl.Handle);
vmr9Control.SetAspectRatioMode(VMRAspectRatioMode.None);
hControl.Paint += new PaintEventHandler(hControl_Paint);
...
}

[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand, Flags =
System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)]
void hControl_Paint(object sender, PaintEventArgs e)
{
    if (isPreviewstarted && vmr9Control != null)
    {
        int hr;
        IntPtr gHDC = e.Graphics.GetHdc();
        hr = vmr9Control.RepaintVideo(hControl.Handle, gHDC);
        DsError.ThrowExceptionForHR(hr);
        e.Graphics.ReleaseHdc(gHDC);
    }
}
</code>```

答:
I suggest you uninstall and reinstall the graphic card drivers.

Steps : Uninstall and re-install display drivers.

To remove the display drivers from Device Manager:

a. Open Device Manager by clicking the Start button or type Device Manager in the search box.

b. If you are prompted for an administrator password or confirmation, type the password or provide confirmation.

c. Look for the Display adapter drivers, right click on it and select Uninstall.

d. Reboot the computer.

e. On reboot, Windows 10 should re-install the drivers automatically.

Body:
I have developed an C# application with Directshow.NET to show camera preview. All is going well almost on every OS but on some of windows OS 10 machines (not every win OS 10, just some of them) preview get failed due to Exception Attempted to divide by zero. at line hr = vmr9Control.RepaintVideo(hControl.Handle, gHDC); inside Paint event of Control.

I searched a lot to find the cause of this exception, even I formattted one of the machine but issue is still there. Also as per observation this exception will not come at the first attempt of preview, after 5-6 iteration of show preview & stop preview causes this exception.

private void SetupGraph(DsDevice dev, Control hControl)
{
...
vmr9Control = (IVMRWindowlessControl)vmr9preview;
vmr9Control.SetVideoClippingWindow(hControl.Handle);
vmr9Control.SetAspectRatioMode(VMRAspectRatioMode.None);
hControl.Paint += new PaintEventHandler(hControl_Paint);
...
}

[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand, Flags =
System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode)]
void hControl_Paint(object sender, PaintEventArgs e)
{
    if (isPreviewstarted && vmr9Control != null)
    {
        int hr;
        IntPtr gHDC = e.Graphics.GetHdc();
        hr = vmr9Control.RepaintVideo(hControl.Handle, gHDC);
        DsError.ThrowExceptionForHR(hr);
        e.Graphics.ReleaseHdc(gHDC);
    }
}


问:
How to iterate over json response array
I have a question about Gatling.

I need to get the following response:

```<code>[
{
"id": 1,
"name": "Jack"
},
{
"id": 2,
"name": "John"
}
]
</code>```

grab those ids, iterate over them and make a new request for each of them.
So far I have this:

```<code>.exec(
            http("Image list")
                .get("/api/img")
                .headers(headers_0)
                .check(
                    jsonPath("$..id").findAll.saveAs("imgs")
                )
        )
</code>```

It successfuly saves ids to "imgs" which is session variable but I am not able to iterate over them or process it at all.
How can I process it? I am new to Gatling and Scala so I have no idea how to approach this.
Please help.

答:
I found a solution.
The only possible format is Seq. In my case this solves the problem:

```<code>val imageIds = session("imgs").as[Seq[String]]
</code>```

Title: How to iterate over json response array

Body:
I have a question about Gatling.

I need to get the following response:

[
{
"id": 1,
"name": "Jack"
},
{
"id": 2,
"name": "John"
}
]

grab those ids, iterate over them and make a new request for each of them.
So far I have this:

.exec(
            http("Image list")
                .get("/api/img")
                .headers(headers_0)
                .check(
                    jsonPath("$..id").findAll.saveAs("imgs")
                )
        )

It successfuly saves ids to "imgs" which is session variable but I am not able to iterate over them or process it at all.
How can I process it? I am new to Gatling and Scala so I have no idea how to approach this.
Please help.

Body:
I found a solution.
The only possible format is Seq. In my case this solves the problem:

val imageIds = session("imgs").as[Seq[String]]


问:
Linked jQuery document not responding
I am currently trying to build a image slider for a website. I have written all of the code required for this to work yet I have having trouble making the jQuery respond or work within the HTML document.

The HTML of the page is:

var currentIndex = 0,
  items = $('.container div'),
  itemsAmt = items.length;

function cycleItems() {
  var item = $('.container div').eq(currentIndex);
  items.hide();
  item.css('display', 'inline-block');
}

var autoSlide = setInterval(function() {
  currentIndex += 1;
  if (currentIndex > itemsAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
}, 3000);

$('.next').click(function() {
  clearInterval(autoSlide);
  currentIndex += 1;
  if (currentIndex > itemsAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
});

$('.prev').click(function() {
  clearInterval(autoSlide);
  currentIndex -= 1;
  if (currentIndex < 0) {
    currentIndex = itemsAmt - 1;
  }
  cycleItems();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  max-width: 400px;
  background-color: black;
  margin: 0 auto;
  text-align: center;
  position: relative;
}

.container div {
  background-color: white;
  width: 100%;
  display: inline-block;
  display: none;
}

.container img {
  width: 100%;
  height: auto;
}

button {
  position: absolute;
}

.next {
  right: 5px;
}

.prev {
  left: 5px;
}</code>```

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

    <button class="next">Next</button>
    <button class="prev">Previous</button>

```

答:
Two things you can consider:
Either wait for the ready state of the DOM tree with, which results into that all DOM elements and references are generated correctly:

```<code>$(document).ready(function() {
//your code here
});
</code>```

This would be the much safer way. Another possible solution is to include your JavaScript files at the bottom of your code e.g. before the  HTML-Tag. Also here it may be important to wait for the DOM ready state to reduce the possibility of errors.

Title: Linked jQuery document not responding

Body:
I am currently trying to build a image slider for a website. I have written all of the code required for this to work yet I have having trouble making the jQuery respond or work within the HTML document.

The HTML of the page is:

var currentIndex = 0,
  items = $('.container div'),
  itemsAmt = items.length;

function cycleItems() {
  var item = $('.container div').eq(currentIndex);
  items.hide();
  item.css('display', 'inline-block');
}

var autoSlide = setInterval(function() {
  currentIndex += 1;
  if (currentIndex > itemsAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
}, 3000);

$('.next').click(function() {
  clearInterval(autoSlide);
  currentIndex += 1;
  if (currentIndex > itemsAmt - 1) {
    currentIndex = 0;
  }
  cycleItems();
});

$('.prev').click(function() {
  clearInterval(autoSlide);
  currentIndex -= 1;
  if (currentIndex < 0) {
    currentIndex = itemsAmt - 1;
  }
  cycleItems();
});

.container {
  max-width: 400px;
  background-color: black;
  margin: 0 auto;
  text-align: center;
  position: relative;
}

.container div {
  background-color: white;
  width: 100%;
  display: inline-block;
  display: none;
}

.container img {
  width: 100%;
  height: auto;
}

button {
  position: absolute;
}

.next {
  right: 5px;
}

.prev {
  left: 5px;
}

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

    <button class="next">Next</button>
    <button class="prev">Previous</button>

Body:
Two things you can consider:
Either wait for the ready state of the DOM tree with, which results into that all DOM elements and references are generated correctly:

$(document).ready(function() {
//your code here
});

This would be the much safer way. Another possible solution is to include your JavaScript files at the bottom of your code e.g. before the </body> HTML-Tag. Also here it may be important to wait for the DOM ready state to reduce the possibility of errors.


问:
Linq to many objects using MVC
I am trying to use Linq to create an object which itself contains 2 data objects. From the Linq expression I am trying to set up the objects directly rather than having an inbetween function in the containing class.

The containing class looks like this:

```<code>public class SupplierCategories
{

    public  category _category;
    public category_sub _category_sub;
    private bool _IsActive;
    private int? _SupplierID;

    public SupplierCategories()
    {

    }

    public bool IsActive
    {
        get
        {
            return _IsActive;
        }
        set
        {
            _IsActive = value;
        }
    }

    public int? SupplierID
    {
        get
        {
            return _SupplierID;
        }
        set
        {
            _SupplierID = value;
            if (_SupplierID != null) // The county is active if there is a supplier ID matching
            {
                _IsActive = true;
            }
        }

    }
}
</code>```

Note: category and category_sub objects are all set up through the Entity Framework.

My link expression has 2 tables and looks like this:

```<code>    public IEnumerable<SupplierCategories> GetAllOrdered()
    {
        IEnumerable<SupplierCategories> areaList;

        var results = from cat in dbContext.categories
                      join sub in dbContext.category_sub on cat.id equals sub.categoryid
                      orderby cat.id ascending, sub.name ascending
                      select new SupplierCategories
                      {
                          _category = { new category { cat.id, cat.name } },
                          _category_sub = { new category_sub { sub.id, sub.categoryid, sub.name } }
                      };

        areaList = results.ToList();

        return areaList;
    }
</code>```

Hopefully you can see that I am trying to create the "_category" and "_category_sub" objects directly.

The error I get is:

Error 5 Cannot initialize type
  'Essential_Collections.Models.category'
  with a collection initializer because
  it does not implement
  'System.Collections.IEnumerable'
  D:\Websites\Essential
  Collections\development\build\Essential
  Collections\Models\SupplierCategories\SupplierCategoriesRepository.cs
  51 37 Essential Collections

Any solutions or possibly other approaches would be gratefully received

答:
Try removing the extra braces thus:</p>

```<code>public IEnumerable<SupplierCategories> GetAllOrdered()
{
    IEnumerable<SupplierCategories> areaList;

    var results = from cat in dbContext.categories
                  join sub in dbContext.category_sub on cat.id equals sub.categoryid
                  orderby cat.id ascending, sub.name ascending
                  select new SupplierCategories()
                  {
                      _category = cat,
                      _category_sub = sub
                  };

    areaList = results.ToList();

    return areaList;
}
</code>```

Title: Linq to many objects using MVC

Body:
I am trying to use Linq to create an object which itself contains 2 data objects. From the Linq expression I am trying to set up the objects directly rather than having an inbetween function in the containing class.

The containing class looks like this:

public class SupplierCategories
{

    public  category _category;
    public category_sub _category_sub;
    private bool _IsActive;
    private int? _SupplierID;

    public SupplierCategories()
    {

    }

    public bool IsActive
    {
        get
        {
            return _IsActive;
        }
        set
        {
            _IsActive = value;
        }
    }

    public int? SupplierID
    {
        get
        {
            return _SupplierID;
        }
        set
        {
            _SupplierID = value;
            if (_SupplierID != null) // The county is active if there is a supplier ID matching
            {
                _IsActive = true;
            }
        }

    }
}

Note: category and category_sub objects are all set up through the Entity Framework.

My link expression has 2 tables and looks like this:

    public IEnumerable<SupplierCategories> GetAllOrdered()
    {
        IEnumerable<SupplierCategories> areaList;

        var results = from cat in dbContext.categories
                      join sub in dbContext.category_sub on cat.id equals sub.categoryid
                      orderby cat.id ascending, sub.name ascending
                      select new SupplierCategories
                      {
                          _category = { new category { cat.id, cat.name } },
                          _category_sub = { new category_sub { sub.id, sub.categoryid, sub.name } }
                      };

        areaList = results.ToList();

        return areaList;
    }

Hopefully you can see that I am trying to create the "_category" and "_category_sub" objects directly.

The error I get is:

Error 5 Cannot initialize type
  'Essential_Collections.Models.category'
  with a collection initializer because
  it does not implement
  'System.Collections.IEnumerable'
  D:\Websites\Essential
  Collections\development\build\Essential
  Collections\Models\SupplierCategories\SupplierCategoriesRepository.cs
  51 37 Essential Collections

Any solutions or possibly other approaches would be gratefully received

Body:
Try removing the extra braces thus:

public IEnumerable<SupplierCategories> GetAllOrdered()
{
    IEnumerable<SupplierCategories> areaList;

    var results = from cat in dbContext.categories
                  join sub in dbContext.category_sub on cat.id equals sub.categoryid
                  orderby cat.id ascending, sub.name ascending
                  select new SupplierCategories()
                  {
                      _category = cat,
                      _category_sub = sub
                  };

    areaList = results.ToList();

    return areaList;
}