问:
Hadoop Mapreduce Job: Input path does not exist: hdfs://localhost:9000/user/******/grep-temp-1208171489
I am running an example mapreduce job that comes with Hadoop 2.8.1

I am using these commands:

```<code>bin/hdfs dfs -copyFromLocal etc/hadoop/core-site.xml .

bin/hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.3.jar grep ./core-site.xml output ‘configuration’
</code>```

However, when I run this, the job exits (the main error appears in the title):

```<code>***********s-mbp-2:hadoop-2.8.1 ***********$ bin/hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.8.1.jar grep ./core-site.xml output ‘configuration’
17/09/12 14:30:28 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/09/12 14:30:29 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
17/09/12 14:30:29 INFO input.FileInputFormat: Total input files to process : 1
17/09/12 14:30:30 INFO mapreduce.JobSubmitter: number of splits:1
17/09/12 14:30:30 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1505251091124_0001
17/09/12 14:30:30 INFO impl.YarnClientImpl: Submitted application application_1505251091124_0001
17/09/12 14:30:30 INFO mapreduce.Job: The url to track the job: http://***********s-mbp-2.lan:8088/proxy/application_1505251091124_0001/
17/09/12 14:30:30 INFO mapreduce.Job: Running job: job_1505251091124_0001
17/09/12 14:30:33 INFO mapreduce.Job: Job job_1505251091124_0001 running in uber mode : false
17/09/12 14:30:33 INFO mapreduce.Job:  map 0% reduce 0%
17/09/12 14:30:33 INFO mapreduce.Job: Job job_1505251091124_0001 failed with state FAILED due to: Application application_1505251091124_0001 failed 2 times due to AM Container for appattempt_1505251091124_0001_000002 exited with  exitCode: 127
Failing this attempt.Diagnostics: Exception from container-launch.
Container id: container_1505251091124_0001_02_000001
Exit code: 127
Stack trace: ExitCodeException exitCode=127:
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:972)
    at org.apache.hadoop.util.Shell.run(Shell.java:869)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:1170)
    at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:236)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:305)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:84)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Container exited with a non-zero exit code 127
For more detailed output, check the application tracking page: http://***********s-mbp-2.lan:8088/cluster/app/application_1505251091124_0001 Then click on links to logs of each attempt.
. Failing the application.
17/09/12 14:30:33 INFO mapreduce.Job: Counters: 0
17/09/12 14:30:33 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
17/09/12 14:30:33 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/***********/.staging/job_1505251091124_0002
org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://localhost:9000/user/***********/grep-temp-576807334
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:329)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:271)
    at org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat.listStatus(SequenceFileInputFormat.java:59)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:393)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:303)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:320)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:198)
    at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1341)
    at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1338)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1807)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1338)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1359)
    at org.apache.hadoop.examples.Grep.run(Grep.java:94)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:76)
    at org.apache.hadoop.examples.Grep.main(Grep.java:103)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:71)
    at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
    at org.apache.hadoop.examples.ExampleDriver.main(ExampleDriver.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:234)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:148)
</code>```

What is going wrong, and how do I fix it?

答: It looks like the program can't access the path in the exception. You may try to manually create that directory with mkdir in hdfs system before running the code. Hope it will help.</p>

Body:
I am running an example mapreduce job that comes with Hadoop 2.8.1

I am using these commands:

bin/hdfs dfs -copyFromLocal etc/hadoop/core-site.xml .

bin/hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.3.jar grep ./core-site.xml output ‘configuration’

However, when I run this, the job exits (the main error appears in the title):

***********s-mbp-2:hadoop-2.8.1 ***********$ bin/hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.8.1.jar grep ./core-site.xml output ‘configuration’
17/09/12 14:30:28 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
17/09/12 14:30:29 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
17/09/12 14:30:29 INFO input.FileInputFormat: Total input files to process : 1
17/09/12 14:30:30 INFO mapreduce.JobSubmitter: number of splits:1
17/09/12 14:30:30 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1505251091124_0001
17/09/12 14:30:30 INFO impl.YarnClientImpl: Submitted application application_1505251091124_0001
17/09/12 14:30:30 INFO mapreduce.Job: The url to track the job: http://***********s-mbp-2.lan:8088/proxy/application_1505251091124_0001/
17/09/12 14:30:30 INFO mapreduce.Job: Running job: job_1505251091124_0001
17/09/12 14:30:33 INFO mapreduce.Job: Job job_1505251091124_0001 running in uber mode : false
17/09/12 14:30:33 INFO mapreduce.Job:  map 0% reduce 0%
17/09/12 14:30:33 INFO mapreduce.Job: Job job_1505251091124_0001 failed with state FAILED due to: Application application_1505251091124_0001 failed 2 times due to AM Container for appattempt_1505251091124_0001_000002 exited with  exitCode: 127
Failing this attempt.Diagnostics: Exception from container-launch.
Container id: container_1505251091124_0001_02_000001
Exit code: 127
Stack trace: ExitCodeException exitCode=127:
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:972)
    at org.apache.hadoop.util.Shell.run(Shell.java:869)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:1170)
    at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:236)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:305)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:84)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Container exited with a non-zero exit code 127
For more detailed output, check the application tracking page: http://***********s-mbp-2.lan:8088/cluster/app/application_1505251091124_0001 Then click on links to logs of each attempt.
. Failing the application.
17/09/12 14:30:33 INFO mapreduce.Job: Counters: 0
17/09/12 14:30:33 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032
17/09/12 14:30:33 INFO mapreduce.JobSubmitter: Cleaning up the staging area /tmp/hadoop-yarn/staging/***********/.staging/job_1505251091124_0002
org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://localhost:9000/user/***********/grep-temp-576807334
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:329)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:271)
    at org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat.listStatus(SequenceFileInputFormat.java:59)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:393)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:303)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:320)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:198)
    at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1341)
    at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1338)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1807)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1338)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1359)
    at org.apache.hadoop.examples.Grep.run(Grep.java:94)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:76)
    at org.apache.hadoop.examples.Grep.main(Grep.java:103)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:71)
    at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
    at org.apache.hadoop.examples.ExampleDriver.main(ExampleDriver.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:234)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:148)

What is going wrong, and how do I fix it?


来源: stackexchange

问:
JQuery Autocomplete malfunction
First time posting so I apologise for any mistakes and for if this has been answered before.

There might be something obvious that I've missed but this function doesn't filter the list of variables. When I enter "0" it shows nothing, but then when I type "j" (and a few other characters such as "e", "c" and "b") the function shows everything in the array.

```<code><head>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
    $(function()
    {
        var data = [{"Part_no":"0001","Part_description":"Part 1"},{"Part_no":"0002","Part_description":"Part 2"}]

        $( "#project" ).autocomplete({
            minLength: 1,
            source: data,
            select: function( event, ui )
            {
                $( "#project" ).val( ui.item.Part_no );
                $( "#project-description" ).html( ui.item.Part_description );

                return false;
            }
        })
        .autocomplete( "instance" )._renderItem = function( ul, item )
        {
          return $( "<li>" )
            .append( "<div>" + item.Part_no + "<br>" + item.Part_description + "</div>" )
            .appendTo( ul );
        };
    });
    </script>
</head>
<body>
    <input id="project">
</body>
</code>```

Thank you for looking.

答:
The issue here was that the process was looking for a "label" array key.

Changing all instances of "Part_no" to "label" fixed the issue. I did this using array_map() in PHP but if anyone knows how to do this in JQuery I would very much like to know.

ContentLicense: CC BY-SA 3.0

Title: JQuery Autocomplete malfunction

Body:
First time posting so I apologise for any mistakes and for if this has been answered before.

There might be something obvious that I've missed but this function doesn't filter the list of variables. When I enter "0" it shows nothing, but then when I type "j" (and a few other characters such as "e", "c" and "b") the function shows everything in the array.

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    <input id="project">

Thank you for looking.


问:
In Firefox (2 or 3), what is the chrome:// path for the "Website Certified by Unknown Authority" XUL dialog?
Another angle:
how do I browse all the XUL for a given chrome path, e.g.

http://kb.mozillazine.org/Dev_:_Firefox_Chrome_URLs has a listing but seems to be out of date.

答:
Mozilla chrome:// URLs refer to actual files located in a .jar file in some fairly well-defined places.

