答:
If you set the program up to build as a GUI program you can then attempt to attach to the console using AttachConsole(). You you attach OK then you were started from a console and you can proceed to redirect your standard handles to the newly attached console.

In this way you can start up and see if you are being started from a console that you can attach to and if so become a console program. If you cant attach you can show a GUI.

I've had some success with this, the main problem I have is redisplaying the command window's prompt when my program exits (which is how normal console programs operate), but I expect you could do something clever (read the console buffer on start up and find the prompt to redisplay when you exit?) if you really wanted to ...

Title: Win32 console problem

Body:
is it possible to create a program that works as console application if started from the console and works as windows program (with GUI) when started otherwise?

If it is possible - how can I do that?

regards
Tobias


来源: stackexchange

问:
DNN SQL installation error
I'm having a syntax issue with the SQL queries to create the tables for a DNN module. I've double checked my code and can't seem to find the issue. However, the DNN installation keeps saying there is an incorrect syntax near 'FK_bank_statement_day_name_table'. I've cross-checked it thoroughly but can't seem to figure </p>

```<code>ALTER TABLE {databaseOwner}[{objectQualifier}bank_statement_day]
WITH CHECK ADD  CONSTRAINT [FK_bank_statement_day_name_table] FOREIGN
KEY([file_name])
REFERENCES {databaseOwner}[{objectQualifier}name_table] ([file_name])

ALTER TABLE {databaseOwner}[{objectQualifier}bank_statement_day]
CHECK CONSTRAINT [FK_bank_statement_day_name_table]
</code>```

答:
You likely are running into problems with DNN because you're missing the GO statements. Try the following:</p>

```<code>ALTER TABLE {databaseOwner}[{objectQualifier}bank_statement_day]
WITH CHECK ADD  CONSTRAINT [FK_bank_statement_day_name_table] FOREIGN
KEY([file_name])
REFERENCES {databaseOwner}[{objectQualifier}name_table] ([file_name])
GO

ALTER TABLE {databaseOwner}[{objectQualifier}bank_statement_day]
CHECK CONSTRAINT [FK_bank_statement_day_name_table]
GO
</code>```

ContentLicense: CC BY-SA 3.0

Title: DNN SQL installation error

Body:
I'm having a syntax issue with the SQL queries to create the tables for a DNN module. I've double checked my code and can't seem to find the issue. However, the DNN installation keeps saying there is an incorrect syntax near 'FK_bank_statement_day_name_table'. I've cross-checked it thoroughly but can't seem to figure

ALTER TABLE {databaseOwner}[{objectQualifier}bank_statement_day]
WITH CHECK ADD  CONSTRAINT [FK_bank_statement_day_name_table] FOREIGN
KEY([file_name])
REFERENCES {databaseOwner}[{objectQualifier}name_table] ([file_name])

ALTER TABLE {databaseOwner}[{objectQualifier}bank_statement_day]
CHECK CONSTRAINT [FK_bank_statement_day_name_table]

Body:
You likely are running into problems with DNN because you're missing the GO statements. Try the following:

ALTER TABLE {databaseOwner}[{objectQualifier}bank_statement_day]
WITH CHECK ADD  CONSTRAINT [FK_bank_statement_day_name_table] FOREIGN
KEY([file_name])
REFERENCES {databaseOwner}[{objectQualifier}name_table] ([file_name])
GO

ALTER TABLE {databaseOwner}[{objectQualifier}bank_statement_day]
CHECK CONSTRAINT [FK_bank_statement_day_name_table]
GO


问:
Missing closing paranthes MySQL workbench, Query syntax
this is my code:

```<code>SELECT Lname
    ,Fname
FROM EMPLOYEE
WHERE NOT EXISTS (
        SELECT *
        FROM WORKS_ON B
        WHERE (
                B.Pno IN (
                    SELECT Pnumber
                    FROM PROJECT
                    WHERE Dnum = 5
                        AND NOT EXISTS (
                            SELECT *
                            FROM WORKS_ON C
                            WHERE C.Essn = Ssn
                                AND C.Pno = B.Pno
                            )
                    )
                );
</code>```

It is almost true but it doesn't work error message : Missing closing parenthesis

答:
Always remember opening and closing of brackets () it is better when you start writing query first open and close brackets and then write query

In your code count of open brackets not equal to close brackets

Body:
this is my code:

SELECT Lname
    ,Fname