The main browser (chrome://browser/content/...) itself:

```<code>{where you installed Firefox}/chrome/browser.jar
</code>```

Firefox add-ons:

```<code>{your profile directory}/extensions/{extension id}/chrome/content/...
</code>```

where {your profile directory}, on Windows XP at least, is

```<code>c:\Documents and Settings\{your username}\Application Data\Mozilla\Firefox\Profiles\{your profile name, usually ends in .default}
</code>```

OwnerDisplayName: someguy

ContentLicense: CC BY-SA 2.5

Body:
Mozilla chrome:// URLs refer to actual files located in a .jar file in some fairly well-defined places.

The main browser (chrome://browser/content/...) itself:

{where you installed Firefox}/chrome/browser.jar

Firefox add-ons:

{your profile directory}/extensions/{extension id}/chrome/content/...

where {your profile directory}, on Windows XP at least, is

c:\Documents and Settings\{your username}\Application Data\Mozilla\Firefox\Profiles\{your profile name, usually ends in .default}

OwnerDisplayName: Jason S


问:
Reason for: Trying to get property of non-object in php
```<code>    if(isset($_POST['uname']))
    {
        $query = "SELECT * FROM user_info";
        $res = $mysqli->query($query);
        $num = $res->num_rows;
        $i = 0;
        $cpwd = $_POST["pswd"];
        $hpwd = SHA1($cpwd);
        $tmp = $_POST["uname"];
        while($i < $num)
        {
            $row = $res->fetch_object();
            $name = $row->Username;
            $pwd = $row->Password;
            if($name == $tmp)
            {
                   //check if user is blocked
            }
            //hashed pwd
            if($pwd == $hpwd)
            {
                //success
                exit();
            }
            //request for pwd change
        else if($pwd == $cpwd)
            {
            //change
                exit();
            }
            else if($pwd != $hpwd)
            {

                //incorrect pwd
            }
        }
        $i++;
    }
    if($i == $num)
    {
        //new user
    }
}
</code>```

答: I'd guess that you're somehow looping past the end of the array and $row is actually NULL.


问:
QBO3 override css for standard inputs
What is the css to change the an input field with class qbo-xxxx? I would like to change the qbo-date field to width of 200px. Something like this:</p>

```<code><style type="text/css">
.section {
    background:none;
    color:#777;
    border-bottom: #CCC 1px solid;
    font-weight:normal;
    text-transform:uppercase;
    margin-bottom:1em;
}

form.grid label:not(.radio) {
    width: 200px;
}
</style>
</code>```

答:
TLDR; You should use something like:

```<code>.qbo-date
{
    width: 16em !important;
}
</code>```

QBO3 offers several standard classes for common input types, defined in qbo.ApplicationWeb / Styles / qbo3.less, including:

.qbo-date

.qbo-money

.qbo-zip

.qbo-int

.qbo-numeric

.qbo-percent

The .qbo-date class is defined as:

```<code>.qbo-date
{
    width: 8em !important;
}
</code>```

Note the use of em vs px - your override should consider responsive design too!

Given that qbo-date uses 8em by default, if you want to double the input length, use 16em (as noted at the top).

Consider experimenting directly in Chrome; you can edit CSS directly in the debugger:

vs:

Title: QBO3 override css for standard inputs

Body:
TLDR; You should use something like:

.qbo-date
{
    width: 16em !important;
}

QBO3 offers several standard classes for common input types, defined in qbo.ApplicationWeb / Styles / qbo3.less, including:

.qbo-date

.qbo-money

.qbo-zip

.qbo-int

.qbo-numeric

.qbo-percent

The .qbo-date class is defined as:

.qbo-date
{
    width: 8em !important;
}

Note the use of em vs px - your override should consider responsive design too!

Given that qbo-date uses 8em by default, if you want to double the input length, use 16em (as noted at the top).

Consider experimenting directly in Chrome; you can edit CSS directly in the debugger:

vs:


问:
Error while adding custom header param in Volley
My code is like this...

```<code>@Override
 public Map<String, String> getHeaders() throws AuthFailureError {
  Map<String, String> params = new HashMap<>();
  params.put("Cookie: sessionid=","07yy02a83089836ddabd4f6bf57e9677");
  return params;
}
</code>```

when i print it on my server side with $_COOKIE['sessionid'] it is coming like...

```<code>  ": 07yy02a83089836ddabd4f6bf57e9677"
</code>```

a :(colon) is being added to the value of that param. i couldn't find the reason after long search in internet helps! hope someone can help me...

答:
I got it fixed by setting like this...</p>

```<code> params.put("Cookie","sessionid=07yy02a83089836ddabd4f6bf57e9677");
</code>```

Body:
My code is like this...

@Override
 public Map<String, String> getHeaders() throws AuthFailureError {
  Map<String, String> params = new HashMap<>();
  params.put("Cookie: sessionid=","07yy02a83089836ddabd4f6bf57e9677");
  return params;
}

when i print it on my server side with $_COOKIE['sessionid'] it is coming like...

  ": 07yy02a83089836ddabd4f6bf57e9677"

a :(colon) is being added to the value of that param. i couldn't find the reason after long search in internet helps! hope someone can help me...

Body:
I got it fixed by setting like this...

 params.put("Cookie","sessionid=07yy02a83089836ddabd4f6bf57e9677");


问:
How do I remove this listener in OnDestroy (Android Firebase)?
This is my ValueEventListener in OnCreate method. I want to destroy this is OnDestroy method because it might be causing memory leak and also I've read it that it's a good practice to do so. </p>

```<code>mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            display_author = (String) dataSnapshot.child("author").getValue();
            display_quote = (String) dataSnapshot.child("quote").getValue();
            display_pic_url = (String) dataSnapshot.child("pic_url").getValue();
            categoryData=(String) dataSnapshot.child("catg").getValue();
            display_prof=(String) dataSnapshot.child("prof").getValue();
            copyQuote = (display_quote + " - " +display_author);
            try {
                author.setText(display_author);
                quote.setText(display_quote);
                category.setText(categoryData);
                profession.setText(display_prof);
                Glide.with(SingleExploreQuotes.this).load(display_pic_url).override(192, 192).into(profile_img);

            } catch (Exception e) {
                finish();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
</code>```

答:
For those looking for the Firebase Firestore version of this answer Use ListenerRegistration and then call .remove() on it in onDestroy()

```<code>private ListenerRegistration listenerRegistration;

listenerRegistration = Reference.addsnapshotListener(new
EventListener<QuerySnapshot>){
  @Override
        public void onEvent(QuerySnapshot documentSnapshots,
        FirebaseFirestoreException e) {
         //get your data

  }
});

@Override
protected void onDestroy() {
    super.onDestroy();

    if(listenerRegistration != null) {
        listenerRegistration.remove();
    }

}
</code>```

Body:
This is my ValueEventListener in OnCreate method. I want to destroy this is OnDestroy method because it might be causing memory leak and also I've read it that it's a good practice to do so.

mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            display_author = (String) dataSnapshot.child("author").getValue();
            display_quote = (String) dataSnapshot.child("quote").getValue();
            display_pic_url = (String) dataSnapshot.child("pic_url").getValue();
            categoryData=(String) dataSnapshot.child("catg").getValue();
            display_prof=(String) dataSnapshot.child("prof").getValue();
            copyQuote = (display_quote + " - " +display_author);
            try {
                author.setText(display_author);
                quote.setText(display_quote);
                category.setText(categoryData);
                profession.setText(display_prof);
                Glide.with(SingleExploreQuotes.this).load(display_pic_url).override(192, 192).into(profile_img);

            } catch (Exception e) {
                finish();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

Body:
For those looking for the Firebase Firestore version of this answer Use ListenerRegistration and then call .remove() on it in onDestroy()

private ListenerRegistration listenerRegistration;

listenerRegistration = Reference.addsnapshotListener(new
EventListener<QuerySnapshot>){
  @Override
        public void onEvent(QuerySnapshot documentSnapshots,
        FirebaseFirestoreException e) {
         //get your data

  }
});

@Override
protected void onDestroy() {
    super.onDestroy();

    if(listenerRegistration != null) {
        listenerRegistration.remove();
    }

}


问:
How to solve this logic operation? (homework)
The teacher gave us this question and I couldn't answer it and I hope to get here some help.

Perform the following logic operation:

1- AB5D AND CD5F

2- DD1D XOR B159

And I want to know the step that I should follow to find the right answer.

答:
The members are in hexadecimal (AB5D, CD5F, ...), so it's easier if you transform them in binary before. You can use this table:

```<code>0 = 0000  4 = 0100  8 = 1000  C = 1100
1 = 0001  5 = 0101  9 = 1001  D = 1101
2 = 0010  6 = 0110  A = 1010  E = 1110
3 = 0011  7 = 0111  B = 1011  F = 1111
</code>```

So, AB5D is 1010101101011101.

And then you apply the bitwise operations. It means the result of, for example, A XOR 3 is:

```<code>A XOR 3 =
1010 XOR 0011 =
1001 =
9 (see conversion table)
</code>```

Body:
The members are in hexadecimal (AB5D, CD5F, ...), so it's easier if you transform them in binary before. You can use this table:

0 = 0000  4 = 0100  8 = 1000  C = 1100
1 = 0001  5 = 0101  9 = 1001  D = 1101
2 = 0010  6 = 0110  A = 1010  E = 1110
3 = 0011  7 = 0111  B = 1011  F = 1111

So, AB5D is 1010101101011101.

And then you apply the bitwise operations. It means the result of, for example, A XOR 3 is:

A XOR 3 =
1010 XOR 0011 =
1001 =
9 (see conversion table)


问:
jQuery serialize does not register checkboxes
I'm using jQuery.serialize to retrieve all data fields in a form.

My problem is that it does not retriev checkboxes that is not checked.

It includes this:

```<code><input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />
</code>```

but not this

```<code><input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />
</code>```

How can I get "values" of checkboxes that is not checked?

答:
For ASP.NET MVC, we successfully save a form with checkboxes via an AJAX POST with the following, which is a combination of several methods referenced in this post, including @Jecoms suggestion:

```<code>var form = $('#myForm');
// Serialize the form into a JavaScript object using the jQuery.serializeObject plugin
// https://plugins.jquery.com/serializeObject/
var data = form.serializeObject();
// Change the submitted value of checkboxes to the value of the checked property
$('#myForm input[type=checkbox]').each( function () { data[this.name] = this.checked; } );
// For a MVC controller, convert the JS object back into a query string using jQuery.param function
data = $.param(data);
// Perform AJAX POST with the form data
$.ajax({
    async: true,
    url: 'mvcActionMethodURL',
    type: 'POST',
    data: data,
    success: function (data, textStatus, xhr) {

    },
    error: function (xhr, status, error) {

    }
});
</code>```

Body:
I'm using jQuery.serialize to retrieve all data fields in a form.

My problem is that it does not retriev checkboxes that is not checked.

It includes this:

<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />

but not this

<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />

How can I get "values" of checkboxes that is not checked?

Body:
For ASP.NET MVC, we successfully save a form with checkboxes via an AJAX POST with the following, which is a combination of several methods referenced in this post, including @Jecoms suggestion:

var form = $('#myForm');
// Serialize the form into a JavaScript object using the jQuery.serializeObject plugin
// https://plugins.jquery.com/serializeObject/
var data = form.serializeObject();
// Change the submitted value of checkboxes to the value of the checked property
$('#myForm input[type=checkbox]').each( function () { data[this.name] = this.checked; } );
// For a MVC controller, convert the JS object back into a query string using jQuery.param function
data = $.param(data);
// Perform AJAX POST with the form data
$.ajax({
    async: true,
    url: 'mvcActionMethodURL',
    type: 'POST',
    data: data,
    success: function (data, textStatus, xhr) {

    },
    error: function (xhr, status, error) {

    }
});


问:
Unable to set alternate app icons in iOS 11
I am unable to change the app's icon to an alternate icon in iOS 11 (Xcode 9, beta 3).

However, it works fine in iOS 10.3 (with the following code):

```<code>    if #available(iOS 10.3, *) {
        guard let iconName = MySingletonClass.sharedInstance.iconName() else { return }
        delay(0.01) {
            UIApplication.shared.setAlternateIconName(iconName, completionHandler: { (error) in
                if let error = error {
                    print(error.localizedDescription)
                } else {
                    print("Success!")
                }
            })
        }
    } else {
        // Fallback on earlier versions
    }
</code>```

My plist is set-up like so:

I find it odd because I have used other apps that use alternate app icons in iOS 11. Is there a known bug with this in iOS 11?

Note: If you're wondering why I'm using the delay, see this post

答:
If this will not help, disable app icons assets. It helps me.
I guess there is some conflict between assets and plist icons.</p>

Body:
I am unable to change the app's icon to an alternate icon in iOS 11 (Xcode 9, beta 3).

However, it works fine in iOS 10.3 (with the following code):

    if #available(iOS 10.3, *) {
        guard let iconName = MySingletonClass.sharedInstance.iconName() else { return }
        delay(0.01) {
            UIApplication.shared.setAlternateIconName(iconName, completionHandler: { (error) in
                if let error = error {
                    print(error.localizedDescription)
                } else {
                    print("Success!")
                }
            })
        }
    } else {
        // Fallback on earlier versions
    }

My plist is set-up like so:

I find it odd because I have used other apps that use alternate app icons in iOS 11. Is there a known bug with this in iOS 11?

Note: If you're wondering why I'm using the delay, see this post


问:
How to import Dictionary text file and check for word matches?
I generate a random string of 500 characters and want to check for words.

```<code>bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio
</code>```

I import a Dictionary Words txt file and check the string to see if it contains each word. If a match is found, it's added to a list.

I read using Dictionary<> is faster than Array for a words list.

When I use that method, I can see the cpu working the foreach loop in the debugger, and my loop counter goes up, about 10,000+ times in 10 seconds, but the loop continues on forever and does not return any results.

When I use Array for Dictionary, the program works, but slower at around 500 times in 10 seconds.

Not Working

Using Dictionary<>

```<code>// Random Message
public string message = Random(500);

// Dictionary Words Reference
public Dictionary<string, string> dictionary = new Dictionary<string, string>();

// Matches Found
public static List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // Import Dictionary File
    dictionary = File
                    .ReadLines(@"C:\dictionary.txt")
                    .Select((v, i) => new { Index = i, Value = v })
                    .GroupBy(p => p.Index / 2)
                    .ToDictionary(g => g.First().Value, g => g.Last().Value);

    // If Message Contains word, add to Matches List
    foreach (KeyValuePair<string, string> entry in dictionary)
    {
        if (message.Contains(entry.Value))
        {
            matches.Add(entry.Value);
        }
    }
}
</code>```

Working

Using Array

```<code>// Random Message
public string message = Random(500);

// Dictionary Words Reference
public string[] dictionary = File.ReadAllLines(@"C:\dictionary.txt");

// Matches Found
public List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // If Message Contains word, add to Matches List
    foreach (var entry in dictionary)
    {
        if (message.Contains(entry))
        {
            matches.Add(entry);
        }
    }
}
</code>```

答:
You are misusing the dictionary,
you are basically using the dictionary as a list, so it only added some overhead to the program. not helping in any way.

It would have been useful if you had something you want to query against the dictionary not the other way around.

Also, in any case, what you want is a HashSet, not a dictionary since your key in the dictionary is not the word you are querying against but an irrelevant int.

you can read more about dictionary and HashSet here:

dictionary: https://www.dotnetperls.com/dictionary

hashset: https://www.dotnetperls.com/hashset

Body:
I generate a random string of 500 characters and want to check for words.

bliduuwfhbgphwhsyzjnlfyizbjfeeepsbpgplpbhaegyepqcjhhotovnzdtlracxrwggbcmjiglasjvmscvxwazmutqiwppzcjhijjbguxfnduuphhsoffaqwtmhmensqmyicnciaoczumjzyaaowbtwjqlpxuuqknxqvmnueknqcbvkkmildyvosczlbnlgumohosemnfkmndtiubfkminlriytmbtrzhwqmovrivxxojbpirqahatmydqgulammsnfgcvgfncqkpxhgikulsjynjrjypxwvlkvwvigvjvuydbjfizmbfbtjprxkmiqpfuyebllzezbxozkiidpplvqkqlgdlvjbfeticedwomxgawuphocisaejeonqehoipzsjgbfdatbzykkurrwwtajeajeornrhyoqadljfjyizzfluetynlrpoqojxxqmmbuaktjqghqmusjfvxkkyoewgyckpbmismwyfebaucsfueuwgio

I import a Dictionary Words txt file and check the string to see if it contains each word. If a match is found, it's added to a list.

I read using Dictionary<> is faster than Array for a words list.

When I use that method, I can see the cpu working the foreach loop in the debugger, and my loop counter goes up, about 10,000+ times in 10 seconds, but the loop continues on forever and does not return any results.

When I use Array for Dictionary, the program works, but slower at around 500 times in 10 seconds.

Not Working

Using Dictionary<>

// Random Message
public string message = Random(500);

// Dictionary Words Reference
public Dictionary<string, string> dictionary = new Dictionary<string, string>();

// Matches Found
public static List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // Import Dictionary File
    dictionary = File
                    .ReadLines(@"C:\dictionary.txt")
                    .Select((v, i) => new { Index = i, Value = v })
                    .GroupBy(p => p.Index / 2)
                    .ToDictionary(g => g.First().Value, g => g.Last().Value);

    // If Message Contains word, add to Matches List
    foreach (KeyValuePair<string, string> entry in dictionary)
    {
        if (message.Contains(entry.Value))
        {
            matches.Add(entry.Value);
        }
    }
}

Working

Using Array

// Random Message
public string message = Random(500);

// Dictionary Words Reference
public string[] dictionary = File.ReadAllLines(@"C:\dictionary.txt");

// Matches Found
public List<string> matches = new List<string>();

public MainWindow()
{
    InitializeComponent();

    // If Message Contains word, add to Matches List
    foreach (var entry in dictionary)
    {
        if (message.Contains(entry))
        {
            matches.Add(entry);
        }
    }
}


问:
How to clone a directory with different name locally with Git / SourceTree
Being a complete noob in git, I have the following question:

I am using SourceTree and BitBucket.

I'd like to do clone and in the future git pull a repo, with root directory name hello. However, on my local machine I need the root directory to have name hello_world, in order for stuff to work properly.

How can I do this?

Optionally, I can download the directory and rename it manually. If so, then how do I "connect" it to the existing git repo, using SourceTree?

答:
Clone takes a parameter for what you want, so

git clone https://url hello

This will place the repo directories under hello, instead of the default repo name.


问:
Double foreach loop with where condition in laravel blade
I have relations like this

```<code>User->hasMany->reviews
Review->belongsTo->user

Review->hasMany->ReviewAnswer
ReviewAnswer->belongsTo->Review
</code>```

Now I try to display answers for specific review. My reviewAnswer table looks like:

```<code>Id, review ID, text
</code>```

But the problem is when I do that:

```<code>@foreach($user->reviews as $data)
  @foreach($data->reviewAnswers->where('review_id', $data->id) as $answer)
    {{$answer->text}}
  @endforeach
@endforeach
</code>```

Then reviews displays okay, but I get the same answers for every review. How to repair that?

答:
Make sure to check if all the relationships are correct. In this example, I assume that your models are stored in your app folder.

First, your User model should have reviews

```<code>public function reviews() {
    return $this->hasMany("App\Review", "user_id", "id");
}
</code>```

Next, set up your Review model to have answers

```<code>public function answers() {
    return $this->hasMany("App\ReviewAnswer", "review_id", "id");
}
</code>```

Then this is how you'll get all users with their respective reviews and answers

```<code>$users = User::with("reviews.answers")->get();
</code>```

Finally, peform the loop in your view

```<code>@foreach($users as $user)
    @foreach($user->reviews as $review)
        @foreach($review->answers as $answer)
        @endforeach
    @endforeach
@endforeach
</code>```

Body:
I have relations like this

User->hasMany->reviews
Review->belongsTo->user

Review->hasMany->ReviewAnswer
ReviewAnswer->belongsTo->Review

Now I try to display answers for specific review. My reviewAnswer table looks like:

Id, review ID, text

But the problem is when I do that:

@foreach($user->reviews as $data)
  @foreach($data->reviewAnswers->where('review_id', $data->id) as $answer)
    {{$answer->text}}
  @endforeach
@endforeach

Then reviews displays okay, but I get the same answers for every review. How to repair that?

Body:
Make sure to check if all the relationships are correct. In this example, I assume that your models are stored in your app folder.

First, your User model should have reviews

public function reviews() {
    return $this->hasMany("App\Review", "user_id", "id");
}

Next, set up your Review model to have answers

public function answers() {
    return $this->hasMany("App\ReviewAnswer", "review_id", "id");
}

Then this is how you'll get all users with their respective reviews and answers

$users = User::with("reviews.answers")->get();

Finally, peform the loop in your view

@foreach($users as $user)
    @foreach($user->reviews as $review)
        @foreach($review->answers as $answer)
        @endforeach
    @endforeach
@endforeach


答:
some times num_rows return 1, even if no rows effected. Try to use

```<code>while($row = $res->fetch_object())
</code>```

or
you forget to increment $i :)

Title: Reason for: Trying to get property of non-object in php

Body:
    if(isset($_POST['uname']))
    {
        $query = "SELECT * FROM user_info";
        $res = $mysqli->query($query);
        $num = $res->num_rows;
        $i = 0;
        $cpwd = $_POST["pswd"];
        $hpwd = SHA1($cpwd);
        $tmp = $_POST["uname"];
        while($i < $num)
        {
            $row = $res->fetch_object();
            $name = $row->Username;
            $pwd = $row->Password;
            if($name == $tmp)
            {
                   //check if user is blocked
            }
            //hashed pwd
            if($pwd == $hpwd)
            {
                //success
                exit();
            }
            //request for pwd change
        else if($pwd == $cpwd)
            {
            //change
                exit();
            }
            else if($pwd != $hpwd)
            {

                //incorrect pwd
            }
        }
        $i++;
    }
    if($i == $num)
    {
        //new user
    }
}

Body:
some times num_rows return 1, even if no rows effected. Try to use

while($row = $res->fetch_object())

or
you forget to increment $i :)


答:
Specifying Git Directory

You can specify which directory you'd like to clone your repository into with the command line using:

```<code>git clone git@bitbucket.org:teamsinspace/documentation-tests.git folder-name
</code>```

Alternativley, just move the .git folder to wherever you'd like the root of your project to be.

Opening repo in SourceTree

You can also rename any Sourcetree-cloned repo, and just reopen it in Sourcetree. In order to do this:

Click on "Clone/New".

Click on the "Add Working Copy" tab.

In the Working Copy Path section, insert your local repository folder path

If it is either a Git or Hg repository, it will be stated as so as
the "Repository Type";

else it'll state that it is an invalid path.

Click "Add" to confirm adding the local repository.

Additional Links

Have a read of the documentation for cloning BitBucket into SourceTree

How can I change the path of a project in SourceTree?

Clone a repository into SourceTree Documentation

Change working copy location

Title: How to clone a directory with different name locally with Git / SourceTree

Body:
Being a complete noob in git, I have the following question:

I am using SourceTree and BitBucket.

I'd like to do clone and in the future git pull a repo, with root directory name hello. However, on my local machine I need the root directory to have name hello_world, in order for stuff to work properly.

How can I do this?

Optionally, I can download the directory and rename it manually. If so, then how do I "connect" it to the existing git repo, using SourceTree?

Body:
Specifying Git Directory

You can specify which directory you'd like to clone your repository into with the command line using:

git clone git@bitbucket.org:teamsinspace/documentation-tests.git folder-name

Alternativley, just move the .git folder to wherever you'd like the root of your project to be.

Opening repo in SourceTree

You can also rename any Sourcetree-cloned repo, and just reopen it in Sourcetree. In order to do this:

Click on "Clone/New".

Click on the "Add Working Copy" tab.

In the Working Copy Path section, insert your local repository folder path

If it is either a Git or Hg repository, it will be stated as so as
the "Repository Type";

else it'll state that it is an invalid path.

Click "Add" to confirm adding the local repository.

Additional Links

Have a read of the documentation for cloning BitBucket into SourceTree

How can I change the path of a project in SourceTree?

Clone a repository into SourceTree Documentation

Change working copy location


问:
Received 'can't find '__main__' module in '<packageName>' with python package
I'm trying to release my first Python package in the wild and I was successful in setting it up on PyPi and able to do a pip install.  When I try to run the package via the command line ($ python etlTest), I receive the following error:

/usr/bin/python: can't find '__main__' module in 'etlTest'

When I run the code directly from my IDE, it works without issue.  I am using Python 2.7 and have __init__.py scripts where required.  What do I need to do to get this working?

答:
I recently got the same issue and finaly find the solution by my self.
So as the error said, I added a file __main__.py at the same path that my __init__.py.

Inside __main__.py I added the following code :

```<code> from mypackage.mymodule import main
      main()
</code>```

main() was the main function of my code. And it's works now.

here my directory:

```<code>package
|__dirpackage
   |_mypackage.py
   |_ __init__.py
   |_ __main__.py
|_setup.py`
</code>```

Body:
I recently got the same issue and finaly find the solution by my self.
So as the error said, I added a file __main__.py at the same path that my __init__.py.

Inside __main__.py I added the following code :

 from mypackage.mymodule import main
      main()

main() was the main function of my code. And it's works now.

here my directory:

package
|__dirpackage
   |_mypackage.py
   |_ __init__.py
   |_ __main__.py
|_setup.py`


问:
Delete mongo recored by the timestamp in its id
This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its _id. I do not have any date, createdAt fields as I see that mongo uses its _id for the createdAt timestamp.

How do I delete a recored, say created 30 days ago, using this gist?

```<code>const date = new Date();
const daysToDeletion = 30;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

const db = <your-database>

db.messages.remove({_id : {$lt : deletionDate}});
</code>```

The above returns a CastError

What would work, and as Ive said, I do not have a createdAt field:

```<code>db.messages.remove({createdAt : {$lt : deletionDate}});
</code>```

答:
You need to extract the timestamp from the object _id. So you could do something like:-</p>

```<code>db.messages.find({}).forEach(function(rec) {
    var recDate = rec._id.getTimestamp();
    // Then here cast your deletionDate and recDate to preferred string format, e.g:-
    var recDateString = recDate.getMonth()+1+'-'+recDate.getDate()+'-'+recDate.getFullYear();
    var deletionDateString = deletionDate.getMonth()+1+'-'+deletionDate.getDate()+'-'+deletionDate.getFullYear();

    if (deletionDateString == recDateString ){
        db.messages.remove({_id:rec._id});
    }
}
</code>```

Body:
This question is mostly popular but with a slight twist; I need to delete few records by when it was created, using its _id. I do not have any date, createdAt fields as I see that mongo uses its _id for the createdAt timestamp.

How do I delete a recored, say created 30 days ago, using this gist?

const date = new Date();
const daysToDeletion = 30;
const deletionDate = new Date(date.setDate(date.getDate() - daysToDeletion));

const db = <your-database>

db.messages.remove({_id : {$lt : deletionDate}});

The above returns a CastError

What would work, and as Ive said, I do not have a createdAt field:

db.messages.remove({createdAt : {$lt : deletionDate}});

Body:
You need to extract the timestamp from the object _id. So you could do something like:-