FROM EMPLOYEE
WHERE NOT EXISTS (
        SELECT *
        FROM WORKS_ON B
        WHERE (
                B.Pno IN (
                    SELECT Pnumber
                    FROM PROJECT
                    WHERE Dnum = 5
                        AND NOT EXISTS (
                            SELECT *
                            FROM WORKS_ON C
                            WHERE C.Essn = Ssn
                                AND C.Pno = B.Pno
                            )
                    )
                );

It is almost true but it doesn't work error message : Missing closing parenthesis


问:
FFServer over https
we're currently providing video/audo feeds via ffserver over "http" i.e. http://127.0.0.1:8000/folder/feed1.mjpg

however, now we need to add the feeds to secure pages over "https" so we need to do something like this https://127.0.0.1:8000/folder/feed1.mjpg

I have searched the web and docs, but didn't find anything in reference to ffserver and https.

Is this possible? if so can anyone point me in the direction of achieving this?

答:
I had the same problem - embedding the ffserver's non-encrypted WEBM stream into HTTPS web site was causing the browser's "mixed content" warning.
I solved the problem by using Apache with mod_proxy.
I basically followed this tutorial: https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension

In short, I made only these 3 steps:

enable the proxy modules

```<code>a2enmod proxy
a2enmod proxy_http
</code>```

create a new virtual host in Apache listening on port 443 with the following directives:

```<code><VirtualHost *:443>
  ServerName livestream.example.com
  ProxyPreserveHost On
  ProxyPass / http://0.0.0.0:8090/
  ProxyPassReverse / http://0.0.0.0:8090/

  SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
  SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
  Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</code>```

set up DNS record for livestream.example.com

My ffserver is running on the same server as Apache, with HTTP port 8090, but I'm sure the proxy can be directed to any other IP address.

That way I was able to embed the WEBM video stream as https://livestream.example.com/somevideo.webm and get rid of the mixed content warning.

(tested on Ubuntu 16.04, Apache 2.4.18, ffserver 2.8.11)

Title: FFServer over https

Body:
I had the same problem - embedding the ffserver's non-encrypted WEBM stream into HTTPS web site was causing the browser's "mixed content" warning.
I solved the problem by using Apache with mod_proxy.
I basically followed this tutorial: https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension

In short, I made only these 3 steps:

enable the proxy modules

a2enmod proxy
a2enmod proxy_http

create a new virtual host in Apache listening on port 443 with the following directives:

<VirtualHost *:443>
  ServerName livestream.example.com
  ProxyPreserveHost On
  ProxyPass / http://0.0.0.0:8090/
  ProxyPassReverse / http://0.0.0.0:8090/

  SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
  SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
  Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>

set up DNS record for livestream.example.com

My ffserver is running on the same server as Apache, with HTTP port 8090, but I'm sure the proxy can be directed to any other IP address.

That way I was able to embed the WEBM video stream as https://livestream.example.com/somevideo.webm and get rid of the mixed content warning.

(tested on Ubuntu 16.04, Apache 2.4.18, ffserver 2.8.11)

ContentLicense: CC BY-SA 4.0


问:
Cannot return an HTML view in Spring MVC
It's my first attempt at using Spring and I ran into a problem. I cannot seem to return a simple HTML file as a view inside a controller. I'm trying to return the index.html file (it just has some text and a button), because it is displayed correctly when going to localhost:8080/.

The project was generated using IntelliJ, I figure I'd mention this since it handled most of the configuration.

Here's the file structure:

```<code>app:
 | src
    | main
       | java
          | com.my.testapp
              | Main.java
              | controllers
                  | TestController.java
       | resources
          | static
              | index.html
</code>```

Here are my files:

Main.java

```<code>@SpringBootApplication
public class Main
{
    public static void main(String[] args)
    {
        SpringApplication.run(Main.class, args);
    }
}
</code>```

TestController.java (the first controller actually works)

```<code>@RequestMapping("/test")
@Controller
public class TestController
{
    @RequestMapping(method = RequestMethod.GET, value = "/testget")
    public @ResponseBody ArrayList<Test> foo()
    {
        ArrayList<Test> tests = new ArrayList<>();

        tests.add(new Test("id1", "pass1"));
        tests.add(new Test("id2", "pass2"));

        return tests;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/someview")
    public String showView()
    {
        return "index";
    }
}
</code>```

And finally, the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.my</groupId>
    <artifactId>testapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springtest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I was previously using @RestController annotation and the controller would simply return the string index, but now I get a 404 page (Whitelabel Error Page). I know this is a common issue, but I haven't been able to solve it using other people's solution.

EDIT: Ok, I managed to fix part of it by removing the line @RequestMapping("/test"), but I now need to pass the view as "index.html" instead of simply "index". Is there a way to skip the .html? Currently it doesn't work without it.

EDIT #2: I finally figured out how to make the views work properly, check my answer below.

答:
You need to define ViewResolver bean to let spring know where are your views

```<code>@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver bean = new InternalResourceViewResolver();
    bean.setViewClass(JstlView.class);
    bean.setPrefix("/WEB-INF/view/");
    bean.setSuffix(".html");
    return bean;
}
</code>```

Body:
It's my first attempt at using Spring and I ran into a problem. I cannot seem to return a simple HTML file as a view inside a controller. I'm trying to return the index.html file (it just has some text and a button), because it is displayed correctly when going to localhost:8080/.

The project was generated using IntelliJ, I figure I'd mention this since it handled most of the configuration.

Here's the file structure:

app:
 | src
    | main
       | java
          | com.my.testapp
              | Main.java
              | controllers
                  | TestController.java
       | resources
          | static
              | index.html

Here are my files:

Main.java

@SpringBootApplication
public class Main
{
    public static void main(String[] args)
    {
        SpringApplication.run(Main.class, args);
    }
}

TestController.java (the first controller actually works)

@RequestMapping("/test")
@Controller
public class TestController
{
    @RequestMapping(method = RequestMethod.GET, value = "/testget")
    public @ResponseBody ArrayList<Test> foo()
    {
        ArrayList<Test> tests = new ArrayList<>();

        tests.add(new Test("id1", "pass1"));
        tests.add(new Test("id2", "pass2"));

        return tests;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/someview")
    public String showView()
    {
        return "index";
    }
}

And finally, the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.my</groupId>
    <artifactId>testapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springtest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <addResources>true</addResources>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I was previously using @RestController annotation and the controller would simply return the string index, but now I get a 404 page (Whitelabel Error Page). I know this is a common issue, but I haven't been able to solve it using other people's solution.

EDIT: Ok, I managed to fix part of it by removing the line @RequestMapping("/test"), but I now need to pass the view as "index.html" instead of simply "index". Is there a way to skip the .html? Currently it doesn't work without it.

EDIT #2: I finally figured out how to make the views work properly, check my answer below.

Body:
You need to define ViewResolver bean to let spring know where are your views

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver bean = new InternalResourceViewResolver();
    bean.setViewClass(JstlView.class);
    bean.setPrefix("/WEB-INF/view/");
    bean.setSuffix(".html");
    return bean;
}


问:
Finding Similarities in strings, then grouping in new array with other data
I believe I have a complex issue which I'm struggling to find a solution for, and for the life of me I can't seem to achieve it.

I need to run an analysis on thousands of bank transactions to find similarities in their descriptions.

To start, I have an array of transactions, that are grouped by month, here's is a small sample:

```<code>$sample_transactions = array(
  ['Oct_2017']=>array(4) {
    [0] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 34345555 REF NO 21283322"
      ["amount"]=>string(4) "1290"
    }
    [1] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 34345555 REF NO 8765876"
      ["amount"]=>string(4) "1000"
    }
    [2] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 785674556 REF NO 46312212"
      ["amount"]=>string(4) "2500"
    }
    [3] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 785674556 REF NO 977553"
      ["amount"]=>string(4) "4000"
    }
  }
  ['Nov_2017']=>array(4) {
    [0] => array(2) {
      ["desc"]=>string(55) "PHONE TRANSFER CREDIT FROM 65765544 REF NO 123444"
      ["amount"]=>string(4) "879"
    }
    [1] => array(2) {
      ["desc"]=>string(55) "EFTPOS JKL REV JANES HAIR MELBOURNE VIC AU"
      ["amount"]=>string(4) "200"
    }
    [2] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 785674556 REF NO 46312212"
      ["amount"]=>string(4) "3200"
    }
    [3] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 785674556 REF NO 977553"
      ["amount"]=>string(4) "6039"
    }
  }
);
</code>```

Using the sample transactions above, the desire is to look for similarities in their desc, then group them together, add a count of how many there were, and increment the total figure.

Here is an example of the desired data:

```<code>Oct_2017
=================================================================
|        Desc.                            |  Amount   |  Count  |
=================================================================
|  TRANSFER CREDIT FROM 34345555 REF NO       2290         2    |
-----------------------------------------------------------------
|  TRANSFER CREDIT FROM 785674556 REF NO      6500         2    |
=================================================================

Nov_2017
=================================================================
|        Desc.                            |  Amount   |  Count  |
=================================================================
|  TRANSFER CREDIT FROM 785674556             9239         2    |
=================================================================
</code>```

If you notice from the two tables of data, it does the following:

Skips the string if it only occurs once

Groups strings if they occur twice, but, they can have differences somewhere, e.g. Reference number at the end of the string

Increments the "amount" for that group

Increments the "count" for each time an occurrence was found.

Edit: These transactions are provided to us from a third party source and saved in our Mysql DB, so the strings could literally be anything. This means we can't have a collection of strings to look for, because we don't know what we are looking for. We need to highlight the "patterns" in the transactions rather than things we are looking for.

Edit2: Some more sample strings could be:

RETURNED CREDIT FROM Mr Nobody 9392 JKK freight ACCOUNT CLOSED

RETURNED CREDIT FROM Mrs Somebody Melbourne Aus INVALID ACCOUNT NUMBER

VISA CREDIT HERTZ GOKKO JIMBO 14/08 AU AUD

EFTPOS DEP Medicare Benefit

DIRECT CREDIT CBA TRANSFER

BPAY REV 3535333 KLM RENEW 4823

AGENT DEPOSIT 87

ANZ ATM PORTLAND 26 NOTHING ST PORTLAND VIC

DIRECT CREDIT DONTY BENEFITS 23423322 EYWQ

Methods I've tried:

1 - I tried this approach to compare strings, however, using similar_text() is not specific enough - it results in groups being made which shouldn't be as it's just based on the similarity percentage, and doesn't group based on characters like required.

2 - I tried querying from the database using ORDER BY desc ASC which obviously orders them quite well, but includes everything, and doesn't group them like the desired result.

答:
The bad news is: php doesn't offer anything out of the box to do this kind of process.

The good news is: you can roll your own and modify it as you learn more about what you want to call "similar".  As your bespoke method matures, its accuracy will ascend ever closer to 100%. Use the "leftovers" to discover similarities that can be built into the code.

I hope this is enough to give you some traction:

Code: (Demo)

```<code>$sample_transactions=[
    'Oct_2017'=>[
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 34345555 REF NO 21283322","amount"=>"1290"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 34345555 REF NO 8765876","amount"=>"1000"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 785674556 REF NO 46312212","amount"=>"2500"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 785674556 REF NO 977553","amount"=>"4000"],
        ["desc"=>"PHONE TRANSFER CREDIT FROM 65765544 REF NO 123444","amount"=>"879"],
        ["desc"=>"EFTPOS JKL REV JANES HAIR MELBOURNE VIC AU","amount"=>"200"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 785674556 REF NO 46312212","amount"=>"3200"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 785674556 REF NO 977553","amount"=>"6039"],
        ["desc"=>"RETURNED CREDIT FROM Mr Nobody 9392 JKK freight ACCOUNT CLOSED","amount"=>"123"],
        ["desc"=>"RETURNED CREDIT FROM Mrs Somebody Melbourne Aus INVALID ACCOUNT NUMBER","amount"=>"124"],
        ["desc"=>"VISA CREDIT HERTZ GOKKO JIMBO 14/08 AU AUD","amount"=>"1234"],
        ["desc"=>"EFTPOS DEP Medicare Benefit","amount"=>"999"],
        ["desc"=>"DIRECT CREDIT CBA TRANSFER","amount"=>"1050"],
        ["desc"=>"BPAY REV 3535333 KLM RENEW 4823","amount"=>"1175"],
        ["desc"=>"AGENT DEPOSIT 87","amount"=>"100"],
        ["desc"=>"ANZ ATM PORTLAND 26 NOTHING ST PORTLAND VIC","amount"=>"200"],
        ["desc"=>"DIRECT CREDIT DONTY BENEFITS 23423322 EYWQ","amount"=>"300"]
    ]
];

foreach($sample_transactions as $mo_year=>$trans_array){
    foreach($trans_array as $trans){
        if(!$key=strstr($trans['desc'],' FROM ',true)){ // declare $key if no ' FROM ' try something else
            if(strpos($trans['desc'],'DIRECT CREDIT')===0){  // try 'DIRECT CREDIT' at start of string
                $key='DIRECT CREDIT';
            }else{
                $key=$trans['desc'];  // if all attempts fail, default to fullstring value
            }
        }
        if(!isset($groups[$mo_year][$key])){
            $groups[$mo_year][$key]=['Amount'=>$trans['amount'],'Count'=>1];  //initialize the row
        }else{
            $groups[$mo_year][$key]=[
                'Amount'=>$groups[$mo_year][$key]['Amount']+$trans['amount'],  // do the sum
                'Count'=>++$groups[$mo_year][$key]['Count']  // increment by 1
            ];
        }
    }
}

// split results into two groups based on Count value
foreach($groups as $mo_year=>$rows){
    foreach($rows as $desc=>$sums){
        if($sums['Count']<2){
            $singletons[$mo_year][$desc]=$sums;
        }else{
            $similarities[$mo_year][$desc]=$sums;
        }
    }
}

echo "Attempted Consolidation:\n";
var_export($groups);
echo "\n\nSimilarities:\n";
var_export($similarities);
echo "\n\nThe leftovers to review and try to isolate relevant similarities\n";
var_export($singletons);
</code>```

Output:

```<code>Attempted Consolidation:
array (
  'Oct_2017' =>
  array (
    'INTERNET TRANSFER CREDIT' =>
    array (
      'Amount' => 18029,
      'Count' => 6,
    ),
    'PHONE TRANSFER CREDIT' =>
    array (
      'Amount' => '879',
      'Count' => 1,
    ),
    'EFTPOS JKL REV JANES HAIR MELBOURNE VIC AU' =>
    array (
      'Amount' => '200',
      'Count' => 1,
    ),
    'RETURNED CREDIT' =>
    array (
      'Amount' => 247,
      'Count' => 2,
    ),
    'VISA CREDIT HERTZ GOKKO JIMBO 14/08 AU AUD' =>
    array (
      'Amount' => '1234',
      'Count' => 1,
    ),
    'EFTPOS DEP Medicare Benefit' =>
    array (
      'Amount' => '999',
      'Count' => 1,
    ),
    'DIRECT CREDIT' =>
    array (
      'Amount' => 1350,
      'Count' => 2,
    ),
    'BPAY REV 3535333 KLM RENEW 4823' =>
    array (
      'Amount' => '1175',
      'Count' => 1,
    ),
    'AGENT DEPOSIT 87' =>
    array (
      'Amount' => '100',
      'Count' => 1,
    ),
    'ANZ ATM PORTLAND 26 NOTHING ST PORTLAND VIC' =>
    array (
      'Amount' => '200',
      'Count' => 1,
    ),
  ),
)

Similarities:
array (
  'Oct_2017' =>
  array (
    'INTERNET TRANSFER CREDIT' =>
    array (
      'Amount' => 18029,
      'Count' => 6,
    ),
    'RETURNED CREDIT' =>
    array (
      'Amount' => 247,
      'Count' => 2,
    ),
    'DIRECT CREDIT' =>
    array (
      'Amount' => 1350,
      'Count' => 2,
    ),
  ),
)

The leftovers to review and try to isolate relevant similarities
array (
  'Oct_2017' =>
  array (
    'PHONE TRANSFER CREDIT' =>
    array (
      'Amount' => '879',
      'Count' => 1,
    ),
    'EFTPOS JKL REV JANES HAIR MELBOURNE VIC AU' =>
    array (
      'Amount' => '200',
      'Count' => 1,
    ),
    'VISA CREDIT HERTZ GOKKO JIMBO 14/08 AU AUD' =>
    array (
      'Amount' => '1234',
      'Count' => 1,
    ),
    'EFTPOS DEP Medicare Benefit' =>
    array (
      'Amount' => '999',
      'Count' => 1,
    ),
    'BPAY REV 3535333 KLM RENEW 4823' =>
    array (
      'Amount' => '1175',
      'Count' => 1,
    ),
    'AGENT DEPOSIT 87' =>
    array (
      'Amount' => '100',
      'Count' => 1,
    ),
    'ANZ ATM PORTLAND 26 NOTHING ST PORTLAND VIC' =>
    array (
      'Amount' => '200',
      'Count' => 1,
    ),
  ),
)
</code>```

Body:
I believe I have a complex issue which I'm struggling to find a solution for, and for the life of me I can't seem to achieve it.

I need to run an analysis on thousands of bank transactions to find similarities in their descriptions.

To start, I have an array of transactions, that are grouped by month, here's is a small sample:

$sample_transactions = array(
  ['Oct_2017']=>array(4) {
    [0] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 34345555 REF NO 21283322"
      ["amount"]=>string(4) "1290"
    }
    [1] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 34345555 REF NO 8765876"
      ["amount"]=>string(4) "1000"
    }
    [2] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 785674556 REF NO 46312212"
      ["amount"]=>string(4) "2500"
    }
    [3] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 785674556 REF NO 977553"
      ["amount"]=>string(4) "4000"
    }
  }
  ['Nov_2017']=>array(4) {
    [0] => array(2) {
      ["desc"]=>string(55) "PHONE TRANSFER CREDIT FROM 65765544 REF NO 123444"
      ["amount"]=>string(4) "879"
    }
    [1] => array(2) {
      ["desc"]=>string(55) "EFTPOS JKL REV JANES HAIR MELBOURNE VIC AU"
      ["amount"]=>string(4) "200"
    }
    [2] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 785674556 REF NO 46312212"
      ["amount"]=>string(4) "3200"
    }
    [3] => array(2) {
      ["desc"]=>string(55) "INTERNET TRANSFER CREDIT FROM 785674556 REF NO 977553"
      ["amount"]=>string(4) "6039"
    }
  }
);