db.messages.find({}).forEach(function(rec) {
    var recDate = rec._id.getTimestamp();
    // Then here cast your deletionDate and recDate to preferred string format, e.g:-
    var recDateString = recDate.getMonth()+1+'-'+recDate.getDate()+'-'+recDate.getFullYear();
    var deletionDateString = deletionDate.getMonth()+1+'-'+deletionDate.getDate()+'-'+deletionDate.getFullYear();

    if (deletionDateString == recDateString ){
        db.messages.remove({_id:rec._id});
    }
}


问:
Compare BLOB against other BLOBs in Oracle database
How to check if there is a duplicate of a blob in a database. I have documents table in the database, however I'm not sure how to check if one of them has a duplicate. I know you're supposed to use dbms_lob.compare function but after reading a few threads and articles on the topic I still do not understand this.

Documents table has document_id column and and data(blob) column. How can I possibly check if document_id = 1 has a duplicate?

答:
See other similar answers, like this one. "If dbms_lob.compare(lob1, lob2) = 0, they are identical."</p>

```<code>select *
from documents dup
join documents orig on orig.document_id = 1
    and dup.document_id <> orig.document_id
where dbms_lob.compare(orig.blob, dup.blob) = 0;
</code>```

Body:
See other similar answers, like this one. "If dbms_lob.compare(lob1, lob2) = 0, they are identical."

select *
from documents dup
join documents orig on orig.document_id = 1
    and dup.document_id <> orig.document_id
where dbms_lob.compare(orig.blob, dup.blob) = 0;


问:
Getting Error on StandardScalar Fit_Transform
```<code> import numpy as np
 import matplotlib.pyplot as plt
 import pandas as pd

 dataset = pd.read_csv('Position_Salaries.csv')
 X = dataset.iloc[:, 1:2].values
 y = dataset.iloc[:, 2].values

from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
sc_y = StandardScaler()
X = sc_X.fit_transform(X)
y = sc_y.fit_transform(y)
</code>```

Ok so here is the problem.
both X and y are single feature and have one column. As you can see X is a matrix. and y is a vector
     X = dataset.iloc[:, 1:2].values
     y = dataset.iloc[:, 2].values

Now when I run y = sc_y.fit_transform(y) I get the error that it is a 1D array. And if i change y = dataset.iloc[:, 2:3].values making it a 2D array.
But I want it to stay as 1D array since its the dependent variable and want it to stay that way. Also i solved earlier different examples where I had to rescale similar data, and it did not give me this kind of error. Not sure why it is giving me now. Moreover i am watching a video while coding and in the video everything is the same but he doesn't get any error.

答:
StandardScaler is meant to work on the features, not labels or target data.
Hence only works on 2-d Data. Please see here for documentation:

http://scikit-learn.org/stable/modules/preprocessing.html#standardization-or-mean-removal-and-variance-scaling

What you can do is, use scale function. StandardScaler is just a wrapper over this function.

```<code>from sklearn.preprocessing import scale
y = scale(y)
</code>```

Or if you want to use StandarScaler, you need to reshape your y to a 2-d array like this:

```<code>import numpy as np
y = np.array(y).reshape(-1,1)
y = sc_y.fit_transform(y)
</code>```

Body:
 import numpy as np
 import matplotlib.pyplot as plt
 import pandas as pd

 dataset = pd.read_csv('Position_Salaries.csv')
 X = dataset.iloc[:, 1:2].values
 y = dataset.iloc[:, 2].values

from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
sc_y = StandardScaler()
X = sc_X.fit_transform(X)
y = sc_y.fit_transform(y)

Ok so here is the problem.
both X and y are single feature and have one column. As you can see X is a matrix. and y is a vector
     X = dataset.iloc[:, 1:2].values
     y = dataset.iloc[:, 2].values

Now when I run y = sc_y.fit_transform(y) I get the error that it is a 1D array. And if i change y = dataset.iloc[:, 2:3].values making it a 2D array.
But I want it to stay as 1D array since its the dependent variable and want it to stay that way. Also i solved earlier different examples where I had to rescale similar data, and it did not give me this kind of error. Not sure why it is giving me now. Moreover i am watching a video while coding and in the video everything is the same but he doesn't get any error.

Body:
StandardScaler is meant to work on the features, not labels or target data.
Hence only works on 2-d Data. Please see here for documentation:

http://scikit-learn.org/stable/modules/preprocessing.html#standardization-or-mean-removal-and-variance-scaling

What you can do is, use scale function. StandardScaler is just a wrapper over this function.

from sklearn.preprocessing import scale
y = scale(y)

Or if you want to use StandarScaler, you need to reshape your y to a 2-d array like this:

import numpy as np
y = np.array(y).reshape(-1,1)
y = sc_y.fit_transform(y)


问:
iOS master detail sec
I'm working on a Contacts app which I'm developing using swift. I recently implemented sections and now the detail controller is not working properly. Whenever I click on a contact, it shows details for some other contact. I think the main problem is in prepareforsegue function but I can't figure it out. Help Pls!</p>

```<code>//
//  ContactListViewController.swift
//  TechOriginators
//
//  Created by Xcode User on 2017-10-09.
//  Copyright © 2017 Xcode User. All rights reserved.
//

import UIKit
import Foundation
class ContactListViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {

    @IBOutlet var contactsTableView : UITableView!

    var contactViewController: ContactViewController? = nil
    var  contacts : [Contact] = [] {
        didSet{
            self.contactsTableView.reloadData()
        }
    }

    //Variables to implement sections in UITableView
    var sectionLetters: [Character] = []
    var contactsDict = [Character: [String]]()
    var contactsName = [String]()

    //Search Controller
    let searchController = UISearchController(searchResultsController: nil)

    //Variable to store filtered contacts through search
    var filteredContacts = [Contact]()

    //Function to show details of a contact record
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail"{
            if let indexPath = contactsTableView.indexPathForSelectedRow{
                let object = contacts[indexPath.row]

                //let object = contactsDict[sectionLetters[indexPath.section]]![indexPath.row]
                let controller = segue.destination as! ContactViewController
                controller.detailItem = object
            }
        }
    }

    func createDict(){
        contactsName = contacts.map{$0.FirstName}
        //print(contactsName)
        sectionLetters = contactsName.map{ (firstName) -> Character in
            return firstName[firstName.startIndex]
        }

        sectionLetters.sorted()

        sectionLetters = sectionLetters.reduce([], { (list, firstName) -> [Character] in
            if !list.contains(firstName){
                return list + [firstName]
            }
            return list
        })

        for entry in contactsName{
            if contactsDict[entry[entry.startIndex]] == nil {
                contactsDict[entry[entry.startIndex]] = [String]()
            }
            contactsDict[entry[entry.startIndex]]!.append(entry)
        }

        for (letter, list) in contactsDict{
            contactsDict[letter] = list.sorted()
        }
        print(sectionLetters)
        print(contactsDict)
    }

//    //Function to load contacts
    func loadContacts()
    {
       self.contacts = getContacts()
    }

    /*private let session: URLSession = .shared
    func loadContacts()
    {
        //let url = URL(string: "http://127.0.0.1:8080/api/Contacts")!
        let url = URL(string: "http://10.16.48.237/api/Contacts")!
        let task = session.dataTask(with: url) { (data, response, error) in
            print("dataRecieved \(data)")
            print("error \(error)")
            print ("response \(response)")
            guard let data = data else { return }
            do {
                self.contacts = try parse(data)
            }
            catch {
                print("JSONParsing Error: \(error)")
            }
        }
        task.resume()  // firing the task
    }*/

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        return sectionLetters.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if self.searchController.isActive {
            return nil
        } else {
            return String(sectionLetters[section])
        }
        //return String(sectionLetters[section])
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive && searchController.searchBar.text != "" {
            return filteredContacts.count
        }
        //return self.contacts.count
        print(contactsDict[sectionLetters[section]]!.count)
        return contactsDict[sectionLetters[section]]!.count
    }

    //Function to display cells in UITableView
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell =  tableView.dequeueReusableCell(withIdentifier: "Cell" , for : indexPath)
        let contact = contacts[indexPath.row]
        let object: Contact

        if searchController.isActive && searchController.searchBar.text != ""{
            let contact = self.filteredContacts[indexPath.row]
            cell.textLabel?.text = contact.FirstName + " " + contact.LastName
        }else{
           //contact = contactsDict[sectionLetters[indexPath.section]]![indexPath.row]
            //cell.textLabel?.text = contact.FirstName + " " + contact.LastName
            cell.textLabel?.text = contactsDict[sectionLetters[indexPath.section]]![indexPath.row]
        }
        return cell
    }

    //Function to update search results when the user types in search bar
    func updateSearchResults(for searchController: UISearchController) {
        filterContentForSearchText(searchText: searchController.searchBar.text!)
    }

    func updateSearchResultsForSearchController(searchController: UISearchController){
        filterContentForSearchText(searchText: searchController.searchBar.text!)
    }

    //Function to find matches for text entered in search bar
    func filterContentForSearchText(searchText: String){
        filteredContacts = contacts.filter{p in
            var containsString = false

            if p.FirstName.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.LastName.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.Division.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.Department.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.BusinessNumber.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.HomePhone.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.CellularPhone.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.Role.lowercased().contains(searchText.lowercased()){
                containsString = true
            }
            return containsString
            }

          contactsTableView.reloadData()
        }

    //Function to sorts contacts by First Name
    func sortContacts() {
        contacts.sort() { $0.FirstName < $1.FirstName }
        contactsTableView.reloadData();
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        loadContacts()
        sortContacts()
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        self.definesPresentationContext = true
        createDict()
        contactsTableView.tableHeaderView = searchController.searchBar
        //contactsTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
        // Do any additional setup after loading the view.

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

//
//  ContactViewController.swift
//  TechOriginators
//
//  Created by Xcode User on 2017-10-09.
//  Copyright © 2017 Xcode User. All rights reserved.
//

import UIKit

class ContactViewController: UIViewController {

    //@IBOutlet weak var detailDescriptionLabel: UILabel!
    @IBOutlet weak var firstNameLabel: UILabel?
    @IBOutlet weak var lastNameLabel: UILabel?
    @IBOutlet weak var divisionLabel: UILabel?
    @IBOutlet weak var departmentLabel: UILabel?
    @IBOutlet weak var businessPhoneButton: UIButton?
    @IBOutlet weak var homePhoneButton: UIButton?
    @IBOutlet weak var cellularPhoneButton: UIButton?
    @IBOutlet weak var roleLabel: UILabel?

    /*@IBOutlet weak var firstNameLabel: UILabel?
     @IBOutlet weak var lastNameLabel: UILabel?
     @IBOutlet weak var phoneButton: UIButton?
     @IBOutlet weak var emailButton: UIButton?*/

    func configureView() {
        // Update the user interface for the detail item.
        if let detail = self.detailItem {
            self.title = detail.FirstName + " " + detail.LastName
            firstNameLabel?.text = detail.FirstName
            lastNameLabel?.text = detail.LastName
            divisionLabel?.text = detail.Division
            departmentLabel?.text = detail.Department
            businessPhoneButton?.setTitle(detail.BusinessNumber, for: .normal)
            homePhoneButton?.setTitle(detail.HomePhone, for: .normal)
            cellularPhoneButton?.setTitle(detail.CellularPhone, for: .normal)
            roleLabel?.text = detail.Role
        }

    }

    @IBAction func businessPhoneButtonPressed(sender: UIButton){
        if let bPhone = detailItem?.BusinessNumber{
            if let url = URL(string: "tel://\(bPhone)"), UIApplication.shared.canOpenURL(url){
                if #available(iOS 10, *){
                    UIApplication.shared.open(url)
                }else{
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }

    @IBAction func homePhoneButtonPressed(sender: UIButton){
        if let hPhone = detailItem?.HomePhone{
            if let url = URL(string: "tel://\(hPhone)"), UIApplication.shared.canOpenURL(url){
                if #available(iOS 10, *){
                    UIApplication.shared.open(url)
                }else{
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }

    @IBAction func cellularPhoneButtonPressed(sender: UIButton){
        if let cPhone = detailItem?.CellularPhone{
            /*if let url = NSURL(string: "tel://\(phone)"){
             UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
             }*/
            if let url = URL(string: "tel://\(cPhone)"), UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url)
                } else {
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }

    /*@IBAction func emailButtonPressed(sender: UIButton){
     if let email = detailItem?.email{
     if let url = URL(string:"mailto:\(email)"){
     UIApplication.shared.open(url as URL)
     }
     }
     }*/

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a      nib.
        configureView()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    var detailItem: Contact? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
</code>```

答:
I suggest using the same data structure for all your table operations to be consistent. Try populating your dictionary as:

```<code>var contactsDict = [Character: [Contact]]()
</code>```

That way, you can always use the section to find the right array and the row to find the right offset in the array.

Separating the names from the contacts in the table's data is inviting them to get out of synch.

Title: iOS master detail sec

Body:
I'm working on a Contacts app which I'm developing using swift. I recently implemented sections and now the detail controller is not working properly. Whenever I click on a contact, it shows details for some other contact. I think the main problem is in prepareforsegue function but I can't figure it out. Help Pls!

//
//  ContactListViewController.swift
//  TechOriginators
//
//  Created by Xcode User on 2017-10-09.
//  Copyright © 2017 Xcode User. All rights reserved.
//

import UIKit
import Foundation
class ContactListViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {

    @IBOutlet var contactsTableView : UITableView!

    var contactViewController: ContactViewController? = nil
    var  contacts : [Contact] = [] {
        didSet{
            self.contactsTableView.reloadData()
        }
    }

    //Variables to implement sections in UITableView
    var sectionLetters: [Character] = []
    var contactsDict = [Character: [String]]()
    var contactsName = [String]()

    //Search Controller
    let searchController = UISearchController(searchResultsController: nil)

    //Variable to store filtered contacts through search
    var filteredContacts = [Contact]()

    //Function to show details of a contact record
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetail"{
            if let indexPath = contactsTableView.indexPathForSelectedRow{
                let object = contacts[indexPath.row]

                //let object = contactsDict[sectionLetters[indexPath.section]]![indexPath.row]
                let controller = segue.destination as! ContactViewController
                controller.detailItem = object
            }
        }
    }

    func createDict(){
        contactsName = contacts.map{$0.FirstName}
        //print(contactsName)
        sectionLetters = contactsName.map{ (firstName) -> Character in
            return firstName[firstName.startIndex]
        }

        sectionLetters.sorted()

        sectionLetters = sectionLetters.reduce([], { (list, firstName) -> [Character] in
            if !list.contains(firstName){
                return list + [firstName]
            }
            return list
        })

        for entry in contactsName{
            if contactsDict[entry[entry.startIndex]] == nil {
                contactsDict[entry[entry.startIndex]] = [String]()
            }
            contactsDict[entry[entry.startIndex]]!.append(entry)
        }

        for (letter, list) in contactsDict{
            contactsDict[letter] = list.sorted()
        }
        print(sectionLetters)
        print(contactsDict)
    }

//    //Function to load contacts
    func loadContacts()
    {
       self.contacts = getContacts()
    }

    /*private let session: URLSession = .shared
    func loadContacts()
    {
        //let url = URL(string: "http://127.0.0.1:8080/api/Contacts")!
        let url = URL(string: "http://10.16.48.237/api/Contacts")!
        let task = session.dataTask(with: url) { (data, response, error) in
            print("dataRecieved \(data)")
            print("error \(error)")
            print ("response \(response)")
            guard let data = data else { return }
            do {
                self.contacts = try parse(data)
            }
            catch {
                print("JSONParsing Error: \(error)")
            }
        }
        task.resume()  // firing the task
    }*/

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        return sectionLetters.count
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if self.searchController.isActive {
            return nil
        } else {
            return String(sectionLetters[section])
        }
        //return String(sectionLetters[section])
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchController.isActive && searchController.searchBar.text != "" {
            return filteredContacts.count
        }
        //return self.contacts.count
        print(contactsDict[sectionLetters[section]]!.count)
        return contactsDict[sectionLetters[section]]!.count
    }

    //Function to display cells in UITableView
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell =  tableView.dequeueReusableCell(withIdentifier: "Cell" , for : indexPath)
        let contact = contacts[indexPath.row]
        let object: Contact

        if searchController.isActive && searchController.searchBar.text != ""{
            let contact = self.filteredContacts[indexPath.row]
            cell.textLabel?.text = contact.FirstName + " " + contact.LastName
        }else{
           //contact = contactsDict[sectionLetters[indexPath.section]]![indexPath.row]
            //cell.textLabel?.text = contact.FirstName + " " + contact.LastName
            cell.textLabel?.text = contactsDict[sectionLetters[indexPath.section]]![indexPath.row]
        }
        return cell
    }

    //Function to update search results when the user types in search bar
    func updateSearchResults(for searchController: UISearchController) {
        filterContentForSearchText(searchText: searchController.searchBar.text!)
    }

    func updateSearchResultsForSearchController(searchController: UISearchController){
        filterContentForSearchText(searchText: searchController.searchBar.text!)
    }

    //Function to find matches for text entered in search bar
    func filterContentForSearchText(searchText: String){
        filteredContacts = contacts.filter{p in
            var containsString = false

            if p.FirstName.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.LastName.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.Division.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.Department.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.BusinessNumber.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.HomePhone.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.CellularPhone.lowercased().contains(searchText.lowercased()){
                containsString = true
            }else if p.Role.lowercased().contains(searchText.lowercased()){
                containsString = true
            }
            return containsString
            }

          contactsTableView.reloadData()
        }

    //Function to sorts contacts by First Name
    func sortContacts() {
        contacts.sort() { $0.FirstName < $1.FirstName }
        contactsTableView.reloadData();
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        loadContacts()
        sortContacts()
        searchController.searchResultsUpdater = self
        searchController.dimsBackgroundDuringPresentation = false
        self.definesPresentationContext = true
        createDict()
        contactsTableView.tableHeaderView = searchController.searchBar
        //contactsTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)
        // Do any additional setup after loading the view.

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

//
//  ContactViewController.swift
//  TechOriginators
//
//  Created by Xcode User on 2017-10-09.
//  Copyright © 2017 Xcode User. All rights reserved.
//

import UIKit

class ContactViewController: UIViewController {

    //@IBOutlet weak var detailDescriptionLabel: UILabel!
    @IBOutlet weak var firstNameLabel: UILabel?
    @IBOutlet weak var lastNameLabel: UILabel?
    @IBOutlet weak var divisionLabel: UILabel?
    @IBOutlet weak var departmentLabel: UILabel?
    @IBOutlet weak var businessPhoneButton: UIButton?
    @IBOutlet weak var homePhoneButton: UIButton?
    @IBOutlet weak var cellularPhoneButton: UIButton?
    @IBOutlet weak var roleLabel: UILabel?

    /*@IBOutlet weak var firstNameLabel: UILabel?
     @IBOutlet weak var lastNameLabel: UILabel?
     @IBOutlet weak var phoneButton: UIButton?
     @IBOutlet weak var emailButton: UIButton?*/

    func configureView() {
        // Update the user interface for the detail item.
        if let detail = self.detailItem {
            self.title = detail.FirstName + " " + detail.LastName
            firstNameLabel?.text = detail.FirstName
            lastNameLabel?.text = detail.LastName
            divisionLabel?.text = detail.Division
            departmentLabel?.text = detail.Department
            businessPhoneButton?.setTitle(detail.BusinessNumber, for: .normal)
            homePhoneButton?.setTitle(detail.HomePhone, for: .normal)
            cellularPhoneButton?.setTitle(detail.CellularPhone, for: .normal)
            roleLabel?.text = detail.Role
        }

    }

    @IBAction func businessPhoneButtonPressed(sender: UIButton){
        if let bPhone = detailItem?.BusinessNumber{
            if let url = URL(string: "tel://\(bPhone)"), UIApplication.shared.canOpenURL(url){
                if #available(iOS 10, *){
                    UIApplication.shared.open(url)
                }else{
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }

    @IBAction func homePhoneButtonPressed(sender: UIButton){
        if let hPhone = detailItem?.HomePhone{
            if let url = URL(string: "tel://\(hPhone)"), UIApplication.shared.canOpenURL(url){
                if #available(iOS 10, *){
                    UIApplication.shared.open(url)
                }else{
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }

    @IBAction func cellularPhoneButtonPressed(sender: UIButton){
        if let cPhone = detailItem?.CellularPhone{
            /*if let url = NSURL(string: "tel://\(phone)"){
             UIApplication.shared.open(url as URL, options: [:], completionHandler: nil)
             }*/
            if let url = URL(string: "tel://\(cPhone)"), UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url)
                } else {
                    UIApplication.shared.openURL(url)
                }
            }
        }
    }

    /*@IBAction func emailButtonPressed(sender: UIButton){
     if let email = detailItem?.email{
     if let url = URL(string:"mailto:\(email)"){
     UIApplication.shared.open(url as URL)
     }
     }
     }*/

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a      nib.
        configureView()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    var detailItem: Contact? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

Body:
I suggest using the same data structure for all your table operations to be consistent. Try populating your dictionary as:

var contactsDict = [Character: [Contact]]()

That way, you can always use the section to find the right array and the row to find the right offset in the array.

Separating the names from the contacts in the table's data is inviting them to get out of synch.


问:
Ajax with CakePHP and Javascript
i' m pretty new in using CakePHP and Javascript, i read many articles about request handling in cake, but i'm still confused, what i'm try to do is to send ajax request from my Javascript code to cakePHP and obtain some data in json format, i tried many ways to do this, but all the time I get simply html of page, instead of data i want to get, I have generated by default app controller class, as a url in Javascript request i use "http://localhost/pages/main" which is url of my view page where i have input controls, i wonder where in controller class should i put code responsible for handling request, and how to implement sending json response, thanks in advance

php code AppController class

```<code>public function beforeRender(Event $event)
{
    // Note: These defaults are just to get started quickly with development
    // and should not be used in production. You should instead set "_serialize"
    // in each action as required.
    if (!array_key_exists('_serialize', $this->viewVars) &&
        in_array($this->response->type(), ['application/json', 'application/xml'])
    ) {
        $this->set('_serialize', true);

        if ($this->request->is('ajax')) {
            $data = ['data1', 'data2'];
            $this->set(compact('data'));
            $this->set('_serialize', ['data']);
        }
    }

    **javascript:**

    var xhr = new XMLHttpRequest();
    var url = 'localhost/pages/main.json';
    var data = {
        unit: 'someUnit',
        name: this.name
    };

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            console.log(xhr.response);
        }
    };
    xhr.open('POST', url);
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send(data);
</code>```

答:
It is easier if you use routing extension

Router::extensions(['json']);

then in your controller you can pass the serialize data like this

```<code>$data = $this->Model->find();
$this->set(compact('data');
$this->set('_serialize', ['data']);
</code>```

In your ajax request, just add .json extension to the url

Title: Ajax with CakePHP and Javascript

Body:
i' m pretty new in using CakePHP and Javascript, i read many articles about request handling in cake, but i'm still confused, what i'm try to do is to send ajax request from my Javascript code to cakePHP and obtain some data in json format, i tried many ways to do this, but all the time I get simply html of page, instead of data i want to get, I have generated by default app controller class, as a url in Javascript request i use "http://localhost/pages/main" which is url of my view page where i have input controls, i wonder where in controller class should i put code responsible for handling request, and how to implement sending json response, thanks in advance

php code AppController class

public function beforeRender(Event $event)
{
    // Note: These defaults are just to get started quickly with development
    // and should not be used in production. You should instead set "_serialize"
    // in each action as required.
    if (!array_key_exists('_serialize', $this->viewVars) &&
        in_array($this->response->type(), ['application/json', 'application/xml'])
    ) {
        $this->set('_serialize', true);

        if ($this->request->is('ajax')) {
            $data = ['data1', 'data2'];
            $this->set(compact('data'));
            $this->set('_serialize', ['data']);
        }
    }

    **javascript:**

    var xhr = new XMLHttpRequest();
    var url = 'localhost/pages/main.json';
    var data = {
        unit: 'someUnit',
        name: this.name
    };

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            console.log(xhr.response);
        }
    };
    xhr.open('POST', url);
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send(data);

Body:
It is easier if you use routing extension

Router::extensions(['json']);

then in your controller you can pass the serialize data like this

$data = $this->Model->find();
$this->set(compact('data');
$this->set('_serialize', ['data']);

In your ajax request, just add .json extension to the url


问:
WCF sessions with a wsHttpBinding and without windows security
I need to create a WCF service that is hosted in IIS, uses http transport and hold state in the server’s memory. While I’m aware that stateful services aren't a good idea, this last constrain is necessary to make the service work with a legacy client.

My first thought was to asp.net’s session to store the values. I activated the asp.net compatibility mode in my service, which gave me access to the HttpContext, but values that were placed in the session object were not being persisted in memory. I assume this was because the http module that handles session state was not correctly configured, but when googling for answer I came across, WCF sessions and thought it might be a better idea to use them.

However, WCF sessions seem what under-document and place a strange set of prerequises on a service, and I haven’t been able to find a configuration that suits my needs: must be hosted in IIS, must use http or https transport and can’t reply on windows authentication because the client and server will not be part of the same domain. I’m trying to get this going using the wsHttpBinding, I had heard WCF sessions required either security or reliable message, but:
- Using the standard binding and when the servers are not part of the same domain it fails with a “SecurityNegotiationException The caller was not authenticated by the service” exception. This is fairly logical as it was using windows security.

If I disable security complete it fails with a “Contract requires Session, but Binding 'WSHttpBinding' doesn't support it or isn't configured properly to support it.”

If while keeping security disabled I enable reliable message I get the exception “Binding validation failed because the WSHttpBinding does not support reliable sessions over transport security (HTTPS). The channel factory or service host could not be opened. Use message security for secure reliable messaging over HTTP.”

I’ve tried enabling transport level security but this doesn’t seem to make any difference to the error generated

Is there any configuration that might work for me? Or should I just go back to the plan of using asp.net sessions?

答:
IMO this is what happens when you're using a technology with a poor abstraction over HTTP like WCF. The fact that WCF web services could in theory be hosted without HTTP (i.e. over NET TCP, MSMQ, etc) just makes it hard to use built-in features of HTTP without entering in configuration hell and start a game of "guess the correct configuration by trial and error" where you try every possible configuration permutation until you've found the correct one that works!

Ultimately if you couldn't use WCF and had to implement the web service from scratch you would simply set a cookie when the client successfully authenticated. Then with every client request  just grab the session information referenced by that cookie.

One possible solution if you had to use WCF is to take session management in your own hands (It's what I do when I'm unhappy with the effort required to get something to work) and have an explicit 'Session' property on all your web services that require a session/authentication (usually a guid generated on Authentication). So for each subsequent request you use the guid to rehydrate the session information associated with that client.

If you're interested in trying out different web service frameworks I maintain an Open Source Web Services Framework that lets you build configuration-free, DRY, testable web services where (without any configuration required) each web service you create is automatically accessible over REST XML, JSON, JSV, SOAP 1.1, SOAP 1.2 endpoints. Effectively it allows you to access your same web service via a HTTP GET url for REST-ful clients and easy debugging as well as SOAP endpoints (a popular choice still mandated by some enterprises). The Hello World tutorial should give you a good overview on some of its features and how it works.


问:
Assign two elements and form a list in Python
Within my project, I have to define a function, in which I get two lists below and one hour, extracted through an earlier file (these are completely arbitrary, but the sequence of the data is the same). The "return" command must return a list with the operator's name, followed by the customer's name.

```<code>[('Ricardo Tavares', 'portuguese', '(mobiles; printers)', '14:15', 42), ('Carl Thompson', 'english', '(laptops)', '14:17', 54), ('Nuria Castro', 'spanish', '(cameras; hifi)', '14:24', 37), ('Giovanni Olivetti', 'italian', '(laptops; bimby; hifi)', '14:52', 21), ('Georg Muller', 'deutsch', '(cameras)', '15:05', 31)]
</code>```

```<code>[('Henry Miller', 'english', 'laptops', 'premium', 3), ('Francois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
</code>```

The objective is to assign operators (first list) to the customers (second list). Assignment must be done according to the field of knowledge (eg. mobiles, printers) and the operator's language (eg. portuguese, english) as well as the customer's help topic (eg. laptops, cameras) and the language they both speak (eg. english, spanish). In addition, it is necessary to keep in mind that customers who are "premium" must be served first than the other "fremium". The assignment of the operators to the customers must be done according to the number of minutes they have worked (the last tuple value of each list element) as well as the last time they answered a customer (eg. 14:15).

With all these conditions, in addition to getting a bit confusing, I can not quite figure out which is the most efficient way to solve this code without being too defensive when programming!

This is what I have right now, but the list stays blank.

```<code>def assign_tasks(operators, requests, current_time):

operators = sorted(operators, key=itemgetter(3), reverse=False)
requests = sorted(requests, key=itemgetter(3), reverse=True)
tasks = []

langr = 0 #Variable that gets the language of the request's file (customer's language)
lango = 0 #Variable that gets the language of the operator's file (operator's language)
for i in range(0, len(requests)):
    langr = requests[i][1]                                   #What language does the customer speaks?
    for k in range(0, len(operators)):
        lango = operators[k][1]                              #What language does the operator speaks?
        if langr == lango:                                   #Do they speak the same language?
            for j in range(0, len(operators[k][2])):
                if operators[k][2][j] == requests[i][2]:     # The operator knows how to solve the client's problem? If yes, then group them together.
                    tasks.append((current_time, operators[k][0], requests[i][0]))
                    operators.remove(operators[k])
                    requests.remove(requests[i])
print(tasks)
return tasks
</code>```

```<code>operators = [('Leticia Ferreira', 'portuguese', '(laptops)', '11:03', 15), ('Atilio Moreno', 'portuguese', '(laptops)', '10:58', 104), ('Ruth Falk', 'german', '(phones; hifi)', '11:06', 150), ('Marianne Thibault', 'french', '(phones)', '11:09', 230), ('Mariana Santana', 'portuguese', '(phones)', '11:11', 230), ('Beate Adenauer', 'german', '(hifi; phones)', '11:12', 140), ('Romana Cerveny', 'czech', '(phones)', '11:13', 213), ('Zdenka Sedlak', 'czech', '(phones)', '11:13', 56)]
requests = [('Christina Holtzer', 'german', 'hifi', 'fremium', 7), ('Andrej Hlavac', 'czech', 'phones', 'fremium', 9), ('Dulce Chaves', 'portuguese', 'laptops', 'fremium', 15), ('Otavio Santiago', 'portuguese', 'laptops', 'fremium', 15), ('Dina Silveira', 'portuguese', 'phones', 'fremium', 9), ('Rafael Kaluza', 'slovenian', 'laptops', 'fremium', 13), ('Sabina Rosario', 'portuguese', 'laptops', 'premium', 10), ('Nuno Rodrigues', 'portuguese', 'laptops', 'fremium', 12), ('Feliciano Santos', 'portuguese', 'phones', 'fremium', 12)]

current_time = "14:55 06:11:2017"

assign_tasks(operators, requests, current_time)
</code>```

Is there something wrong?

答:
I won't show any code in this answer, but a simple algorithmic approach that I would take. The rest will be up to you.

The approach I would take is as follows:

Loop through the customers

For each customer check what language the customer speaks.

Loop through the operators and check if each speaks the same language as the customer.

If a customer does, check if he/she covers the problem that the customer needs help with.

If he/she does, assign the operator to the customer. (I do not know how you would represent that, so I'll leave it like that.

Repeat the process above for the next customer and until all customers are taken care of.

This algorithm that I just came up with is by no means perfect, but it should get the job done if this is what you are looking for.

The fun part is now implementing that (at least to me).

Hope this helps.

Body:
Within my project, I have to define a function, in which I get two lists below and one hour, extracted through an earlier file (these are completely arbitrary, but the sequence of the data is the same). The "return" command must return a list with the operator's name, followed by the customer's name.

[('Ricardo Tavares', 'portuguese', '(mobiles; printers)', '14:15', 42), ('Carl Thompson', 'english', '(laptops)', '14:17', 54), ('Nuria Castro', 'spanish', '(cameras; hifi)', '14:24', 37), ('Giovanni Olivetti', 'italian', '(laptops; bimby; hifi)', '14:52', 21), ('Georg Muller', 'deutsch', '(cameras)', '15:05', 31)]

[('Henry Miller', 'english', 'laptops', 'premium', 3), ('Francois Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

The objective is to assign operators (first list) to the customers (second list). Assignment must be done according to the field of knowledge (eg. mobiles, printers) and the operator's language (eg. portuguese, english) as well as the customer's help topic (eg. laptops, cameras) and the language they both speak (eg. english, spanish). In addition, it is necessary to keep in mind that customers who are "premium" must be served first than the other "fremium". The assignment of the operators to the customers must be done according to the number of minutes they have worked (the last tuple value of each list element) as well as the last time they answered a customer (eg. 14:15).

With all these conditions, in addition to getting a bit confusing, I can not quite figure out which is the most efficient way to solve this code without being too defensive when programming!

This is what I have right now, but the list stays blank.

def assign_tasks(operators, requests, current_time):

operators = sorted(operators, key=itemgetter(3), reverse=False)
requests = sorted(requests, key=itemgetter(3), reverse=True)
tasks = []

langr = 0 #Variable that gets the language of the request's file (customer's language)
lango = 0 #Variable that gets the language of the operator's file (operator's language)
for i in range(0, len(requests)):
    langr = requests[i][1]                                   #What language does the customer speaks?
    for k in range(0, len(operators)):
        lango = operators[k][1]                              #What language does the operator speaks?
        if langr == lango:                                   #Do they speak the same language?
            for j in range(0, len(operators[k][2])):
                if operators[k][2][j] == requests[i][2]:     # The operator knows how to solve the client's problem? If yes, then group them together.
                    tasks.append((current_time, operators[k][0], requests[i][0]))
                    operators.remove(operators[k])
                    requests.remove(requests[i])
print(tasks)
return tasks

operators = [('Leticia Ferreira', 'portuguese', '(laptops)', '11:03', 15), ('Atilio Moreno', 'portuguese', '(laptops)', '10:58', 104), ('Ruth Falk', 'german', '(phones; hifi)', '11:06', 150), ('Marianne Thibault', 'french', '(phones)', '11:09', 230), ('Mariana Santana', 'portuguese', '(phones)', '11:11', 230), ('Beate Adenauer', 'german', '(hifi; phones)', '11:12', 140), ('Romana Cerveny', 'czech', '(phones)', '11:13', 213), ('Zdenka Sedlak', 'czech', '(phones)', '11:13', 56)]
requests = [('Christina Holtzer', 'german', 'hifi', 'fremium', 7), ('Andrej Hlavac', 'czech', 'phones', 'fremium', 9), ('Dulce Chaves', 'portuguese', 'laptops', 'fremium', 15), ('Otavio Santiago', 'portuguese', 'laptops', 'fremium', 15), ('Dina Silveira', 'portuguese', 'phones', 'fremium', 9), ('Rafael Kaluza', 'slovenian', 'laptops', 'fremium', 13), ('Sabina Rosario', 'portuguese', 'laptops', 'premium', 10), ('Nuno Rodrigues', 'portuguese', 'laptops', 'fremium', 12), ('Feliciano Santos', 'portuguese', 'phones', 'fremium', 12)]

current_time = "14:55 06:11:2017"

assign_tasks(operators, requests, current_time)

Is there something wrong?


问:
Datatables export to Excel and format a numeric column as currency
I'm trying to export numeric data to Excel. The numeric formatting is as follows:

Thousands grouping separator: "."

Decimal point indicator: ","

Number of decimal points to show: "0"

Prefix: "$"

And the header and footer texts are formatted as bold.

This is the table:

```<code><table id="idtablainforme_ventaporfamilia" class="table table-striped table-striped table-bordered nowrap dataTable">
    <thead>
        <tr>
            <th>
                <b>FAMILIA</b>
            </th>
            <th>
                <b>VENTA</b>
            </th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th><b>TOTAL</b></th>
            <th><b>$12.925.150</b></th>
        </tr>
    </tfoot>
    <tbody>
        <tr><td>CHEQUERA MUJER</td><td>$5.231.760</td></tr>
        <tr><td>CARTERA</td><td>$3.487.630</td></tr>
        <tr><td>BILLETERA MUJER</td><td>$2.155.120</td></tr>
        <tr><td>NECESER</td><td>$21.980</td></tr>
        <tr><td>COSMETIQUERA</td><td>$10.990</td></tr>
        <tr><td>SET DE VIAJE</td><td>$10.990</td></tr>
    </tbody>
</table>
</code>```

This is my try:

```<code><script>
    $('#idtablainforme_ventaporfamilia').DataTable({
        destroy: true,
        "searching": false,
        "paging": false,
        "ordering": false,
        "info": false,
        "autowidth": false,
        columns: [
           { data: "1", render: $.fn.dataTable.render.text() },
           { data: "2", render: $.fn.dataTable.render.number('.', ',', 0, '$') }
        ],
        footerCallback: function (tfoot, data, start, end, display) {
            var $th = $(tfoot).find('th').eq(1);
            $th.text($.fn.dataTable.render.number('.', ',', 0, '$').display($th.text()))
        },
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                footer: true,
                title: 'INFORME DE VENTAS POR FAMILIA',
                text: '<i class="fa fa-file-excel-o"></i>',
                titleAttr: 'Exporta a EXCEL',
            }
        ]
    });
</script>
</code>```

But it doesn't convert the numeric data, and the header and footer texts are not formatted as bold. They are exported in Excel as string, except for the values 21.98 $, 10.99 $ and 10.99 $ (although they should be $21.980, $10.990 and $10.990) as follows:

```<code>FAMILIA         VENTA
CHEQUERA MUJER  $5.494.310
CARTERA         $5.231.760
BILLETERA MUJER $2.155.120
NECESER         21.98  $
COSMETIQUERA    10.99  $
SET DE VIAJE    10.99  $
TOTAL           $12.925.150
</code>```

答:
The currency symbol ($) appearing to the right, is a known bug, which the creator of DataTables is aware of.

As for the other things, I created a demo

And based on that:

You are pre-populating the amount with the dollar sign (at least, according to your posted HTML code); don't do that! just provide the numerical value

Header and footer are indeed bold, both in display (right side of the screen shot below) and once exported to excel; check to ensure that the CSS isn't being overridden.

That said, check out for other formatting needs, that DataTables provides.

Edit:

I do not know why my posted JSFiddle link does not include other libs... but for your reference, the following screenshot shows exactly the JS/CSS libs that were included in my re-build of your case:

Body:
I'm trying to export numeric data to Excel. The numeric formatting is as follows:

Thousands grouping separator: "."

Decimal point indicator: ","

Number of decimal points to show: "0"

Prefix: "$"

And the header and footer texts are formatted as bold.

This is the table:

                FAMILIA

                VENTA

            TOTAL
            $12.925.150

CHEQUERA MUJER	$5.231.760

CARTERA	$3.487.630

BILLETERA MUJER	$2.155.120

NECESER	$21.980

COSMETIQUERA	$10.990

SET DE VIAJE	$10.990

This is my try:

But it doesn't convert the numeric data, and the header and footer texts are not formatted as bold. They are exported in Excel as string, except for the values 21.98 $, 10.99 $ and 10.99 $ (although they should be $21.980, $10.990 and $10.990) as follows:

FAMILIA         VENTA
CHEQUERA MUJER  $5.494.310
CARTERA         $5.231.760
BILLETERA MUJER $2.155.120
NECESER         21.98  $
COSMETIQUERA    10.99  $
SET DE VIAJE    10.99  $
TOTAL           $12.925.150