Using the sample transactions above, the desire is to look for similarities in their desc, then group them together, add a count of how many there were, and increment the total figure.

Here is an example of the desired data:

Oct_2017
=================================================================
|        Desc.                            |  Amount   |  Count  |
=================================================================
|  TRANSFER CREDIT FROM 34345555 REF NO       2290         2    |
-----------------------------------------------------------------
|  TRANSFER CREDIT FROM 785674556 REF NO      6500         2    |
=================================================================

Nov_2017
=================================================================
|        Desc.                            |  Amount   |  Count  |
=================================================================
|  TRANSFER CREDIT FROM 785674556             9239         2    |
=================================================================

If you notice from the two tables of data, it does the following:

Skips the string if it only occurs once

Groups strings if they occur twice, but, they can have differences somewhere, e.g. Reference number at the end of the string

Increments the "amount" for that group

Increments the "count" for each time an occurrence was found.

Edit: These transactions are provided to us from a third party source and saved in our Mysql DB, so the strings could literally be anything. This means we can't have a collection of strings to look for, because we don't know what we are looking for. We need to highlight the "patterns" in the transactions rather than things we are looking for.

Edit2: Some more sample strings could be:

RETURNED CREDIT FROM Mr Nobody 9392 JKK freight ACCOUNT CLOSED

RETURNED CREDIT FROM Mrs Somebody Melbourne Aus INVALID ACCOUNT NUMBER

VISA CREDIT HERTZ GOKKO JIMBO 14/08 AU AUD

EFTPOS DEP Medicare Benefit

DIRECT CREDIT CBA TRANSFER

BPAY REV 3535333 KLM RENEW 4823

AGENT DEPOSIT 87

ANZ ATM PORTLAND 26 NOTHING ST PORTLAND VIC

DIRECT CREDIT DONTY BENEFITS 23423322 EYWQ

Methods I've tried:

1 - I tried this approach to compare strings, however, using similar_text() is not specific enough - it results in groups being made which shouldn't be as it's just based on the similarity percentage, and doesn't group based on characters like required.

2 - I tried querying from the database using ORDER BY desc ASC which obviously orders them quite well, but includes everything, and doesn't group them like the desired result.

Body:
The bad news is: php doesn't offer anything out of the box to do this kind of process.

The good news is: you can roll your own and modify it as you learn more about what you want to call "similar".  As your bespoke method matures, its accuracy will ascend ever closer to 100%. Use the "leftovers" to discover similarities that can be built into the code.

I hope this is enough to give you some traction:

Code: (Demo)

$sample_transactions=[
    'Oct_2017'=>[
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 34345555 REF NO 21283322","amount"=>"1290"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 34345555 REF NO 8765876","amount"=>"1000"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 785674556 REF NO 46312212","amount"=>"2500"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 785674556 REF NO 977553","amount"=>"4000"],
        ["desc"=>"PHONE TRANSFER CREDIT FROM 65765544 REF NO 123444","amount"=>"879"],
        ["desc"=>"EFTPOS JKL REV JANES HAIR MELBOURNE VIC AU","amount"=>"200"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 785674556 REF NO 46312212","amount"=>"3200"],
        ["desc"=>"INTERNET TRANSFER CREDIT FROM 785674556 REF NO 977553","amount"=>"6039"],
        ["desc"=>"RETURNED CREDIT FROM Mr Nobody 9392 JKK freight ACCOUNT CLOSED","amount"=>"123"],
        ["desc"=>"RETURNED CREDIT FROM Mrs Somebody Melbourne Aus INVALID ACCOUNT NUMBER","amount"=>"124"],
        ["desc"=>"VISA CREDIT HERTZ GOKKO JIMBO 14/08 AU AUD","amount"=>"1234"],
        ["desc"=>"EFTPOS DEP Medicare Benefit","amount"=>"999"],
        ["desc"=>"DIRECT CREDIT CBA TRANSFER","amount"=>"1050"],
        ["desc"=>"BPAY REV 3535333 KLM RENEW 4823","amount"=>"1175"],
        ["desc"=>"AGENT DEPOSIT 87","amount"=>"100"],
        ["desc"=>"ANZ ATM PORTLAND 26 NOTHING ST PORTLAND VIC","amount"=>"200"],
        ["desc"=>"DIRECT CREDIT DONTY BENEFITS 23423322 EYWQ","amount"=>"300"]
    ]
];

foreach($sample_transactions as $mo_year=>$trans_array){
    foreach($trans_array as $trans){
        if(!$key=strstr($trans['desc'],' FROM ',true)){ // declare $key if no ' FROM ' try something else
            if(strpos($trans['desc'],'DIRECT CREDIT')===0){  // try 'DIRECT CREDIT' at start of string
                $key='DIRECT CREDIT';
            }else{
                $key=$trans['desc'];  // if all attempts fail, default to fullstring value
            }
        }
        if(!isset($groups[$mo_year][$key])){
            $groups[$mo_year][$key]=['Amount'=>$trans['amount'],'Count'=>1];  //initialize the row
        }else{
            $groups[$mo_year][$key]=[
                'Amount'=>$groups[$mo_year][$key]['Amount']+$trans['amount'],  // do the sum
                'Count'=>++$groups[$mo_year][$key]['Count']  // increment by 1
            ];
        }
    }
}

// split results into two groups based on Count value
foreach($groups as $mo_year=>$rows){
    foreach($rows as $desc=>$sums){
        if($sums['Count']<2){
            $singletons[$mo_year][$desc]=$sums;
        }else{
            $similarities[$mo_year][$desc]=$sums;
        }
    }
}

echo "Attempted Consolidation:\n";
var_export($groups);
echo "\n\nSimilarities:\n";
var_export($similarities);
echo "\n\nThe leftovers to review and try to isolate relevant similarities\n";
var_export($singletons);

Output:

Attempted Consolidation:
array (
  'Oct_2017' =>
  array (
    'INTERNET TRANSFER CREDIT' =>
    array (
      'Amount' => 18029,
      'Count' => 6,
    ),
    'PHONE TRANSFER CREDIT' =>
    array (
      'Amount' => '879',
      'Count' => 1,
    ),
    'EFTPOS JKL REV JANES HAIR MELBOURNE VIC AU' =>
    array (
      'Amount' => '200',
      'Count' => 1,
    ),
    'RETURNED CREDIT' =>
    array (
      'Amount' => 247,
      'Count' => 2,
    ),
    'VISA CREDIT HERTZ GOKKO JIMBO 14/08 AU AUD' =>
    array (
      'Amount' => '1234',
      'Count' => 1,
    ),
    'EFTPOS DEP Medicare Benefit' =>
    array (
      'Amount' => '999',
      'Count' => 1,
    ),
    'DIRECT CREDIT' =>
    array (
      'Amount' => 1350,
      'Count' => 2,
    ),
    'BPAY REV 3535333 KLM RENEW 4823' =>
    array (
      'Amount' => '1175',
      'Count' => 1,
    ),
    'AGENT DEPOSIT 87' =>
    array (
      'Amount' => '100',
      'Count' => 1,
    ),
    'ANZ ATM PORTLAND 26 NOTHING ST PORTLAND VIC' =>
    array (
      'Amount' => '200',
      'Count' => 1,
    ),
  ),
)

Similarities:
array (
  'Oct_2017' =>
  array (
    'INTERNET TRANSFER CREDIT' =>
    array (
      'Amount' => 18029,
      'Count' => 6,
    ),
    'RETURNED CREDIT' =>
    array (
      'Amount' => 247,
      'Count' => 2,
    ),
    'DIRECT CREDIT' =>
    array (
      'Amount' => 1350,
      'Count' => 2,
    ),
  ),
)

The leftovers to review and try to isolate relevant similarities
array (
  'Oct_2017' =>
  array (
    'PHONE TRANSFER CREDIT' =>
    array (
      'Amount' => '879',
      'Count' => 1,
    ),
    'EFTPOS JKL REV JANES HAIR MELBOURNE VIC AU' =>
    array (
      'Amount' => '200',
      'Count' => 1,
    ),
    'VISA CREDIT HERTZ GOKKO JIMBO 14/08 AU AUD' =>
    array (
      'Amount' => '1234',
      'Count' => 1,
    ),
    'EFTPOS DEP Medicare Benefit' =>
    array (
      'Amount' => '999',
      'Count' => 1,
    ),
    'BPAY REV 3535333 KLM RENEW 4823' =>
    array (
      'Amount' => '1175',
      'Count' => 1,
    ),
    'AGENT DEPOSIT 87' =>
    array (
      'Amount' => '100',
      'Count' => 1,
    ),
    'ANZ ATM PORTLAND 26 NOTHING ST PORTLAND VIC' =>
    array (
      'Amount' => '200',
      'Count' => 1,
    ),
  ),
)


问:
How do I print everything separately? What will be the loop?
Make two new dictionaries representing different people, and store all three
dictionaries in a list called people. Loop through your list of people. As you
loop through the list, print everything you know about each person.

```<code>person_1 = {'first_name':'shamol',
      'last_name': 'kabir',
      'age': '25',
      'city': 'jessore'}
person_2 = {'first_name':'shorif',
        'last_name':'jaman',
        'age':'28',
        'city':'khulna'}
person_3= {'first_name':'mizan',
       'last_name':'rahman',
       'age':'25',
       'city':'jessore'}
people= [person_1,person_2,person_3]
</code>```

what will be the next few lines??

答:
I don't understand what you are asking for, as you could simply print(people)</p>

```<code>person_1 = {'first_name':'shamol',
      'last_name': 'kabir',
      'age': '25',
      'city': 'jessore'}
person_2 = {'first_name':'shorif',
        'last_name':'jaman',
        'age':'28',
        'city':'khulna'}
person_3= {'first_name':'mizan',
       'last_name':'rahman',
       'age':'25',
       'city':'jessore'}
people= [person_1,person_2,person_3]

for person in people:
    for key in person:
        print('{} : {}'.format(key, person[key])) # works in both python 2 and python 3
        #print(f'{key} {person[key]}')            #works in python 3 only
    print('-'*20)
</code>```

Body:
Make two new dictionaries representing different people, and store all three
dictionaries in a list called people. Loop through your list of people. As you
loop through the list, print everything you know about each person.

person_1 = {'first_name':'shamol',
      'last_name': 'kabir',
      'age': '25',
      'city': 'jessore'}
person_2 = {'first_name':'shorif',
        'last_name':'jaman',
        'age':'28',
        'city':'khulna'}
person_3= {'first_name':'mizan',
       'last_name':'rahman',
       'age':'25',
       'city':'jessore'}
people= [person_1,person_2,person_3]

what will be the next few lines??

Body:
I don't understand what you are asking for, as you could simply print(people)

person_1 = {'first_name':'shamol',
      'last_name': 'kabir',
      'age': '25',
      'city': 'jessore'}
person_2 = {'first_name':'shorif',
        'last_name':'jaman',
        'age':'28',
        'city':'khulna'}
person_3= {'first_name':'mizan',
       'last_name':'rahman',
       'age':'25',
       'city':'jessore'}
people= [person_1,person_2,person_3]

for person in people:
    for key in person:
        print('{} : {}'.format(key, person[key])) # works in both python 2 and python 3
        #print(f'{key} {person[key]}')            #works in python 3 only
    print('-'*20)


答:
You need to go to the itms array to get your desired keys, you will need a second foreach

```<code>foreach($data['b2b'] as $inner){
    foreach( $inner['inv'][0]['itms'] as $row){
       $stmt->bindParam(1, $row['itc']['tx_cs']);
       $stmt->bindParam(2, $row['itc']['elg']);
    $stmt->execute();
     }
}
</code>```

or:

```<code>foreach($data['b2b'] as $inner){
        $stmt->bindParam(1, $inner['inv'][0]['itms'][0]['itc']['tx_cs']);
        $stmt->bindParam(2, $inner['inv'][0]['itms'][0]['itc']['elg']);
        $stmt->execute();
 }
</code>```

Title: This is my JSON data and trying to acces this data and insert to the mysql

Body:
    {
    "gstin":"29AAHCS4690J1ZQ",
    "fp":"072017",
    "b2b":[
      {
         "ctin":"01AAACJ4126D1ZE",
         "cfs":"Y",
         "inv":[
            {
               "itms":[
                  {
                     "num":1,
                     "itc":{
                        "tx_cs":0,
                        "elg":"ip",
                        "tx_i":112.5
                     },
                     "itm_det":{
                        "csamt":0,
                        "rt":18,
                        "txval":625,
                        "iamt":112.5
                     }
                  }
               ],
               "val":738,
               "inv_typ":"R",
               "flag":"N",
               "updby":"S",
               "pos":"29",
               "idt":"31-07-2017",
               "rchrg":"N",
               "cflag":"U",
               "inum":"FL-17000069",

    "chksum":"4d3e41facf5002f418e1ac605d9888d74ee21652e19de6db624fc7106e3c5866"
            }
         ]
      },

{
         "ctin":"29AACFI3027K1ZC",
         "cfs":"Y",
         "inv":[
            {
               "itms":[
                  {
                     "num":1800,
                     "itc":{
                        "elg":"ip",
                        "tx_c":171.59,
                        "tx_s":171.59
                     },
                     "itm_det":{
                        "samt":171.59,
                        "rt":18,
                        "txval":1906.5,
                        "camt":171.59
                     }
                  }
               ],
               "val":2250,
               "inv_typ":"R",
               "flag":"N",
               "updby":"S",
               "pos":"29",
               "idt":"06-07-2017",
               "rchrg":"Y",
               "cflag":"U",
               "inum":"0042",
               "chksum":"aa1187a2bb7d6098c39c4c992bd391ab7fd59e7eeefcea5b91fc9881ba4423d8"
            }
         ]
      }
    ]
    }

The above code is in JSON and I am accessing this in the following way as shown below

<?php
$servername = "localhost";
$username = "root";
$password = "";

$db = new PDO("mysql:host=$servername;dbname=item", $username, $password);
$jsondata = file_get_contents('data.json');
$data  = json_decode($jsondata, true);
$stmt = $db->prepare("insert into itc(tx_cs, elg) values(? , ?)");
var_dump($data);
// echo $data;
foreach($data as $row){
$stmt->bindParam(1, $row['tx_cs']);
$stmt->bindParam(2, $row['elg']);
$stmt->execute();

 }
  ?>

After executing insert statement I am getting just null in mysql any solution for this. If I trying to insert getting illegal string "tx_cs" if there any alternative to access nested JSON data. and also I want to know the how the array indexes Thanks in advance.

This is var_dump Result                                                                           array(4) { ["gstin"]=> string(15) "29AAHCS4690J1ZQ" ["fp"]=> string(6) "072017" ["b2b"]=> array(59) { [0]=> array(3) { ["ctin"]=> string(15) "01AAACJ4126D1ZE" ["cfs"]=> string(1) "Y" ["inv"]=> array(1) { [0]=> array(11) { ["itms"]=> array(1) { [0]=> array(3) { ["num"]=> int(1) ["itc"]=> array(3) { ["tx_cs"]=> int(0) ["elg"]=> string(2) "ip" ["tx_i"]=> float(112.5) } ["itm_det"]=> array(4) { ["csamt"]=> int(0) ["rt"]=> int(18) ["txval"]=> int(625) ["iamt"]=> float(112.5) } } } ["val"]=> int(738) ["inv_typ"]=> string(1) "R" ["flag"]=> string(1) "N" ["updby"]=> string(1) "S" ["pos"]=> string(2) "29" ["idt"]=> string(10) "31-07-2017" ["rchrg"]=> string(1) "N" ["cflag"]=> string(1) "U" ["inum"]=> string(11) "FL-17000069" ["chksum"]=> string(64)

Body:
You need to go to the itms array to get your desired keys, you will need a second foreach

foreach($data['b2b'] as $inner){
    foreach( $inner['inv'][0]['itms'] as $row){
       $stmt->bindParam(1, $row['itc']['tx_cs']);
       $stmt->bindParam(2, $row['itc']['elg']);
    $stmt->execute();
     }
}

or:

foreach($data['b2b'] as $inner){
        $stmt->bindParam(1, $inner['inv'][0]['itms'][0]['itc']['tx_cs']);
        $stmt->bindParam(2, $inner['inv'][0]['itms'][0]['itc']['elg']);
        $stmt->execute();
 }


问:
laravel Collections's function only on Elequent ORM result always return empty collection
I want only return the id, name and pic_thumbnail column of the Eloquent ORM collections result. I use only() on the result of get(). But I always get the empty collection.

```<code>public function models()
{
    if(!isset($_SESSION["uid"]))
        return Response::json(['error' => 'please login.']);
    $models = Model::where('user_id', $_SESSION["uid"])->get();
    Log::info($models);
    Log::info($models->only(['id', 'name']));
    Log::info($models->only(['id', 'name'])->all());
    foreach($models as $model){
        $pic = $model->pics()->orderBy('displayorder')->first();
        if($pic == null)
            $model->pic_thumbnail = 'static/thumbnail_no_image.jpg';
        else
            $model->pic_thumbnail = $pic->imgfilename('thumbnail');
    }

    Log::info($models);
    Log::info($models->only(['id', 'name', 'pic_thumbnail']));
    Log::info($models->only(['id', 'name', 'pic_thumbnail'])->all());
    return Response::json(['models' => $models->only(['id', 'name', 'pic_thumbnail'])->all()]);
}
</code>```

Log,

```<code>[2017-11-13 11:29:34] local.INFO: [{"id":83,"name":"ssss","description":"sssssssssss","category":3,"internalcomment":"","rating_editor":"4","created_at":"2017-08-30 01:29:49","updated_at":"2017-08-30 01:29:50","deleted_at":null,"zipall_name":"ssss.zip","zipall_size":770146,"zipall_md5":"b10a0462e6010659ba210bb09487b42a","user_id":52,"price":null},{"id":105,"name":"asdfasad","description":"12","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-10-26 15:22:02","updated_at":"2017-10-26 15:22:02","deleted_at":null,"zipall_name":"asdfasad.zip","zipall_size":10545,"zipall_md5":"7f1b88e67ce98a6499f06d6d7cd3e530","user_id":52,"price":null},{"id":122,"name":"oooooooooo","description":"oooooooooo","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-11-03 10:17:08","updated_at":"2017-11-03 10:19:03","deleted_at":null,"zipall_name":"oooooooooo.zip","zipall_size":21242,"zipall_md5":"9177faf7ae2c4b7c12f9208a99690130","user_id":52,"price":0.01},{"id":123,"name":"skull","description":"skull  demon","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-11-08 11:08:30","updated_at":"2017-11-08 11:08:30","deleted_at":null,"zipall_name":"skull.zip","zipall_size":299086,"zipall_md5":"22fe1047b13630ffcc0be115634ce167","user_id":52,"price":0}]
[2017-11-13 11:29:34] local.INFO: []
[2017-11-13 11:29:34] local.INFO: array (
)
[2017-11-13 11:29:34] local.INFO: [{"id":83,"name":"ssss","description":"sssssssssss","category":3,"internalcomment":"","rating_editor":"4","created_at":"2017-08-30 01:29:49","updated_at":"2017-08-30 01:29:50","deleted_at":null,"zipall_name":"ssss.zip","zipall_size":770146,"zipall_md5":"b10a0462e6010659ba210bb09487b42a","user_id":52,"price":null,"pic_thumbnail":"static\/thumbnail_no_image.jpg"},{"id":105,"name":"asdfasad","description":"12","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-10-26 15:22:02","updated_at":"2017-10-26 15:22:02","deleted_at":null,"zipall_name":"asdfasad.zip","zipall_size":10545,"zipall_md5":"7f1b88e67ce98a6499f06d6d7cd3e530","user_id":52,"price":null,"pic_thumbnail":"\/data\/pic\/thumbnail\/0\/183.jpg"},{"id":122,"name":"oooooooooo","description":"oooooooooo","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-11-03 10:17:08","updated_at":"2017-11-03 10:19:03","deleted_at":null,"zipall_name":"oooooooooo.zip","zipall_size":21242,"zipall_md5":"9177faf7ae2c4b7c12f9208a99690130","user_id":52,"price":0.01,"pic_thumbnail":"\/data\/pic\/thumbnail\/0\/229.jpg"},{"id":123,"name":"skull","description":"skull  demon","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-11-08 11:08:30","updated_at":"2017-11-08 11:08:30","deleted_at":null,"zipall_name":"skull.zip","zipall_size":299086,"zipall_md5":"22fe1047b13630ffcc0be115634ce167","user_id":52,"price":0,"pic_thumbnail":"\/data\/pic\/thumbnail\/0\/231.jpg"}]
[2017-11-13 11:29:34] local.INFO: []
[2017-11-13 11:29:34] local.INFO: array (
)
</code>```

答:
According to the example in the manual. it looks like it works only for single collection, not for collection of collections.

I think you have to do something like below.

```<code>$results = $models->map(function($model) {
    return $model->only(['id', 'name']);
});
</code>```

Body:
I want only return the id, name and pic_thumbnail column of the Eloquent ORM collections result. I use only() on the result of get(). But I always get the empty collection.

public function models()
{
    if(!isset($_SESSION["uid"]))
        return Response::json(['error' => 'please login.']);
    $models = Model::where('user_id', $_SESSION["uid"])->get();
    Log::info($models);
    Log::info($models->only(['id', 'name']));
    Log::info($models->only(['id', 'name'])->all());
    foreach($models as $model){
        $pic = $model->pics()->orderBy('displayorder')->first();
        if($pic == null)
            $model->pic_thumbnail = 'static/thumbnail_no_image.jpg';
        else
            $model->pic_thumbnail = $pic->imgfilename('thumbnail');
    }

    Log::info($models);
    Log::info($models->only(['id', 'name', 'pic_thumbnail']));
    Log::info($models->only(['id', 'name', 'pic_thumbnail'])->all());
    return Response::json(['models' => $models->only(['id', 'name', 'pic_thumbnail'])->all()]);
}

Log,

[2017-11-13 11:29:34] local.INFO: [{"id":83,"name":"ssss","description":"sssssssssss","category":3,"internalcomment":"","rating_editor":"4","created_at":"2017-08-30 01:29:49","updated_at":"2017-08-30 01:29:50","deleted_at":null,"zipall_name":"ssss.zip","zipall_size":770146,"zipall_md5":"b10a0462e6010659ba210bb09487b42a","user_id":52,"price":null},{"id":105,"name":"asdfasad","description":"12","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-10-26 15:22:02","updated_at":"2017-10-26 15:22:02","deleted_at":null,"zipall_name":"asdfasad.zip","zipall_size":10545,"zipall_md5":"7f1b88e67ce98a6499f06d6d7cd3e530","user_id":52,"price":null},{"id":122,"name":"oooooooooo","description":"oooooooooo","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-11-03 10:17:08","updated_at":"2017-11-03 10:19:03","deleted_at":null,"zipall_name":"oooooooooo.zip","zipall_size":21242,"zipall_md5":"9177faf7ae2c4b7c12f9208a99690130","user_id":52,"price":0.01},{"id":123,"name":"skull","description":"skull  demon","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-11-08 11:08:30","updated_at":"2017-11-08 11:08:30","deleted_at":null,"zipall_name":"skull.zip","zipall_size":299086,"zipall_md5":"22fe1047b13630ffcc0be115634ce167","user_id":52,"price":0}]
[2017-11-13 11:29:34] local.INFO: []
[2017-11-13 11:29:34] local.INFO: array (
)
[2017-11-13 11:29:34] local.INFO: [{"id":83,"name":"ssss","description":"sssssssssss","category":3,"internalcomment":"","rating_editor":"4","created_at":"2017-08-30 01:29:49","updated_at":"2017-08-30 01:29:50","deleted_at":null,"zipall_name":"ssss.zip","zipall_size":770146,"zipall_md5":"b10a0462e6010659ba210bb09487b42a","user_id":52,"price":null,"pic_thumbnail":"static\/thumbnail_no_image.jpg"},{"id":105,"name":"asdfasad","description":"12","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-10-26 15:22:02","updated_at":"2017-10-26 15:22:02","deleted_at":null,"zipall_name":"asdfasad.zip","zipall_size":10545,"zipall_md5":"7f1b88e67ce98a6499f06d6d7cd3e530","user_id":52,"price":null,"pic_thumbnail":"\/data\/pic\/thumbnail\/0\/183.jpg"},{"id":122,"name":"oooooooooo","description":"oooooooooo","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-11-03 10:17:08","updated_at":"2017-11-03 10:19:03","deleted_at":null,"zipall_name":"oooooooooo.zip","zipall_size":21242,"zipall_md5":"9177faf7ae2c4b7c12f9208a99690130","user_id":52,"price":0.01,"pic_thumbnail":"\/data\/pic\/thumbnail\/0\/229.jpg"},{"id":123,"name":"skull","description":"skull  demon","category":2,"internalcomment":"","rating_editor":"4","created_at":"2017-11-08 11:08:30","updated_at":"2017-11-08 11:08:30","deleted_at":null,"zipall_name":"skull.zip","zipall_size":299086,"zipall_md5":"22fe1047b13630ffcc0be115634ce167","user_id":52,"price":0,"pic_thumbnail":"\/data\/pic\/thumbnail\/0\/231.jpg"}]
[2017-11-13 11:29:34] local.INFO: []
[2017-11-13 11:29:34] local.INFO: array (
)

Body:
According to the example in the manual. it looks like it works only for single collection, not for collection of collections.

I think you have to do something like below.

$results = $models->map(function($model) {
    return $model->only(['id', 'name']);
});


问:
Binary search Python Why do we use mid + 1 or mid - 1
I am learning binary search and the sample code uses" low = mid +1 and high = mid -1" but I don't understand why we do not use "low = mid and high = mid " instead?

```<code>def binarysearch(sequence, value):
    lo, hi = 0, len(sequence) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sequence[mid] < value:
            lo = mid + 1
        elif value < sequence[mid]:
            hi = mid - 1
        else:
            return mid
    return None

my_list = [1, 3, 5, 7, 9]
binarysearch(my_list, 3)
</code>```

答:
Please let me try to explain why the binary search works. Let's say we've the following sequence A=[-5, 10, 14, 33, 42, 42, 42] and searched_value = 14 we would have:

```<code>Iteration 1,     lo = 0, hi = 6, mid = 3     A[mid] > 14
Iteration 2,     lo = 0, hi = 2, mid = 1     A[mid] < 14
Iteration 3,     lo = 2, hi = 2, mid = 2     A[mid] = 14  (found!)
</code>```

At each iteration of the algorithm we could conclude that lo and hi always contains the position of the searched value, and we'll prove it by induction on the number of iterations:

Inductive Hypothesis: if the searched value is present in the sequence it will always be contained between lo and hi.

Base Case: At iteration 1 lo = 0 and hi = n-1 contains all elements, in consequence if the searched value is present in the sequence it'll be contained between lo and hi, and the invariant is trivially correct.

Inductive Step: At any step if the searched value is contained between lo and hi, it'll continue to be contained between lo and hi at the next iteration. We've 3 possibilities (and here is the answer to the question):

If A[mid] = searched_value: In this case the algorithm finishes reporting correctly the position of the searched value in the sequence and the invariant is correct because the searched value was between lo and hi.

If A[mid] < searched_value: Knowing that it's a sorted sequence, all the elements between A[lo...mid] < searched_value (including A[mid]), thus we can assign lo=mid+1 (safely searching only in the upper half) and the invariant will still be correct at the next iteration.

If A[mid] > searched_value: knowing that it's a sorted sequence, all the elements between A[mid...hi] > searched value (including A[mid]), thus we can assing hi=mid-1 (safely searching only in the lower half) and the invariant will still be correct at the next iteration.

Given that, at each iteration, the algorithm always searches on smaller segments
 of the sequence, the termination condition is guaranteed because either there's only 1 element that is searched_value or it is different and, at the next iteration, the algorithm is going to report that such element isn't present in the sequence.

In consequence the algorithm is proved correct (and the reason why we use mid+1 and mid-1).

Body:
I am learning binary search and the sample code uses" low = mid +1 and high = mid -1" but I don't understand why we do not use "low = mid and high = mid " instead?

def binarysearch(sequence, value):
    lo, hi = 0, len(sequence) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sequence[mid] < value:
            lo = mid + 1
        elif value < sequence[mid]:
            hi = mid - 1
        else:
            return mid
    return None

my_list = [1, 3, 5, 7, 9]
binarysearch(my_list, 3)

Body:
Please let me try to explain why the binary search works. Let's say we've the following sequence A=[-5, 10, 14, 33, 42, 42, 42] and searched_value = 14 we would have:

Iteration 1,     lo = 0, hi = 6, mid = 3     A[mid] > 14
Iteration 2,     lo = 0, hi = 2, mid = 1     A[mid] < 14
Iteration 3,     lo = 2, hi = 2, mid = 2     A[mid] = 14  (found!)

At each iteration of the algorithm we could conclude that lo and hi always contains the position of the searched value, and we'll prove it by induction on the number of iterations:

Inductive Hypothesis: if the searched value is present in the sequence it will always be contained between lo and hi.

Base Case: At iteration 1 lo = 0 and hi = n-1 contains all elements, in consequence if the searched value is present in the sequence it'll be contained between lo and hi, and the invariant is trivially correct.

Inductive Step: At any step if the searched value is contained between lo and hi, it'll continue to be contained between lo and hi at the next iteration. We've 3 possibilities (and here is the answer to the question):

If A[mid] = searched_value: In this case the algorithm finishes reporting correctly the position of the searched value in the sequence and the invariant is correct because the searched value was between lo and hi.

If A[mid] < searched_value: Knowing that it's a sorted sequence, all the elements between A[lo...mid] < searched_value (including A[mid]), thus we can assign lo=mid+1 (safely searching only in the upper half) and the invariant will still be correct at the next iteration.

If A[mid] > searched_value: knowing that it's a sorted sequence, all the elements between A[mid...hi] > searched value (including A[mid]), thus we can assing hi=mid-1 (safely searching only in the lower half) and the invariant will still be correct at the next iteration.

Given that, at each iteration, the algorithm always searches on smaller segments
 of the sequence, the termination condition is guaranteed because either there's only 1 element that is searched_value or it is different and, at the next iteration, the algorithm is going to report that such element isn't present in the sequence.

In consequence the algorithm is proved correct (and the reason why we use mid+1 and mid-1).


问:
Dynamically change header string in angular 2
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a

```<code><h1>{{title}}</h1>
</code>```

and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page

below is an image of what im trying to change

Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..

Not sure how I can go about this and everything ive researched has been to change the title in the  tags

答:
use title service in browser platform to change the title dynamically. refer this link for more information

app.module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule, Title }  from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    Title
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
</code>```

app.component.ts

```<code>// Import the native Angular services.
import { Component } from '@angular/core';
import { Title }     from '@angular/platform-browser';

@Component({
selector: 'app-root',
template:
  `<p>
    Select a title to set on the current HTML document:
  </p>

  <ul>
    <li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
    <li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
    <li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
  </ul>
  `
})
export class AppComponent {
  public constructor(private titleService: Title ) { }

  public setTitle( newTitle: string) {
    this.titleService.setTitle( newTitle );
  }
}
</code>```

Body:
In my app Im trying to dynamically change the title in my header component depending on the page that Im on, so In my header component I want to use a

{{title}}

and I want it to change depending on the page that I am on. Now the header is fixed so it's on every page

below is an image of what im trying to change

Basically if im on the home page I want it to say home and then if Im on an about page I want it to change to about..

Not sure how I can go about this and everything ive researched has been to change the title in the  tags

Body:
use title service in browser platform to change the title dynamically. refer this link for more information

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule, Title }  from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule
  ],
  declarations: [
    AppComponent
  ],
  providers: [
    Title
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

app.component.ts

// Import the native Angular services.
import { Component } from '@angular/core';
import { Title }     from '@angular/platform-browser';

@Component({
selector: 'app-root',
template:
  `<p>
    Select a title to set on the current HTML document:
  </p>

  <ul>
    <li><a (click)="setTitle( 'Good morning!' )">Good morning</a>.</li>
    <li><a (click)="setTitle( 'Good afternoon!' )">Good afternoon</a>.</li>
    <li><a (click)="setTitle( 'Good evening!' )">Good evening</a>.</li>
  </ul>
  `
})
export class AppComponent {
  public constructor(private titleService: Title ) { }

  public setTitle( newTitle: string) {
    this.titleService.setTitle( newTitle );
  }
}


问:
Printing BST in directory listing format
I've this project to print a Binary Search Tree in these Formats (Pre-order, In-order, Post-order, and finally  directory listing format)
I got them all working fine, except the  directory listing format, I didn't know how to print BST in this format, please See the pic I attached.

I'd very appreciate it if someone can help..

this is my method of printing

```<code>void preOrder(Node node)
 {
     if (node != null)
     {
         System.out.print(node.key + " ");
         preOrder(node.left);
         preOrder(node.right);
     }
 }`
 tree.preOrder(tree.root);
</code>```

答:
Use Level orer traversal . Psuedo algorithm is this:
initialize an empty queue.

Use recursion from root

Insert first root node in queue.print the node value

If node has any left , insert left in queue

If node has any right , insert right in queue,

On checking for both insert a delimiter e.g '\0'.
   again check if the queue is empty

if empty stop recursion

If not again go  back to step 1.

Thats how you can print directory listing format.

Follow this link for further understanding.
http://www.geeksforgeeks.org/level-order-tree-traversal/

Body:
I've this project to print a Binary Search Tree in these Formats (Pre-order, In-order, Post-order, and finally  directory listing format)
I got them all working fine, except the  directory listing format, I didn't know how to print BST in this format, please See the pic I attached.

I'd very appreciate it if someone can help..

this is my method of printing

void preOrder(Node node)
 {
     if (node != null)
     {
         System.out.print(node.key + " ");
         preOrder(node.left);
         preOrder(node.right);
     }
 }`
 tree.preOrder(tree.root);


问:
C# How to sort int when value is too large
```<code>8
723
77715926535897932384626433832795
</code>```

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

答:
The best option is to use a numeric datatype with greater capacity. The largest numeric datatype is the decimal which has 96 bits of precision (about 28 digits). There are also some other data types that are in between. In general it is best to use the datatype that is just large enough. With floating point data types, beware of loss of precision when there are too many significant digits.

If you are working with numbers so huge they won't fit into any of the numeric data types, you can sort an arbitrarily long integer by padding it with zeroes so they are all the same length.

```<code>using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var inputs = new string[]
        {
            "77715926535897932384626433832795",
            "8",
            "2398798734",
            "0092",
            "12987981239871928379817231",
            "98279384792873498274908123946109478276492874927864928734872983476928739487298374"
        };

        //Determine the length of the longest number when expressed as a string
        var maxLength = inputs.Select(a => a.Length).Max();

        //Pad all the numbers to the left with zeroes
        var padded = inputs.Select(a => a.PadLeft(maxLength, '0'));

        //Now sort them
        var sorted = padded.OrderBy(a => a);

        foreach (var s in sorted)
        {
            Console.WriteLine(s);
        }
    }
}
</code>```

Body:
8
723
77715926535897932384626433832795

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

Body:
The best option is to use a numeric datatype with greater capacity. The largest numeric datatype is the decimal which has 96 bits of precision (about 28 digits). There are also some other data types that are in between. In general it is best to use the datatype that is just large enough. With floating point data types, beware of loss of precision when there are too many significant digits.

If you are working with numbers so huge they won't fit into any of the numeric data types, you can sort an arbitrarily long integer by padding it with zeroes so they are all the same length.

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var inputs = new string[]
        {
            "77715926535897932384626433832795",
            "8",
            "2398798734",
            "0092",
            "12987981239871928379817231",
            "98279384792873498274908123946109478276492874927864928734872983476928739487298374"
        };

        //Determine the length of the longest number when expressed as a string
        var maxLength = inputs.Select(a => a.Length).Max();

        //Pad all the numbers to the left with zeroes
        var padded = inputs.Select(a => a.PadLeft(maxLength, '0'));

        //Now sort them
        var sorted = padded.OrderBy(a => a);

        foreach (var s in sorted)
        {
            Console.WriteLine(s);
        }
    }
}


问:
is there an API for PHP_CodeSniffer?
Does PHP_CodeSniffer have an API I can use, rather than run the command line?

So given a string of PHP code, $code, and Composer ensuring loading of the PHP_CodeSniffer code, is there something I can do such as:

```<code>// Pseudocode!
$code_sniffer = new PHPCodeSniffer;
$result = $code_sniffer->sniff($code);
</code>```

rather than go via the command line with something like:

```<code>$result = exec(sprintf('echo %s | vendor/bin/phpcs', escapeshellarg($code)));
</code>```

答:
There is, but you need to write more code than that.

Take a look at the example here: https://gist.github.com/gsherwood/aafd2c16631a8a872f0c4a23916962ac

That example allows you to sniff a piece of code that isn't written to a file yet, and set up things like the standard to use (could also be a ruleset.xml file).

Another example, that uses the JS tokenizer instead of PHP + pulls content from an existing file, is available here: https://gist.github.com/gsherwood/f17cfc90f14a9b29eeb6b2e99e6e7f66

It is shorter because it doesn't use as many options.

Title: is there an API for PHP_CodeSniffer?

Body:
Does PHP_CodeSniffer have an API I can use, rather than run the command line?

So given a string of PHP code, $code, and Composer ensuring loading of the PHP_CodeSniffer code, is there something I can do such as:

// Pseudocode!
$code_sniffer = new PHPCodeSniffer;
$result = $code_sniffer->sniff($code);

rather than go via the command line with something like:

$result = exec(sprintf('echo %s | vendor/bin/phpcs', escapeshellarg($code)));


问:
POST data not received on server side
I use Postman (the Chrome app) to send POST data to a URL but the POST data are never received by the PHP file, no matter how I change the content-type before sending. Is there a server setting on Apache that stops post data from external sources?

This is the URL:
http://friendesque.com/arranged/handler.php

And this is the content of the handler.php file:

```<code><?php
     echo("Inside file");

     echo("JSON:");
     $json = file_get_contents('php://input');
     echo($json);

     echo("POST:");
     print_r($_POST);

     echo("GET:");
     print_r($_GET);
?>
</code>```

答: Use file name like /index.php . It will work !! </p>

Title: POST data not received on server side

Body:
I use Postman (the Chrome app) to send POST data to a URL but the POST data are never received by the PHP file, no matter how I change the content-type before sending. Is there a server setting on Apache that stops post data from external sources?

This is the URL:
http://friendesque.com/arranged/handler.php

And this is the content of the handler.php file:

<?php
     echo("Inside file");

     echo("JSON:");
     $json = file_get_contents('php://input');
     echo($json);

     echo("POST:");
     print_r($_POST);

     echo("GET:");
     print_r($_GET);
?>


问:
appendChild function not adding label onto form
I am attempting to input a question and have that question appear as an element within a form, "survey-form". However, when I use JavaScript to append the child node to the "survey-form" the text appears for half a second before disappearing. It seems the label element is appended but then deleted. Any idea on how to fix this?

window.onload = init;

function init() {
  document.getElementById("question-form").addEventListener("submit",
    validateQuestion);
}

function validateQuestion() {
  let questionValue = document.getElementById("question-box").value;
  if (questionValue == "" || questionValue == undefined) {
    alert("Fill the box with information so it can be added to the survey!");
    return;
  } else {
    addQuestion(questionValue);
  }
}

function addQuestion(question) {
  let label = document.createElement("label");
  label.innerHTML = question;

  document.getElementById("survey-form").appendChild(label);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Create Your Own Survey</title>
  <link rel="stylesheet" type="text/css" href="index.css">
  <script type="text/javascript" src="index.js"></script>
</head>

<body>
  <div id="model-side">
    <form id="question-form" method="" action="">
      <label>Create a question for the survey:</label>
      <input id="question-box" type="text" size="35" /><br/>
      <input type="submit" value="Submit Question" />
    </form>
  </div>

  <div id="view-side">
    <form id="survey-form" method="" action="">
      <label>Current View</label>
    </form>
  </div>
</body>

</html></code>```

答:
Just add: event.preventDefault().

The Event interface's preventDefault() method tells the user agent
  that if the event does not get explicitly handled, its default action
  should not be taken as it normally would be. The event continues to
  propagate as usual, unless one of its event listeners calls
  stopPropagation() or stopImmediatePropagation(), either of which
  terminates propagation at once.

Something like this:

window.onload = init;

function init() {
  document.getElementById("question-form").addEventListener("submit",
    validateQuestion);
}

function validateQuestion(event) { // Add event to get the question-form context.
  event.preventDefault(); // Prevent the default action of the question-form in the form submission.
  let questionValue = document.getElementById("question-box").value;
  if (questionValue == "" || questionValue == undefined) {
    alert("Fill the box with information so it can be added to the survey!");
  } else {
    addQuestion(questionValue);
  }
}

function addQuestion(question) {
  let label = document.createElement("label");
  label.innerHTML = question;

  document.getElementById("survey-form").appendChild(label);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Create Your Own Survey</title>
  <link rel="stylesheet" type="text/css" href="index.css">
  <script type="text/javascript" src="index.js"></script>
</head>

<body>
  <div id="model-side">
    <form id="question-form" method="" action="">
      <label>Create a question for the survey:</label>
      <input id="question-box" type="text" size="35" /><br/>
      <input type="submit" value="Submit Question" />
    </form>
  </div>

  <div id="view-side">
    <form id="survey-form" method="" action="">
      <label>Current View</label>
    </form>
  </div>
</body>

</html></code>```

Body:
I am attempting to input a question and have that question appear as an element within a form, "survey-form". However, when I use JavaScript to append the child node to the "survey-form" the text appears for half a second before disappearing. It seems the label element is appended but then deleted. Any idea on how to fix this?

window.onload = init;

function init() {
  document.getElementById("question-form").addEventListener("submit",
    validateQuestion);
}

function validateQuestion() {
  let questionValue = document.getElementById("question-box").value;
  if (questionValue == "" || questionValue == undefined) {
    alert("Fill the box with information so it can be added to the survey!");
    return;
  } else {
    addQuestion(questionValue);
  }
}

function addQuestion(question) {
  let label = document.createElement("label");
  label.innerHTML = question;

  document.getElementById("survey-form").appendChild(label);
}

<!DOCTYPE html>

  <title>Create Your Own Survey</title>
  <link rel="stylesheet" type="text/css" href="index.css">

    <form id="question-form" method="" action="">
      Create a question for the survey:
      <input id="question-box" type="text" size="35" />

      <input type="submit" value="Submit Question" />
    </form>

    <form id="survey-form" method="" action="">
      Current View
    </form>

Body:
Just add: event.preventDefault().

The Event interface's preventDefault() method tells the user agent
  that if the event does not get explicitly handled, its default action
  should not be taken as it normally would be. The event continues to
  propagate as usual, unless one of its event listeners calls
  stopPropagation() or stopImmediatePropagation(), either of which
  terminates propagation at once.

Something like this:

window.onload = init;

function init() {
  document.getElementById("question-form").addEventListener("submit",
    validateQuestion);
}

function validateQuestion(event) { // Add event to get the question-form context.
  event.preventDefault(); // Prevent the default action of the question-form in the form submission.
  let questionValue = document.getElementById("question-box").value;
  if (questionValue == "" || questionValue == undefined) {
    alert("Fill the box with information so it can be added to the survey!");
  } else {
    addQuestion(questionValue);
  }
}

function addQuestion(question) {
  let label = document.createElement("label");
  label.innerHTML = question;

  document.getElementById("survey-form").appendChild(label);
}

<!DOCTYPE html>
<html>

<head>
  <title>Create Your Own Survey</title>
  <link rel="stylesheet" type="text/css" href="index.css">
  <script type="text/javascript" src="index.js"></script>
</head>

<body>
  <div id="model-side">
    <form id="question-form" method="" action="">
      <label>Create a question for the survey:</label>
      <input id="question-box" type="text" size="35" /><br/>
      <input type="submit" value="Submit Question" />
    </form>
  </div>

  <div id="view-side">
    <form id="survey-form" method="" action="">
      <label>Current View</label>
    </form>
  </div>
</body>

</html>


问:
How to move a div's border "up" one pixel with css
I have a div, which I have given a border on top. The border needs to be shifted one pixel higher. Is this possible with CSS.</p>

答:
You can do</p>

```<code>div { position: relative; margin-top: -1px; }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can do

div { position: relative; margin-top: -1px; }


问:
Issue using SAML for authentication with spring boot app
I'm currently reading this article on how to set up SAML with Spring Boot applications.

I followed all the steps and I just changed the Single Sign On URL from "https://localhost:8443/saml/SSO" to "https://localhost:8443/mycompanysaml/SSO".

When I run the application, I see no errors in the IDE console, But the login page of Okta doesn't show on the browser. I have the following message.
Error message in the browser

And the stacktrace of the message in the console is the following :

```<code>2017-11-03 15:21:23.991  INFO 50013 --- [nio-8443-exec-7] o.a.c.c.C[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-11-03 15:21:23.991  INFO 50013 --- [nio-8443-exec-7]o.s.web.servlet.DispatcherServlet        : FrameworkServlet'dispatcherServlet': initialization started
2017-11-03 15:21:24.006  INFO 50013 --- [nio-8443-exec-7]o.s.web.servlet.DispatcherServlet        : FrameworkServlet'dispatcherServlet': initialization completed in 15 ms
2017-11-03 15:21:24.021  INFO 50013 --- [nio-8443-exec-7]o.s.s.s.m.MetadataGeneratorFilter        : No default metadata configured, generating with default values, please pre-configure metadata for production use
2017-11-03 15:21:24.060  INFO 50013 --- [nio-8443-exec-7]o.s.s.s.m.MetadataGeneratorFilter        : Created default metadata for system with entityID: https://localhost:8443/saml/metadata
2017-11-03 15:21:24.708  INFO 50013 --- [nio-8443-exec-7].s.m.p.AbstractReloadingMetadataProvider : New metadata succesfullyloaded for 'https://dev-531605.oktapreview.com/app/exkcp2fsptqmfDGtf0h7/sso/saml/metadata'
2017-11-03 15:21:24.720  INFO 50013 --- [nio-8443-exec-7].s.m.p.AbstractReloadingMetadataProvider : Next refresh cycle for metadata provider 'https://dev-531605.oktapreview.com/app/exkcp2fsptqmfDGtf0h7/sso/saml/metadata' will occur on '2017-11-04T01:21:24.240Z' ('2017-11-03T18:21:24.240-07:00' local time)
2017-11-03 15:21:24.865  INFO 50013 --- [io-8443-exec-10]o.s.security.saml.log.SAMLDefaultLogger:AuthNRequest;SUCCESS;0:0:0:0:0:0:0:1;https://localhost:8443/saml/metadata;http://www.okta.com/exkcp2fsptqmfDGtf0h7;;;
</code>```

Could someone please explain me what going on ? Is it because I changed the Single Sign On URL to my own, it shouldn't be a problem, right ?

Thanks in advance for your help.
G.

答:
The configuration that you setup for SAML in your application will have one spring security filter related to SAML where you have added the filters.

so if you want to change the SSO url then you will have to change the url's in the filters declared in the config file.

For the application that you are referring is using the default configurations.

for more info. http://www.sylvainlemoine.com/2016/06/06/spring-saml2.0-websso-and-jwt-for-mobile-api/ check this

Body:
I'm currently reading this article on how to set up SAML with Spring Boot applications.

I followed all the steps and I just changed the Single Sign On URL from "https://localhost:8443/saml/SSO" to "https://localhost:8443/mycompanysaml/SSO".

When I run the application, I see no errors in the IDE console, But the login page of Okta doesn't show on the browser. I have the following message.
Error message in the browser

And the stacktrace of the message in the console is the following :

2017-11-03 15:21:23.991  INFO 50013 --- [nio-8443-exec-7] o.a.c.c.C[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-11-03 15:21:23.991  INFO 50013 --- [nio-8443-exec-7]o.s.web.servlet.DispatcherServlet        : FrameworkServlet'dispatcherServlet': initialization started
2017-11-03 15:21:24.006  INFO 50013 --- [nio-8443-exec-7]o.s.web.servlet.DispatcherServlet        : FrameworkServlet'dispatcherServlet': initialization completed in 15 ms
2017-11-03 15:21:24.021  INFO 50013 --- [nio-8443-exec-7]o.s.s.s.m.MetadataGeneratorFilter        : No default metadata configured, generating with default values, please pre-configure metadata for production use
2017-11-03 15:21:24.060  INFO 50013 --- [nio-8443-exec-7]o.s.s.s.m.MetadataGeneratorFilter        : Created default metadata for system with entityID: https://localhost:8443/saml/metadata
2017-11-03 15:21:24.708  INFO 50013 --- [nio-8443-exec-7].s.m.p.AbstractReloadingMetadataProvider : New metadata succesfullyloaded for 'https://dev-531605.oktapreview.com/app/exkcp2fsptqmfDGtf0h7/sso/saml/metadata'
2017-11-03 15:21:24.720  INFO 50013 --- [nio-8443-exec-7].s.m.p.AbstractReloadingMetadataProvider : Next refresh cycle for metadata provider 'https://dev-531605.oktapreview.com/app/exkcp2fsptqmfDGtf0h7/sso/saml/metadata' will occur on '2017-11-04T01:21:24.240Z' ('2017-11-03T18:21:24.240-07:00' local time)
2017-11-03 15:21:24.865  INFO 50013 --- [io-8443-exec-10]o.s.security.saml.log.SAMLDefaultLogger:AuthNRequest;SUCCESS;0:0:0:0:0:0:0:1;https://localhost:8443/saml/metadata;http://www.okta.com/exkcp2fsptqmfDGtf0h7;;;

Could someone please explain me what going on ? Is it because I changed the Single Sign On URL to my own, it shouldn't be a problem, right ?

Thanks in advance for your help.
G.


问:
cURL login remote and browse through the site and download
I have a curl script that is used to remote control a login a website. The website has some data in its various menu(links). with this script I can log in to the website but I can not download any data. because after logging in whenever I click any link it logged me out and take me to the login page again.</p>

```<code><?php
$url='';
$login_email = '*******';
$login_pass = '*******';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '$url');
curl_setopt($ch,

 CURLOPT_POSTFIELDS,'identity='.urlencode($login_email).
'&password='.urlencode($l
ogin_pass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
 curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT
5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_setopt($ch, CURLOPT_URL, $url);
$page = curl_exec($ch) or die(curl_error($ch));
echo $page;

?>
</code>```

答:
I think the problem is not on curl.

Try to have session_start(); on all the pages.

Body:
I have a curl script that is used to remote control a login a website. The website has some data in its various menu(links). with this script I can log in to the website but I can not download any data. because after logging in whenever I click any link it logged me out and take me to the login page again.

<?php
$url='';
$login_email = '*******';
$login_pass = '*******';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '$url');
curl_setopt($ch,

 CURLOPT_POSTFIELDS,'identity='.urlencode($login_email).
'&password='.urlencode($l
ogin_pass).'&login=Login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
 curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT
5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_setopt($ch, CURLOPT_URL, $url);
$page = curl_exec($ch) or die(curl_error($ch));
echo $page;

?>


问:
Split At @ in excel
BOS@TOR 11/10/2017 07:00PM ET

LA@TB 11/10/2017 07:00PM ET

Above is data I would like to Split at the @ and not get the @ to show up in my columns.
The First is Away and the Second is Home.

```<code>=LEFT(L2,FIND("@",L2)-1)
=RIGHT(L2,FIND("@",L2)*1)
</code>```

It Returns  Home: TOR, Away: BOS. Perfect! Same With LA AND TB. But If its BOS@LA
it will return HOME @LA and ROAD BOS. How can I just remove the @ regardless of the number of Characters?

答:
Your problem with =RIGHT(L2,FIND("@",L2)) (the "multiply by one" is superfluous, by the way) when you have something like:

```<code>BIGSTRING@X
</code>```

is that the position of the @ depends on the length of BIGSTRING rather than X. The position of the @ is ten and the rightmost ten characters of BIGSTRING@X are not X but rather IGSTRING@X.

This means it will work for something like XYZZY@PLUGH (same size on either side of the @) but not NINECHARS@FOUR (with different sizes).

The first calculation is correct as-is. For the second calculation, you should remove the size of BIGSTRING@ to get the desired number of characters to extract on the right:

```<code>=RIGHT(L2,LEN(L2)-FIND("@",L2))
</code>```

Had Excel been smart enough to offer the variant of the MID formula function where a missing length meant "take remainder of string" (VBA has it), you could have also used =MID(L2,FIND("@",L2)+1).

But, since formula MID appears to need the length, I'd just opt for the RIGHT variant as above.

Title: Split At @ in excel

Body:
BOS@TOR 11/10/2017 07:00PM ET

LA@TB 11/10/2017 07:00PM ET

Above is data I would like to Split at the @ and not get the @ to show up in my columns.
The First is Away and the Second is Home.

=LEFT(L2,FIND("@",L2)-1)
=RIGHT(L2,FIND("@",L2)*1)

It Returns  Home: TOR, Away: BOS. Perfect! Same With LA AND TB. But If its BOS@LA
it will return HOME @LA and ROAD BOS. How can I just remove the @ regardless of the number of Characters?

Body:
Your problem with =RIGHT(L2,FIND("@",L2)) (the "multiply by one" is superfluous, by the way) when you have something like:

BIGSTRING@X

is that the position of the @ depends on the length of BIGSTRING rather than X. The position of the @ is ten and the rightmost ten characters of BIGSTRING@X are not X but rather IGSTRING@X.

This means it will work for something like XYZZY@PLUGH (same size on either side of the @) but not NINECHARS@FOUR (with different sizes).

The first calculation is correct as-is. For the second calculation, you should remove the size of BIGSTRING@ to get the desired number of characters to extract on the right:

=RIGHT(L2,LEN(L2)-FIND("@",L2))

Had Excel been smart enough to offer the variant of the MID formula function where a missing length meant "take remainder of string" (VBA has it), you could have also used =MID(L2,FIND("@",L2)+1).

But, since formula MID appears to need the length, I'd just opt for the RIGHT variant as above.


问:
Change Start of Named Range
I have a single namedRange that (for example) incorrectly starts in Row 5 of Column 1 when it should start in Row 2 (under a header row).

NOTE: In reality I don't know where it 'starts' only that it is somewhere BELOW where it should be.

I am trying to move the namedRange using like this:

```<code>    Set SecondCellInFirstColumnOfNamedRange = Range(rngNames(irng)).Columns(1).Cells(2)
    Set LastCellInFirstColumnOfNamedRange = Range(rngNames(irng)).Columns(1).Cells(RowNumberOfLastCell)
    Range(SecondCellInFirstColumnOfNamedRange, LastCellInFirstColumnOfNamedRange).Name = rngNames(irng)
</code>```

But it just keeps pushing the named range down the page.

What I have been trying to do is this:

find the column index of the first cell

specify the 2nd cell in the column as the start of the namedRange

specify the last used cell in the column as the end of the namedRange

答:
Assuming your named range already ends at the right row, a quick fix would be:

```<code>With Range(rngNames(irng))
    .Offset(-3).Resize(.Rows.Count + 3).Name = rngNames(irng)
End With
</code>```

The principle is to name a range that starts 3 rows above and is 3 rows "longer".

Edit: as per your updated question:

```<code>With Range(rngNames(irng))
    .Worksheet.Range(.Columns(1).EntireColumn.Cells(2, 1), .Cells(.Cells.CountLarge)).Name = rngNames(irng)
End With
</code>```

Note that you shouldn't call Range without it being qualified by its parent, e.g. you should use MyWorksheet.Range(...). This allows you to work free of whatever is active.

Title: Change Start of Named Range

Body:
I have a single namedRange that (for example) incorrectly starts in Row 5 of Column 1 when it should start in Row 2 (under a header row).

NOTE: In reality I don't know where it 'starts' only that it is somewhere BELOW where it should be.

I am trying to move the namedRange using like this:

    Set SecondCellInFirstColumnOfNamedRange = Range(rngNames(irng)).Columns(1).Cells(2)
    Set LastCellInFirstColumnOfNamedRange = Range(rngNames(irng)).Columns(1).Cells(RowNumberOfLastCell)
    Range(SecondCellInFirstColumnOfNamedRange, LastCellInFirstColumnOfNamedRange).Name = rngNames(irng)

But it just keeps pushing the named range down the page.

What I have been trying to do is this:

find the column index of the first cell

specify the 2nd cell in the column as the start of the namedRange

specify the last used cell in the column as the end of the namedRange

Body:
Assuming your named range already ends at the right row, a quick fix would be:

With Range(rngNames(irng))
    .Offset(-3).Resize(.Rows.Count + 3).Name = rngNames(irng)
End With

The principle is to name a range that starts 3 rows above and is 3 rows "longer".

Edit: as per your updated question:

With Range(rngNames(irng))
    .Worksheet.Range(.Columns(1).EntireColumn.Cells(2, 1), .Cells(.Cells.CountLarge)).Name = rngNames(irng)
End With

Note that you shouldn't call Range without it being qualified by its parent, e.g. you should use MyWorksheet.Range(...). This allows you to work free of whatever is active.


问:
How to send a selected (out of many) input values to DB using ajax?
first post so be gentle :)... OK, I'm trying to create a very simple inventory ordering site, but i'm having issues with the following:

Let's say you have (n) items in your inventory, so based on that number i run a 'for' loop and list a hidden input field with an ID of that inventory item and display a button to order. For example:

```<code><form>
for ($i=0; $i<$num_items;$i++)  {
  <input type="hidden" name="item" value="<?=$ID[$i]?>">
  <input type="submit" value="Order" onclick="InsertIntoDB()">
}
</form>
</code>```

Now, lets say a user want to order only 2 item out of 5 in inventory. They would click on corresponding "Order" buttons and the appropriate hidden input values would be send to DB without redirecting (it would be a seamless experience for a user where once the user clicks on buttons they want the page will not reload or redirect). Here's the script that i have for the button click:

```<code><script type="text/javascript">
function InsertIntoDB (){
    var order = $('form input[name="item"]').val();
    $.post('send_to_DB.php', {updateDB:order} ); }
</script>
</code>```

This is what i have for send_to_DB.php file:

```<code>|code for connecting to DB|

$writetoDB=$_POST['uptadeDB'];
foreach ($writetoDB as  $n) {
$insert = "UPDATE `test` SET onorder=1 WHERE ID='$n'";
mysql_query(insert);
}
</code>```

I am struggling to get those 2 values that user clicked into the DB. Any help would be much appreciated, lost many hours of sleep due to this one :). Thanks!!!

答:
Try this out

```<code><form>
 for ($i=0; $i<$num_items;$i++)  {
   //<input type="hidden" name="item" value="<?=$ID[$i]?>">
   <input type="submit" value="Order" onclick="InsertIntoDB(<?=$ID[$i]?>)">
 }
</form>
</code>```

So that in your script you can try this

```<code><script type="text/javascript">
  function InsertIntoDB (order){
    $.post('send_to_DB.php', {updateDB:order} );
  }
</code>```

Where order will now have the value id of the selected order

Body:
first post so be gentle :)... OK, I'm trying to create a very simple inventory ordering site, but i'm having issues with the following:

Let's say you have (n) items in your inventory, so based on that number i run a 'for' loop and list a hidden input field with an ID of that inventory item and display a button to order. For example:

<form>
for ($i=0; $i<$num_items;$i++)  {
  <input type="hidden" name="item" value="<?=$ID[$i]?>">
  <input type="submit" value="Order" onclick="InsertIntoDB()">
}
</form>

Now, lets say a user want to order only 2 item out of 5 in inventory. They would click on corresponding "Order" buttons and the appropriate hidden input values would be send to DB without redirecting (it would be a seamless experience for a user where once the user clicks on buttons they want the page will not reload or redirect). Here's the script that i have for the button click:

This is what i have for send_to_DB.php file:

|code for connecting to DB|

$writetoDB=$_POST['uptadeDB'];
foreach ($writetoDB as  $n) {
$insert = "UPDATE `test` SET onorder=1 WHERE ID='$n'";
mysql_query(insert);
}

I am struggling to get those 2 values that user clicked into the DB. Any help would be much appreciated, lost many hours of sleep due to this one :). Thanks!!!

Body:
Try this out

<form>
 for ($i=0; $i<$num_items;$i++)  {
   //<input type="hidden" name="item" value="<?=$ID[$i]?>">
   <input type="submit" value="Order" onclick="InsertIntoDB(<?=$ID[$i]?>)">
 }
</form>

So that in your script you can try this

<script type="text/javascript">
  function InsertIntoDB (order){
    $.post('send_to_DB.php', {updateDB:order} );
  }

Where order will now have the value id of the selected order


问:
Sum the number of firms in one year
Suppose I have a dataframe as follows:

```<code>dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
 firm year
1   1 2001
2   1 2002
3   1 2003
4   1 2004
5   2 2002
6   3 2002
7   3 2003
8   3 2004
9   4 2002
10  4 2003
11  4 2004
12  4 2005
13  5 2001
14  5 2002
15  6 2001
16  6 2002
</code>```

Now, I hope to sum the number of firms which have exited the market in one year. For example, I want a table like this:

```<code> resulttable
     All 2001 2002 2003 2004 2005
2001   3    0    2    0    1    0
2002   3    0    1    0    1    1
</code>```

The first row of resulttable means that 3 firms entered the market in year 2001 and 2 firms exited in 2003, 1 firm exited in year 2004. Thanks!

答:
You can tabulate "enter" years and "exit" years with table:

```<code>res <- table(
    dt$year[!duplicated(dt$firm)],
    factor(dt$year[!duplicated(dt$firm, fromLast = TRUE)], levels = unique(dt$year))
)
res <- as.data.frame.matrix(res)
res$All <- rowSums(res)

# > res
#      2001 2002 2003 2004 2005 All
# 2001    0    2    0    1    0   3
# 2002    0    1    0    1    1   3
</code>```

I assumed the dt is sorted as provided. If not, one has to sort by year first.

Here is the suggested way from thelatemail in comment, the results look like this:

```<code>addmargins(table(
    dt$year[!duplicated(dt$firm)],
    factor(dt$year[!duplicated(dt$firm, fromLast = TRUE)], levels = unique(dt$year))
), 2)

#      2001 2002 2003 2004 2005 Sum
# 2001    0    2    0    1    0   3
# 2002    0    1    0    1    1   3
</code>```

Title: Sum the number of firms in one year

Body:
Suppose I have a dataframe as follows:

dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
 firm year
1   1 2001
2   1 2002
3   1 2003
4   1 2004
5   2 2002
6   3 2002
7   3 2003
8   3 2004
9   4 2002
10  4 2003
11  4 2004
12  4 2005
13  5 2001
14  5 2002
15  6 2001
16  6 2002

Now, I hope to sum the number of firms which have exited the market in one year. For example, I want a table like this:

 resulttable
     All 2001 2002 2003 2004 2005
2001   3    0    2    0    1    0
2002   3    0    1    0    1    1

The first row of resulttable means that 3 firms entered the market in year 2001 and 2 firms exited in 2003, 1 firm exited in year 2004. Thanks!

Body:
You can tabulate "enter" years and "exit" years with table:

res <- table(
    dt$year[!duplicated(dt$firm)],
    factor(dt$year[!duplicated(dt$firm, fromLast = TRUE)], levels = unique(dt$year))
)
res <- as.data.frame.matrix(res)
res$All <- rowSums(res)

# > res
#      2001 2002 2003 2004 2005 All
# 2001    0    2    0    1    0   3
# 2002    0    1    0    1    1   3

I assumed the dt is sorted as provided. If not, one has to sort by year first.

Here is the suggested way from thelatemail in comment, the results look like this:

addmargins(table(
    dt$year[!duplicated(dt$firm)],
    factor(dt$year[!duplicated(dt$firm, fromLast = TRUE)], levels = unique(dt$year))
), 2)

#      2001 2002 2003 2004 2005 Sum
# 2001    0    2    0    1    0   3
# 2002    0    1    0    1    1   3