问:
Get joined reulst from 2 table and when value not exist any of them, fill with empty value
I have tables clients and partners

Table clients

```<code>company_id | name
------------------
11         | UA prods.
12         | CI corp.
13         | UAC
</code>```

Table partners

```<code>company_id | name
------------------
11         | UA prods.
12         | CI corp.
20         | BDP Group
30         | UFF
</code>```

I need get all company names from both table. When company exists in both tables, then theyr names, when doesn't exist, just leave it empty.

I tried left joins, inner joins but it gives me not what I want.

I want result like this

```<code>clients    | partners
--------------------
UA prods.  | UA prods.
CI corp.   | CI corp.
UAC        |
           | BDP Group
           | UFF
</code>```

答:
So basically the best solution to what you are looking for is FULL OUTER JOIN which is not supported by MySQL.

So in mysql you can do the same thing by this query -

```<code>SELECT clients.name AS clients, partners.name AS partners FROM clients
LEFT JOIN partners ON clients.company_id = partners.company_id
UNION
SELECT clients.name AS clients, partners.name AS partners FROM clients
RIGHT JOIN partners ON clients.company_id = partners.company_id
</code>```

NOTE : Don't use UNION ALL, it will give you a result like this -

```<code>       clients    |  partners
-----------------------------------
       UA prods.  |  UA prods.
       CI corp.   |  CI corp.
       UAC        |  NULL
       UA prods.  |  UA prods.
       CI corp.   |  CI corp.
       NULL       |  BDP Group
       NULL       |  UFF
</code>```

Body:
I have tables clients and partners

Table clients

company_id | name
------------------
11         | UA prods.
12         | CI corp.
13         | UAC

Table partners

company_id | name
------------------
11         | UA prods.
12         | CI corp.
20         | BDP Group
30         | UFF

I need get all company names from both table. When company exists in both tables, then theyr names, when doesn't exist, just leave it empty.

I tried left joins, inner joins but it gives me not what I want.

I want result like this

clients    | partners
--------------------
UA prods.  | UA prods.
CI corp.   | CI corp.
UAC        |
           | BDP Group
           | UFF

Body:
So basically the best solution to what you are looking for is FULL OUTER JOIN which is not supported by MySQL.

So in mysql you can do the same thing by this query -

SELECT clients.name AS clients, partners.name AS partners FROM clients
LEFT JOIN partners ON clients.company_id = partners.company_id
UNION
SELECT clients.name AS clients, partners.name AS partners FROM clients
RIGHT JOIN partners ON clients.company_id = partners.company_id

NOTE : Don't use UNION ALL, it will give you a result like this -

       clients    |  partners
-----------------------------------
       UA prods.  |  UA prods.
       CI corp.   |  CI corp.
       UAC        |  NULL
       UA prods.  |  UA prods.
       CI corp.   |  CI corp.
       NULL       |  BDP Group
       NULL       |  UFF


来源: stackexchange

问:
Your branch is ahead of 'origin/master' by 3 commits
I am getting the following when running git status

```<code>Your branch is ahead of 'origin/master' by 3 commits.
</code>```

I have read on some other post the way to fix this is run git pull --rebase but what exactly is rebase, will I lose data or is this simple way to sync with master?

答:
This happened to me once after I merged a pull request on Bitbucket.

I just had to do:

git fetch

My problem was solved. I hope this helps!!!

ContentLicense: CC BY-SA 3.0

Body:
I am getting the following when running git status

Your branch is ahead of 'origin/master' by 3 commits.

I have read on some other post the way to fix this is run git pull --rebase but what exactly is rebase, will I lose data or is this simple way to sync with master?

ContentLicense: CC BY-SA 4.0


问:
What does sCount=2 dsCount=1 mean in android ANR file?
I have some problem with an ANR files, I got a SUSPENDED lable in main thread,
somebody say the reason maybe GC , Debugger, infinite loop, so I have try Debugger and infinite loop, and I got the SUSPENDED , but the difference is when I use Debugger to get ANR, I got sCount=2 dsCount=1, and when I use infinite loop to get ANR, i got sCount=1 dsCount=0..
so What does it mean in an ANR file?

Following is the screenshot of the ANR

答:
As you can judge from sources:

```<code>dvmPrintDebugMessage(target, " | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p
                     self=%p\n",
                     groupName, thread->suspendCount, thread->dbgSuspendCount,
                     thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);
</code>```

So, to answer your question:

sCount stands for thread->suspendCount, dsCount stands for thread->dbgSuspendCount.

Body:
As you can judge from sources:

dvmPrintDebugMessage(target, " | group=\"%s\" sCount=%d dsCount=%d s=%c obj=%p
                     self=%p\n",
                     groupName, thread->suspendCount, thread->dbgSuspendCount,
                     thread->isSuspended ? 'Y' : 'N', thread->threadObj, thread);

So, to answer your question:

sCount stands for thread->suspendCount, dsCount stands for thread->dbgSuspendCount.


问:
Checking character value in a loop
```<code>package Medium;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Scanner;

public class Demo3 {
    public static void main(String[] args) {
        int sum = 0;
        System.out.println("please input a num:");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        ArrayList<String> arr = new ArrayList<String>();
        for(int i =0;i<=num;i++){
            String s = Integer.toString(i);         //get all the numbers changed into String type
            arr.add(i, s);
            //System.out.println(arr);
        }

        for(int j=0;j<arr.size();j++){
            String t = arr.get(j);
            System.out.println(t+"----------");
            for(int k =0;k<t.length();k++){         //go through all the nums
                System.out.println(t.charAt(k));
                if(t.charAt(k)==(char)(1)){         //this line may possible be wrong?
                    sum = sum+1;//none of the sum be added
                    System.out.println("sum:"+sum);
                }else{
                    break;
                }
            }
            System.out.println(sum);
        }
    }
}
</code>```

input 11,the outcome is:

```<code>please input a num:
11
0----------
0
1----------
1
2----------
2
3----------
3
4----------
4
5----------
5
6----------
6
7----------
7
8----------
8
9----------
9
10----------
1
11----------
1
0
</code>```

the description is: Count the number of k's between 0 and n. k can be 0 - 9.

none of the sum is being used, why is that?
I though it may probably come up for if(t.charAt(k) == (char)(1))?

答:
You are right.

```<code>if(t.charAt(k)==(char)(1)){
</code>```

must be

```<code>if(t.charAt(k)=='1'){
</code>```

(char)(1) is the character at posion one in the charset, not the number 1 as character.

You see the difference if you test it in a program with:

```<code>System.out.println((char)(1));
System.out.println('1');
</code>```

or you can see it using the hex code:

```<code>System.out.println(String.format("Hex code of (char)1 %04x", (int) (char)1));
System.out.println(String.format("Hex code of '1' %04x", (int) '1'));
</code>```

Output is

```<code>Hex code of (char)1 0001
Hex code of '1' 0031
</code>```

Title: Checking character value in a loop

Body:
package Medium;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Scanner;

public class Demo3 {
    public static void main(String[] args) {
        int sum = 0;
        System.out.println("please input a num:");
        Scanner in = new Scanner(System.in);
        int num = in.nextInt();
        ArrayList<String> arr = new ArrayList<String>();
        for(int i =0;i<=num;i++){
            String s = Integer.toString(i);         //get all the numbers changed into String type
            arr.add(i, s);
            //System.out.println(arr);
        }

        for(int j=0;j<arr.size();j++){
            String t = arr.get(j);
            System.out.println(t+"----------");
            for(int k =0;k<t.length();k++){         //go through all the nums
                System.out.println(t.charAt(k));
                if(t.charAt(k)==(char)(1)){         //this line may possible be wrong?
                    sum = sum+1;//none of the sum be added
                    System.out.println("sum:"+sum);
                }else{
                    break;
                }
            }
            System.out.println(sum);
        }
    }
}

input 11,the outcome is:

please input a num:
11
0----------
0
1----------
1
2----------
2
3----------
3
4----------
4
5----------
5
6----------
6
7----------
7
8----------
8
9----------
9
10----------
1
11----------
1
0

the description is: Count the number of k's between 0 and n. k can be 0 - 9.

none of the sum is being used, why is that?
I though it may probably come up for if(t.charAt(k) == (char)(1))?

Body:
You are right.

if(t.charAt(k)==(char)(1)){

must be

if(t.charAt(k)=='1'){

(char)(1) is the character at posion one in the charset, not the number 1 as character.

You see the difference if you test it in a program with:

System.out.println((char)(1));
System.out.println('1');

or you can see it using the hex code:

System.out.println(String.format("Hex code of (char)1 %04x", (int) (char)1));
System.out.println(String.format("Hex code of '1' %04x", (int) '1'));

Output is

Hex code of (char)1 0001
Hex code of '1' 0031


问:
Error while listing directories recursively on C:\ drive
I’m trying to list every file, including dll, exe, driver list, etc on my windows system using PowerShell.

The following gives me list of only the particular folder called "Users"

```<code>Get-ChildItem C:\Users -Recurse | Select-Object DirectoryName,Name |Where { $_.DirectoryName -ne $NULL } | Export-CSV C:\Filelist.csv
</code>```

It gives the list of files in only Users folder and I get error when I try to list all files under C Drive using the following command as per my aim:

```<code>Get-ChildItem C:\ -Recurse | Select-Object DirectoryName,Name | Where { $_.DirectoryName -ne $NULL } | Export-CSV C:\Filelist.csv
</code>```

I receive this error:

```<code>ERROR : Get-ChildItem : Access to the path ‘C:\Windows\CSC\v2.0.6’ is denied.
At line:1 char:14
+ Get-Childitem <<<< C:\ -Recurse | Select-Object DirectoryName,Name | Where { $_.DirectoryName -ne $NULL } | Export-CSV C:\Filelist.csv
    + CategoryInfo : PermissionDenied: (C:\Windows\CSC\v2.0.6:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
</code>```

How do I list the entire C drive or all files including dll, scripts, exe s on my system and export to a CSV file?

答:
You have to execute your script as admin. Also you can omit the error message for files you don't have access to using the -ErrorAction common parameter:

```<code>Get-ChildItem C:\ -Recurse -ErrorAction SilentlyContinue |
    Select-Object DirectoryName,Name |
    Where { $_.DirectoryName -ne $NULL } |
    Export-CSV C:\Filelist.csv
</code>```

Body:
I’m trying to list every file, including dll, exe, driver list, etc on my windows system using PowerShell.

The following gives me list of only the particular folder called "Users"

Get-ChildItem C:\Users -Recurse | Select-Object DirectoryName,Name |Where { $_.DirectoryName -ne $NULL } | Export-CSV C:\Filelist.csv

It gives the list of files in only Users folder and I get error when I try to list all files under C Drive using the following command as per my aim:

Get-ChildItem C:\ -Recurse | Select-Object DirectoryName,Name | Where { $_.DirectoryName -ne $NULL } | Export-CSV C:\Filelist.csv

I receive this error:

ERROR : Get-ChildItem : Access to the path ‘C:\Windows\CSC\v2.0.6’ is denied.
At line:1 char:14
+ Get-Childitem <<<< C:\ -Recurse | Select-Object DirectoryName,Name | Where { $_.DirectoryName -ne $NULL } | Export-CSV C:\Filelist.csv
    + CategoryInfo : PermissionDenied: (C:\Windows\CSC\v2.0.6:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

How do I list the entire C drive or all files including dll, scripts, exe s on my system and export to a CSV file?

Body:
You have to execute your script as admin. Also you can omit the error message for files you don't have access to using the -ErrorAction common parameter:

Get-ChildItem C:\ -Recurse -ErrorAction SilentlyContinue |
    Select-Object DirectoryName,Name |
    Where { $_.DirectoryName -ne $NULL } |
    Export-CSV C:\Filelist.csv


问:
Get Camunda TaskID after creation in response
We are using Camunda for our approval process implementation in our application.
We created a BPMN process with human Task service. We are using the below URL

```<code>engine-rest/engine/default/process-definition/key/processKey/start
</code>```

we pass our form parameters as input to this service

```<code>{
"variables": {
"requestId" : {"value" : "xxxxx", "type" : "String"},
"catalog" : {"value" : "yyyy", "type" : "String"},
"businessReason": {"value":"yyyyy","type":"String"},
"link": {"value":"","type":"String"}
}
}
</code>```

The response of this start task is below-

```<code>{
  "links": [
{
  "method": "GET",
  "href": "http://localhost:8080/engine-rest/engine/default/process-instance/31701",
  "rel": "self"
}
  ],
  "id": "31701",
  "definitionId": "xxxxx:7:31605",
  "businessKey": null,
  "caseInstanceId": null,
  "ended": false,
  "suspended": false,
  "tenantId": null
}
</code>```

The id in the response is not the actual task ID which we use to get the task details etc instead its the execution ID.

Is there a way to get the task id back in the response.? Also can we add some parameteres to the above response. Like

```<code>"status" : "success"
</code>```

I am having listener class created for the Human task but not sure how to add response parameters . Any help is appreciated

答: This is not possible unless you build a custom REST resource on top of Camunda's Java API. See https://docs.camunda.org/manual/7.6/reference/rest/overview/embeddability/ for info how you would embed the default REST resources into a custom JAX-RS application.</p>

Body:
We are using Camunda for our approval process implementation in our application.
We created a BPMN process with human Task service. We are using the below URL

engine-rest/engine/default/process-definition/key/processKey/start

we pass our form parameters as input to this service

{
"variables": {
"requestId" : {"value" : "xxxxx", "type" : "String"},
"catalog" : {"value" : "yyyy", "type" : "String"},
"businessReason": {"value":"yyyyy","type":"String"},
"link": {"value":"","type":"String"}
}
}

The response of this start task is below-

{
  "links": [
{
  "method": "GET",
  "href": "http://localhost:8080/engine-rest/engine/default/process-instance/31701",
  "rel": "self"
}
  ],
  "id": "31701",
  "definitionId": "xxxxx:7:31605",
  "businessKey": null,
  "caseInstanceId": null,
  "ended": false,
  "suspended": false,
  "tenantId": null
}

The id in the response is not the actual task ID which we use to get the task details etc instead its the execution ID.

Is there a way to get the task id back in the response.? Also can we add some parameteres to the above response. Like

"status" : "success"

I am having listener class created for the Human task but not sure how to add response parameters . Any help is appreciated


问:
Java ArrayList Index
```<code>int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");
</code>```

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana

答: Exactly as arrays in all C-like languages. The indexes start from 0. So, apple is 0, banana is 1, orange is 2 etc.</p>

ContentLicense: CC BY-SA 2.5

Title: Java ArrayList Index

Body:
int[] alist = new int [3];
alist.add("apple");
alist.add("banana");
alist.add("orange");

Say that I want to use the second item in the ArrayList. What is the coding in order to get the following output?

output:

banana


问:
Protractor: Testing ui-bootstrap tooltip on IE
Using Protractor to test that a tooltip (using ui-bootstrap directive) shows up, I found out that if there is a delay to show up the tooltip then IE gets stuck when the mouse is moved on the element that should trigger the tooltip.

HTML

```<code><div id="trigger" tooltip-popup-delay="500" tooltip="Tooltip content...">Lorem ipsum</div>
</code>```

JS test code

```<code>browser.driver.actions().mouseMove(element(by.id('trigger'))).perform()
  .then(function (){
    browser.sleep('500');
    expect(element(by.id('trigger')).element(by.css('.tooltip')).isDisplayed()).toBeTruthy();
  });
</code>```

Removing the tooltip-popup-delay attribute makes the test pass and if I'm right right it's because IE WebDriver achieves hovering "by continuously firing mouse over events at the last location the mouse cursor has been moved to" (see enablePersistentHover option explanation here) and then protractor is waiting forever as each mouseover triggers a $timeout.

Every works fine testing on Chrome/Firefox.

My question then is:
Is there a way to do a proper hovering using protractor/IE WebDriver that could make this test pass even with a tooltip that have a delay to show up ?

答:
Unfortunately suggested by @alecxe not worked for me.
After a few hours I tried to resolve the problem only by using manual triggering of the mouse hover event, but it's actually not that easy as looks.
I've wrote something like:

```<code>browser.executeScript("
  var event = document.createEvent('MouseEvent');
  event.initMouseEvent('mouseover',true,true,window,0,0,0,0,0,false,false,false,false,0,null);
  arguments[0].dispatchEvent(event);", elm.getWebElement()
)
browser.wait(protractor.ExpectedConditions.presenceOf(elm), tooltipDelay);
browser.actions().mouseMove(elm, {x:5, y:5}).perform()
</code>```

First part triggers IE event for hover, after it protractor waits until element will be present and after triggers normal protractor hover - otherwise it can be a problem, that tooltip will never dissappear.
Offset 5px I've used to place the cursor in the middle of element, not sure if it'll be needed for other cases.

That's not a solution, but possibly someone can use it as a source of motivation during the fight with IE.

Body:
Using Protractor to test that a tooltip (using ui-bootstrap directive) shows up, I found out that if there is a delay to show up the tooltip then IE gets stuck when the mouse is moved on the element that should trigger the tooltip.

HTML

Lorem ipsum

JS test code

browser.driver.actions().mouseMove(element(by.id('trigger'))).perform()
  .then(function (){
    browser.sleep('500');
    expect(element(by.id('trigger')).element(by.css('.tooltip')).isDisplayed()).toBeTruthy();
  });

Removing the tooltip-popup-delay attribute makes the test pass and if I'm right right it's because IE WebDriver achieves hovering "by continuously firing mouse over events at the last location the mouse cursor has been moved to" (see enablePersistentHover option explanation here) and then protractor is waiting forever as each mouseover triggers a $timeout.

Every works fine testing on Chrome/Firefox.

My question then is:
Is there a way to do a proper hovering using protractor/IE WebDriver that could make this test pass even with a tooltip that have a delay to show up ?

Body:
Unfortunately suggested by @alecxe not worked for me.
After a few hours I tried to resolve the problem only by using manual triggering of the mouse hover event, but it's actually not that easy as looks.
I've wrote something like:

browser.executeScript("
  var event = document.createEvent('MouseEvent');
  event.initMouseEvent('mouseover',true,true,window,0,0,0,0,0,false,false,false,false,0,null);
  arguments[0].dispatchEvent(event);", elm.getWebElement()
)
browser.wait(protractor.ExpectedConditions.presenceOf(elm), tooltipDelay);
browser.actions().mouseMove(elm, {x:5, y:5}).perform()

First part triggers IE event for hover, after it protractor waits until element will be present and after triggers normal protractor hover - otherwise it can be a problem, that tooltip will never dissappear.
Offset 5px I've used to place the cursor in the middle of element, not sure if it'll be needed for other cases.

That's not a solution, but possibly someone can use it as a source of motivation during the fight with IE.


问:
Visual studio Code - prevent same file opening twice

It's happened a few times before that I've opened the same file twice and forgotten about it. Meaning I was editing the same file in both panes, which means two versions of the same file. This led to bugs and me not understanding why me code was not being run properly.

Is there a setting which prevents having the same file open twice?

答:
Update v1.11.0 - March 2017

I submitted this PR, and you can now use the setting:

"workbench.editor.revealIfOpen": true
```


问:
JMeter saving test results into file. CLI
I added 'Simple Data Writer' to my test plan with the next filename path:

```<code>${__time(Y-MM-dd)}/${__time(HH-mm)}.jtl
</code>```

It works perfectly when I run script from UI but not from command line (script doesn't create folder and saves results into incorrectly named file).

Any ideas how to create folder with date in the name and time in name of .jtl file using Simple Data Writer ?

I'm using windows 10.

Thank you

答:
Define results file location using __P() function like:

```<code>${__P(date,)}/${__P(time,)}.jtl
</code>```

Create a batch file to run your JMeter script which will define these date and time properties using current system date and time via -J command line argument. Example code (you might need to amend it to correspond your operating system regional settings like short date format)

```<code>@echo off
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set testdate=%%c-%%b-%%a)
For /f "tokens=1-2 delims=/:/ " %%a in ('time /t') do (set testtime=%%a-%%b)
jmeter.bat -Jdate=%testdate% -Jtime=%testtime% -n -t test.jmx
</code>```

Run JMeter test using above batch file - the listener should create the relevant folder and .jtl results file.

See Apache JMeter Properties Customization Guide to learn more about JMeter properties and ways of setting, reading and overriding them.

Body:
I added 'Simple Data Writer' to my test plan with the next filename path:

${__time(Y-MM-dd)}/${__time(HH-mm)}.jtl

It works perfectly when I run script from UI but not from command line (script doesn't create folder and saves results into incorrectly named file).

Any ideas how to create folder with date in the name and time in name of .jtl file using Simple Data Writer ?

I'm using windows 10.

Thank you

Body:
Define results file location using __P() function like:

${__P(date,)}/${__P(time,)}.jtl

Create a batch file to run your JMeter script which will define these date and time properties using current system date and time via -J command line argument. Example code (you might need to amend it to correspond your operating system regional settings like short date format)

@echo off
For /f "tokens=1-4 delims=/ " %%a in ('date /t') do (set testdate=%%c-%%b-%%a)
For /f "tokens=1-2 delims=/:/ " %%a in ('time /t') do (set testtime=%%a-%%b)
jmeter.bat -Jdate=%testdate% -Jtime=%testtime% -n -t test.jmx

Run JMeter test using above batch file - the listener should create the relevant folder and .jtl results file.

See Apache JMeter Properties Customization Guide to learn more about JMeter properties and ways of setting, reading and overriding them.


问:
How to set up a rebase in Git Bash on Windows
I'm trying to following the instructions on https://help.github.com/articles/using-git-rebase-on-the-command-line/ for interactively rebasing from my initial commit (More specifically, I'm trying to remove all the bin and obj folders from the history). So once I type in

```<code>git rebase -i --root
</code>```

I get the following screen as expected, but then I can't figure out how to change the first one to edit. Like I can't figure out which button on the keyboard to click. Sorry if this is a stupid question.

答:
Thats pretty easy. You have to change the word pick to edit
Then you save the file, in your case press ESC and then type :wq. Then git will start the rebase and you will stop on each commit you want to edit.

Edit: If you don't know how to insert in vim: press ESC and then i after that you are in insert-mode and as soon as you are finished with typing press ESC again and save it as described above.

Body:
I'm trying to following the instructions on https://help.github.com/articles/using-git-rebase-on-the-command-line/ for interactively rebasing from my initial commit (More specifically, I'm trying to remove all the bin and obj folders from the history). So once I type in

git rebase -i --root

I get the following screen as expected, but then I can't figure out how to change the first one to edit. Like I can't figure out which button on the keyboard to click. Sorry if this is a stupid question.


问:
aspnet core how to webpack build on deploy
I have a aspnet core application with a vue.js part, which I build with webpack and everything works fine.
Now I search a solution to create a productionbuild with it, to create a minified version of my vue bundle and to run vue in production mode (without console.logs), which I set in my webpack.config like:

```<code>if (process.env.NODE_ENV === 'production') {
    module.exports.plugins = [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]
} else {
    module.exports.devtool = '#source-map'
}
</code>```

but process.env.NODE_ENV is always undefined when I webpack it via gulp.
Than I tried to use Microsoft.AspNetCore.SpaServices with this line in startup.cs:

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
    if(env.IsDevelopment())
        app.UseWebpackDevMiddleware();
...
}
</code>```

This works also fine like my gulp configuration and process.env.NODE_ENV property is set to 'development'

Now I try to create a production build in VS 2017 (Build -> Publish Projectname), but no webpack task runs.

So i tried to add this in my *.csproj:

```<code><Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <Exec Command="npm run build" />
</Target>
</code>```

this throws the error: The command "npm run build" exited with code 1.

Now I'm out of other ideas to resolve it and hope that anyone can help me. THX!

答:
Resolved using:
in .csproj:

```<code><Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <Exec Command="npm install" />
    <Exec Command="npm run production" />
</Target>
</code>```

and adding scripts in my package.json:

```<code>"scripts": {
    "dev": "cross-env NODE_ENV=development webpack --hide-modules",
    "production": "cross-env NODE_ENV=production webpack --hide-modules"
}
</code>```

this needs webpack & cross-env packages (and all other used packages during webpack) installed & a working webpack.config.js

Ask if someone is interrested to my webpack.config.js or some other code

Body:
I have a aspnet core application with a vue.js part, which I build with webpack and everything works fine.
Now I search a solution to create a productionbuild with it, to create a minified version of my vue bundle and to run vue in production mode (without console.logs), which I set in my webpack.config like:

if (process.env.NODE_ENV === 'production') {
    module.exports.plugins = [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        })
    ]
} else {
    module.exports.devtool = '#source-map'
}

but process.env.NODE_ENV is always undefined when I webpack it via gulp.
Than I tried to use Microsoft.AspNetCore.SpaServices with this line in startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
    if(env.IsDevelopment())
        app.UseWebpackDevMiddleware();
...
}

This works also fine like my gulp configuration and process.env.NODE_ENV property is set to 'development'

Now I try to create a production build in VS 2017 (Build -> Publish Projectname), but no webpack task runs.

So i tried to add this in my *.csproj:

<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <Exec Command="npm run build" />
</Target>

this throws the error: The command "npm run build" exited with code 1.

Now I'm out of other ideas to resolve it and hope that anyone can help me. THX!

Body:
Resolved using:
in .csproj:

<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <Exec Command="npm install" />
    <Exec Command="npm run production" />
</Target>

and adding scripts in my package.json:

"scripts": {
    "dev": "cross-env NODE_ENV=development webpack --hide-modules",
    "production": "cross-env NODE_ENV=production webpack --hide-modules"
}

this needs webpack & cross-env packages (and all other used packages during webpack) installed & a working webpack.config.js

Ask if someone is interrested to my webpack.config.js or some other code


问:
Dynamic ng-click along with $compile fires click event two times on single click
I have added dynamic HTML containing a div tag.

And I have bound ng-click to it dynamically as:

```<code>$('#likePulseButton' + item.nid).attr('ng-click', 'likePulseObject(' + item.nid + ')');
</code>```

After this, I have compiled it as:

```<code>$compile($('#likePulseButton' + item.nid))($scope);
</code>```

But when we click on this element, it fires click event two times, even if we have clicked only once.

Some help would be really appreciable.

Thanks in advance.

答:
Even I got stuck once doing something similar

After trying different things I realized ng-click which is already compile is compiled a second time when $compile($('#likePulseButton' + item.nid))($scope); is called.

To resolve this issue, only need to compile the altered/affected elements i.e var elem= $compile($('#likePulseButton' + item.nid);

by replacing $compile($('#likePulseButton' + item.nid))($scope); with $compile(elem)(scope);

According to docs

Double compilation occurs when an already compiled part of the DOM gets compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues, and memory leaks. Refer to the Compiler Guide section on double compilation for an in-depth explanation and ways to avoid it.

Check this docs for more.

Body:
I have added dynamic HTML containing a div tag.

And I have bound ng-click to it dynamically as:

$('#likePulseButton' + item.nid).attr('ng-click', 'likePulseObject(' + item.nid + ')');

After this, I have compiled it as:

$compile($('#likePulseButton' + item.nid))($scope);

But when we click on this element, it fires click event two times, even if we have clicked only once.

Some help would be really appreciable.

Thanks in advance.


答:
In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:</p>

```<code>ArrayList<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");

System.out.println( alist.get(1) );
</code>```

Title: Java ArrayList Index

Body:
In order to store Strings in an dynamic array (add-method) you can't define it as an array of integers ( int[3] ). You should declare it like this:

ArrayList<String> alist = new ArrayList<String>();
alist.add("apple");
alist.add("banana");
alist.add("orange");

System.out.println( alist.get(1) );


问:
Look through every items in array(A) and check if it allready exsists in another array(B)
I have two arrays(arrayA & arrayB). I want to check if any of the items in arrayA allready exists in arrayB. if it doesn't I want to add it to arrayB(but that's not the problem). In the exampel I just want to console.log that I'm adding the item to array B.

First I thought this was a good idea:

```<code> for(var i = 0; i < arrayA.length; i++){
        for (var j = 0; j < arrayB.length; j++) {
            if(body[i].id == res[j].name){
                console.log("The article allready exsists")
            }
            else{
                console.log("Adding item to arrayB")
            }

      }

      }
</code>```

Then I realised that this wasn't a verry good way to do it because the array's are pretty big. Also the else-statement will be ran the number of times equal to the length of arrayA. Also It's a problem because the first time this will run the array length of arrayB will be zero and wont even reach the else-statement.

Is their any other ways to achive what I'm trying to do here?

答:
May be this could help. You donot need nested loops for achieving this.</p>

```<code> var arrayA = [1,2,3,4,5,6];
 var arrayB = [2,4,7,8];
 for(var i = 0; i < arrayA.length; i++){
       if(arrayB.indexOf(arrayA[i]) > -1){
            console.log("The article allready exsists");
         }
         else{
             console.log("Adding item to arrayB")
         }
   }
</code>```

Body:
I have two arrays(arrayA & arrayB). I want to check if any of the items in arrayA allready exists in arrayB. if it doesn't I want to add it to arrayB(but that's not the problem). In the exampel I just want to console.log that I'm adding the item to array B.

First I thought this was a good idea:

 for(var i = 0; i < arrayA.length; i++){
        for (var j = 0; j < arrayB.length; j++) {
            if(body[i].id == res[j].name){
                console.log("The article allready exsists")
            }
            else{
                console.log("Adding item to arrayB")
            }

      }

      }

Then I realised that this wasn't a verry good way to do it because the array's are pretty big. Also the else-statement will be ran the number of times equal to the length of arrayA. Also It's a problem because the first time this will run the array length of arrayB will be zero and wont even reach the else-statement.

Is their any other ways to achive what I'm trying to do here?

Body:
May be this could help. You donot need nested loops for achieving this.

 var arrayA = [1,2,3,4,5,6];
 var arrayB = [2,4,7,8];
 for(var i = 0; i < arrayA.length; i++){
       if(arrayB.indexOf(arrayA[i]) > -1){
            console.log("The article allready exsists");
         }
         else{
             console.log("Adding item to arrayB")
         }
   }


问:
translate() takes exactly one argument (2 given) in python error
```<code>import os
import re

def rename_files():
    # get the files from dir
    file_list=os.listdir(r"C:\OOP\prank")
    print(file_list)
    saved_path=os.getcwd()
    print("current working directory"+saved_path)
    os.chdir(r"C:\OOP\prank")
    #rename the files
    for file_name in file_list:
        print("old name-"+file_name)
        #print("new name-"+file_name.strip("0123456789"))
        os.rename(file_name,file_name.translate(None,"0123456789"))
        os.chdir(saved_path)

rename_files()
</code>```

Here error is showing due to translate line ...help me what to do next ..I am using translate to remove the digit from filename.

```<code>Traceback (most recent call last):
    File "C:\Users\vikash\AppData\Local\Programs\Python\Python35-  32\pythonprogram\secretName.py", line 17, in <module>
rename_files()
      File "C:\Users\vikash\AppData\Local\Programs\Python\Python35-  32\pythonprogram\secretName.py", line 15, in rename_files
     os.rename(file_name,file_name.translate(None,"0123456789"))
     TypeError: translate() takes exactly one argument (2 given)
</code>```

答:
Higher versions in Python use this :

```<code>eg: oldname= "delhi123"
remove="1234567890"
table=str.maketrans("","",remove)
oldname.translate(table)
</code>```

Overall solution for your query:

```<code>import os

def rename_file_names():
    file_list=os.listdir(r"C:\Users\welcome\Downloads\Compressed\prank")
    print (file_list)
    saved_path=os.getcwd()
    print("current working direcorty is"+saved_path)
    os.chdir(r"C:\Users\welcome\Downloads\Compressed\prank")
    remove="123456789"
    table=str.maketrans("","",remove)
    for file_name in file_list:
        os.rename(file_name,file_name.translate(table))

rename_file_names()
</code>```

Body:
import os
import re

def rename_files():
    # get the files from dir
    file_list=os.listdir(r"C:\OOP\prank")
    print(file_list)
    saved_path=os.getcwd()
    print("current working directory"+saved_path)
    os.chdir(r"C:\OOP\prank")
    #rename the files
    for file_name in file_list:
        print("old name-"+file_name)
        #print("new name-"+file_name.strip("0123456789"))
        os.rename(file_name,file_name.translate(None,"0123456789"))
        os.chdir(saved_path)

rename_files()

Here error is showing due to translate line ...help me what to do next ..I am using translate to remove the digit from filename.

Traceback (most recent call last):
    File "C:\Users\vikash\AppData\Local\Programs\Python\Python35-  32\pythonprogram\secretName.py", line 17, in <module>
rename_files()
      File "C:\Users\vikash\AppData\Local\Programs\Python\Python35-  32\pythonprogram\secretName.py", line 15, in rename_files
     os.rename(file_name,file_name.translate(None,"0123456789"))
     TypeError: translate() takes exactly one argument (2 given)

Body:
Higher versions in Python use this :

eg: oldname= "delhi123"
remove="1234567890"
table=str.maketrans("","",remove)
oldname.translate(table)

Overall solution for your query:

import os

def rename_file_names():
    file_list=os.listdir(r"C:\Users\welcome\Downloads\Compressed\prank")
    print (file_list)
    saved_path=os.getcwd()
    print("current working direcorty is"+saved_path)
    os.chdir(r"C:\Users\welcome\Downloads\Compressed\prank")
    remove="123456789"
    table=str.maketrans("","",remove)
    for file_name in file_list:
        os.rename(file_name,file_name.translate(table))

rename_file_names()


问:
Construct callable function from string
How to construct and call a function from a string?
For example, consider three different functions and a list of strings, I want to be able to use the items in list of strings to construct and call the appropriate function</p>

```<code>def do_function1():
    return 'done function1'

def do_function2():
    return 'done function2'

def do_function3():
    return 'done function3'

listOfstr = ['function1','function2','function3']

for item in listOfstr:
    result = 'do_'+item()
    print(result)

result = 'do_'+item()
TypeError: 'str' object is not callable
</code>```

答:
First of all, usually you won't need this. Instead of putting strings in a list, you can also put functions themselves in a list like this:

```<code>def do_function1():
    return 'done function1'

def do_function2():
    return 'done function2'

def do_function3():
    return 'done function3'

list_of_functions = [do_function1, do_function2, do_function3]

for item in list_of_functions:
    result = item()
    print(result)
</code>```

However, if you insist, you can do it like this:

```<code>locals()["do_function1"]()
</code>```

locals() gives you a dictionary of locally defined objects by name.

Title: Construct callable function from string

Body:
How to construct and call a function from a string?
For example, consider three different functions and a list of strings, I want to be able to use the items in list of strings to construct and call the appropriate function

def do_function1():
    return 'done function1'

def do_function2():
    return 'done function2'

def do_function3():
    return 'done function3'

listOfstr = ['function1','function2','function3']

for item in listOfstr:
    result = 'do_'+item()
    print(result)

result = 'do_'+item()
TypeError: 'str' object is not callable

Body:
First of all, usually you won't need this. Instead of putting strings in a list, you can also put functions themselves in a list like this:

def do_function1():
    return 'done function1'

def do_function2():
    return 'done function2'

def do_function3():
    return 'done function3'

list_of_functions = [do_function1, do_function2, do_function3]

for item in list_of_functions:
    result = item()
    print(result)

However, if you insist, you can do it like this:

locals()["do_function1"]()

locals() gives you a dictionary of locally defined objects by name.


问:
Multiple SKSpriteNodes as one Node in Swift
I'm trying to create a simplified Dr. Mario like game where I have a pill shaped object, each half with their own color.

The pills can be stacked on top of each other and I need to find out via collision detection if two similar colors have collided.

What I tried

I created an SKSpriteNode subclass where I generated half of the pill with its color and spawned two in my scene. I positioned them near each other and created a fixed joint between them. The problem is that I couldn't rotate them as if they were a single Node (there's an open question regardin this issue)

I created two SKSpriteNode subclasses. The first one is just like the one above, returning half a pill, but instead of getting called from the scene, these get called from the second subclass, which returns the pill as a single node into the scene. In this scenario, the rotation works, but I can't figure out how to create a joint between them and add that joint to the physicsWorld from outside the scene.

Either way, neither of my solutions seem okay. How would you go about creating the pill object?

答:
I would just create an SKNode subclass with two SKSpriteNode references to the left and the right half of the pill and add these two sprite nodes as children.

Something like this.

```<code>class Pill: SKNode {
    var left: SKSpriteNode?
    var right: SKSpriteNode?

    func setup() {
        left = SKSpriteNode()
        /* Setup left half of the pil */
        addChild(left!)

        right = SKSpriteNode()
        /* Setup right half of the pil */
        addChild(right!)
    }
}
</code>```

Body:
I would just create an SKNode subclass with two SKSpriteNode references to the left and the right half of the pill and add these two sprite nodes as children.

Something like this.

class Pill: SKNode {
    var left: SKSpriteNode?
    var right: SKSpriteNode?

    func setup() {
        left = SKSpriteNode()
        /* Setup left half of the pil */
        addChild(left!)

        right = SKSpriteNode()
        /* Setup right half of the pil */
        addChild(right!)
    }
}


问:
Complex Sumproduct formula
Please could someone help me work out the sumproduct equation for something a little tricky.

Here is what I am trying to acheive.

Look in column B:B of sheet Postings, where it matches cell A3 = Tier 1, then   sumproduct Postings! Column K:K, M:M

I have tried this.

```<code>IF(SUMIF(Postings!B:B,Sheet1!A3)<>0,Postings!$K$3:$K$201,Postings!$M$3:$M$201)
</code>```

答:
Sounds like you want this:

=SUMPRODUCT((Postings!$B$3:$B$201=Sheet1!A3)+0,Postings!$K$3:$K$201,Postings!$M$3:$M$201)

That will multiply columns K and M only for rows where the column B criterion is met, and sum the results, is that what you need?

Title: Complex Sumproduct formula

Body:
Please could someone help me work out the sumproduct equation for something a little tricky.

Here is what I am trying to acheive.

Look in column B:B of sheet Postings, where it matches cell A3 = Tier 1, then   sumproduct Postings! Column K:K, M:M

I have tried this.

IF(SUMIF(Postings!B:B,Sheet1!A3)<>0,Postings!$K$3:$K$201,Postings!$M$3:$M$201)


问:
Configure IIS Express for external access to VS2010 project
I am developing a project in VS2010 and am able to view my site locally via IIS Express.  I would like to enable external access over the network.

All my research has sent me to this blog entry: http://blogs.iis.net/vaidyg/archive/2010/07/29/serving-external-traffic-with-webmatrix-beta.aspx, which is helpful but does not seem to show how to configure bindings for a project started in visual studio (I cannot find the screen in the screenshots, and I have edited binding info in applicationhost.config, but it does not seem to be reflected when I run the site from visual studio).

答:
If you're working with Visual Studio then follow these steps to access the IIS-Express over IP-Adress:

Get your host IP-Adress: ipconfig in Windows Command Line

GoTo $(SolutionDir).vs\config\applicationHost.config

Find

<site name="WebApplication3" id="2">
  <application path="/" applicationPool="Clr4IntegratedAppPool">
    <virtualDirectory path="/" physicalPath="C:\Users\user.name\Source\Repos\protoype-one\WebApplication3" />
  </application>
  <bindings>
      <binding protocol="http" bindingInformation="*:62549:localhost" />
  </bindings>
</site>

Add:
<binding protocol="http" bindingInformation="*:62549:192.168.178.108"/>

with your IP-Adress

Run your Visual Studio with Administrator rights and everything should work

Maybe look for some firewall issues if you try to connect from remote

The clue is, that Visual Studio got it's own applicationHost.config file!


问:
Error 1045 (28000) Access deneied for user 'root'@'localhost'
I am using ubuntu 16.04 and have just installed mysql. However, I am not able to access the mysql shell. I keep getting the Error 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Could you please help. Thanks.

答: Thanks for the comments. I solved the problem by reinstalling mysql from the mysql-api-config_0.3.8.1_all.deb file and can now access the mysql shell.</p>


问:
Angular not binding data on html directly
I'm a beginner in Angular (ver 1.6.3) and i ran into this problem:

i have a controller called prof:

```<code>(function () {
    'use strict';

    angular
        .module('app.prof', [])
        .controller('ProfController', ProfController);

    /** @ngInject */
    function ProfController($scope, Data)
    {
        var vm = this;
        vm.documents = Data.documents;
        vm.classes = Data.classes;
    }
})();
</code>```

Here's its associated module :

```<code>(function () {
    'use strict';

    angular
        .module('app.prof')
        .config(config);

    /** @ngInject */
    function config($stateProvider, $translatePartialLoaderProvider, msApiProvider) {
        // State
        $stateProvider
            .state('app.prof', {
                url    : '/prof',
                views  : {
                    'content@app': {
                        templateUrl: 'app/main/prof/prof.html',
                        controller : 'ProfController as vm'
                    }
                },
                resolve : {
                    Data : function(msApi){
                        return msApi.resolve('data@get');
                    }
                }
            });

        $translatePartialLoaderProvider.addPart('app/main/prof');
        msApiProvider.register('data', ['app/data/prof/prof-data.json']);
    }
})();
</code>```

And here's the main problem : i have this html :

```<code><div class="document" ng-repeat="document in vm.documents">
    <ms-card template="'app/custom-directives/prof-card/prof-card.html'"
             ng-model="document"></ms-card>
</div>
</code>```

it works perfectly fine, the data is correctly binded and all, but when i put the template called directly in the page instead of calling it throught a <ms-card> it doesn't work anymore !
i've tried to put some console.log() a little eveywhere but it always says the data isn't defined; i don't get it.
Plus, the ng-repeat always works fine

Edit : a bit of the html i call :

```<code><md-list-item class="document-item md-white-bg md-2-line" md-ink-ripple>
              <div class="media ml-16">
                <img class="image-apercu" ng-src="{{card.media.image.src}}" alt="{{card.media.image.alt}}" ng-show="card.media.image">
              </div>
</code>```

ps : when i add the html directly i don't forget to put the ng-model="document" but it still doesn't work

This is very confusing for me :/

答:
You cannot bind the "vm" object with "$scope".  you need to bind it with Scope like

```<code>function ProfController($scope, Data)
    {
        //$scope.vm = this;

        $scope.vm.documents = Data.documents;
        $scope.vm.classes = Data.classes;
    }
</code>```

Your Html Should be like :

```<code><body ng-app="app.prof" ng-controller="ProfController">
    <div class="document" ng-repeat="document in vm.documents">
        <ms-card template="'app/custom-directives/prof-card/prof-card.html'"
                 ng-bind="document"></ms-card>
    </div>
</body>
</code>```

Hope this will work for you

Body:
I'm a beginner in Angular (ver 1.6.3) and i ran into this problem:

i have a controller called prof:

(function () {
    'use strict';

    angular
        .module('app.prof', [])
        .controller('ProfController', ProfController);

    /** @ngInject */
    function ProfController($scope, Data)
    {
        var vm = this;
        vm.documents = Data.documents;
        vm.classes = Data.classes;
    }
})();

Here's its associated module :

(function () {
    'use strict';

    angular
        .module('app.prof')
        .config(config);

    /** @ngInject */
    function config($stateProvider, $translatePartialLoaderProvider, msApiProvider) {
        // State
        $stateProvider
            .state('app.prof', {
                url    : '/prof',
                views  : {
                    'content@app': {
                        templateUrl: 'app/main/prof/prof.html',
                        controller : 'ProfController as vm'
                    }
                },
                resolve : {
                    Data : function(msApi){
                        return msApi.resolve('data@get');
                    }
                }
            });

        $translatePartialLoaderProvider.addPart('app/main/prof');
        msApiProvider.register('data', ['app/data/prof/prof-data.json']);
    }
})();

And here's the main problem : i have this html :

    <ms-card template="'app/custom-directives/prof-card/prof-card.html'"
             ng-model="document"></ms-card>

it works perfectly fine, the data is correctly binded and all, but when i put the template called directly in the page instead of calling it throught a <ms-card> it doesn't work anymore !
i've tried to put some console.log() a little eveywhere but it always says the data isn't defined; i don't get it.
Plus, the ng-repeat always works fine

Edit : a bit of the html i call :

<md-list-item class="document-item md-white-bg md-2-line" md-ink-ripple>

ps : when i add the html directly i don't forget to put the ng-model="document" but it still doesn't work

This is very confusing for me :/

Body:
You cannot bind the "vm" object with "$scope".  you need to bind it with Scope like

function ProfController($scope, Data)
    {
        //$scope.vm = this;

        $scope.vm.documents = Data.documents;
        $scope.vm.classes = Data.classes;
    }

Your Html Should be like :

<body ng-app="app.prof" ng-controller="ProfController">
    <div class="document" ng-repeat="document in vm.documents">
        <ms-card template="'app/custom-directives/prof-card/prof-card.html'"
                 ng-bind="document"></ms-card>
    </div>
</body>

Hope this will work for you


问:
Selenium | Java | Can anyone suggest how to select this element?
Need help to select an element that has the following attributes</p>

```<code><a href="" tabindex="-1" ng-bind-html="match.label uibTypeaheadHighlight:query" class="ng-binding ng-scope"><strong>Lantus</strong> 100 iu (Insulin)</a>
</code>```

答:
You can identify element using either className,linktext,css selectors or xpath. Below are the examples, you can try any of these below.

```<code>driver.findElement(By.xpath("//descendant::strong[contains(text(), 'Lantus')]"));

driver.findElement(By.cssSelector(".ng-binding.ng-scope");

driver.findElement(By.xpath("//strong[contains(text(), 'Lantus')]"));

driver.findElement(By.xpath("//a[@class='ng-binding ng-scope']"));

driver.findElement(By.linkText("Lantus 100 iu (Insulin)");

driver.findElement(By.className("ng-binding"));
</code>```

Let me know if you have any queries.

Body:
Need help to select an element that has the following attributes

Lantus 100 iu (Insulin)

Body:
You can identify element using either className,linktext,css selectors or xpath. Below are the examples, you can try any of these below.

driver.findElement(By.xpath("//descendant::strong[contains(text(), 'Lantus')]"));

driver.findElement(By.cssSelector(".ng-binding.ng-scope");

driver.findElement(By.xpath("//strong[contains(text(), 'Lantus')]"));

driver.findElement(By.xpath("//a[@class='ng-binding ng-scope']"));

driver.findElement(By.linkText("Lantus 100 iu (Insulin)");

driver.findElement(By.className("ng-binding"));

Let me know if you have any queries.


问:
What's wrong with this MySQL query and PHP foreach
Please help me learn what is wrong with this PHP / MySQL query.

This is my channels table:

name    url              id      key
BBC2    http://url.com/2 BBC2   2
BBC1    http://url.com/1 BBC1   1
```

<p>This works:</p>

<pre class="lang-PHP prettyprint-override"><code>$getchans = "SELECT * FROM channels";
$channels = mysqli_query($db,$getchans);
foreach ($channels as $channel)
{
    // do stuff
}
</code>```

This does not work:

```<code>$getchans = "SELECT * FROM channels ORDER BY key ASC";
$channels = mysqli_query($db,$getchans);
foreach ($channels as $channel)
{
    // do stuff
}
</code>```

and gives error Warning: Invalid argument supplied for foreach()

Can anyone please tell me why it doesn't work when MySQL query/result  is ordered?

Thank you.

答:
key is a keyword in mysql so you need to use `` quotes in your query.

$getchans="SELECT * FROM channels ORDER BY key ASC";

Body:
Please help me learn what is wrong with this PHP / MySQL query.

This is my channels table:

name    url              id      key
BBC2    http://url.com/2 BBC2   2
BBC1    http://url.com/1 BBC1   1

This works:

$getchans = "SELECT * FROM channels";
$channels = mysqli_query($db,$getchans);
foreach ($channels as $channel)
{
    // do stuff
}

This does not work:

$getchans = "SELECT * FROM channels ORDER BY key ASC";
$channels = mysqli_query($db,$getchans);
foreach ($channels as $channel)
{
    // do stuff
}

and gives error Warning: Invalid argument supplied for foreach()

Can anyone please tell me why it doesn't work when MySQL query/result  is ordered?

Thank you.


问:
My combobox will only run once
```<code>            from tkinter import *
            from tkinter.ttk import *

            month  = (1,2,3,4,5,6,7,8,9,10,11,12)

            def func1(self,event = None):
                var = self.CB1.get()
                print(var)
                print("Your Birthday is: " + var)

            class app():
                def __init__(self):

                    window = Tk()

                    self.CB1 = Combobox(window,values = month,state = "readonly")
                    self.CB1.current(0)

                    self.CB1.bind("<<ComboboxSelected>>", func1(self,event = None))

                    self.CB1.pack()

                    window.mainloop()

            app()
</code>```

<p>So it will output 1, and say "Your birthday is 1", it will not do it again if I select a different number. I have tried over 10 different pages to understand combo-boxes, and am failing quite hard to understand. Any help would be appreciated. Thank you to all who help. </p>

答:
This happens because in the line

```<code>self.CB1.bind("<<ComboboxSelected>>", func1(self,event = None))
</code>```

func1 is executed directly and the result (None) is assigned as the bind "function". Use a lambda expression like this:

```<code>self.CB1.bind("<<ComboboxSelected>>", lambda x: func1(self, x))
</code>```

Now you're binding an anonymous function to the event without executing it.

Title: My combobox will only run once

Body:
            from tkinter import *
            from tkinter.ttk import *

            month  = (1,2,3,4,5,6,7,8,9,10,11,12)

            def func1(self,event = None):
                var = self.CB1.get()
                print(var)
                print("Your Birthday is: " + var)

            class app():
                def __init__(self):

                    window = Tk()

                    self.CB1 = Combobox(window,values = month,state = "readonly")
                    self.CB1.current(0)

                    self.CB1.bind("<<ComboboxSelected>>", func1(self,event = None))

                    self.CB1.pack()

                    window.mainloop()

            app()

So it will output 1, and say "Your birthday is 1", it will not do it again if I select a different number. I have tried over 10 different pages to understand combo-boxes, and am failing quite hard to understand. Any help would be appreciated. Thank you to all who help.

Body:
This happens because in the line

self.CB1.bind("<<ComboboxSelected>>", func1(self,event = None))

func1 is executed directly and the result (None) is assigned as the bind "function". Use a lambda expression like this:

self.CB1.bind("<<ComboboxSelected>>", lambda x: func1(self, x))

Now you're binding an anonymous function to the event without executing it.


问:
Jquery chekbox select all except disabled
I have this jsp code as a header to toggle all checkbox:

```<code><th><input name="checkAll" type="checkbox" onClick="toggleCheck(this, this.form.poFulfill);"/></th>
</code>```

Each row reads the record whether that checkbox will be disabled or not:

```<code><input type="checkbox" name="poFulfill" value='<%=row.poId.toString()%>'
<%=(row.qtyIn.compareTo(row.qtyOut) == 0))?"disabled":""%>>
</code>```

I want to select all checkbox that is ENABLED only.  I read I need to use jquery so I modified my header to:

```<code><th><input id="chkSelectAll" name="checkAll" type="checkbox"/></th>
</code>```

And added this:

```<code><script type="text/javascript">
$('#chkSelectAll').click(function () {
var checked_status = this.checked;
$('div#item input[type=checkbox]').not(":disabled").prop("checked", checked_status);
});
</script>
</code>```

Not working and nothing happens when I click checkbox to select all.  Any idea?

答:
I strongly suggest you to use change() instead of click() when using checkboxes, radios. I've added a div with item id and it seems to work:

$('#chkSelectAll').change(function() {
  var checked_status = this.checked;
  $('div#item input[type=checkbox]').not(":disabled").prop("checked", checked_status);
  console.log($('#chkSelectAll1').is(':checked'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<th><input id="chkSelectAll" name="checkAll" type="checkbox" /></th>
<div id='item'>
<input id="chkSelectAll1" name="checkAll1" type="checkbox" disabled/>
<input id="chkSelectAll2" name="checkAll2" type="checkbox" />
<input id="chkSelectAll3" name="checkAll3" type="checkbox" />
</div></code>```

Body:
I have this jsp code as a header to toggle all checkbox:

<input name="checkAll" type="checkbox" onClick="toggleCheck(this, this.form.poFulfill);"/>

Each row reads the record whether that checkbox will be disabled or not:

<input type="checkbox" name="poFulfill" value='<%=row.poId.toString()%>'
<%=(row.qtyIn.compareTo(row.qtyOut) == 0))?"disabled":""%>>

I want to select all checkbox that is ENABLED only.  I read I need to use jquery so I modified my header to:

<input id="chkSelectAll" name="checkAll" type="checkbox"/>

And added this:

Not working and nothing happens when I click checkbox to select all.  Any idea?

Body:
I strongly suggest you to use change() instead of click() when using checkboxes, radios. I've added a div with item id and it seems to work:

$('#chkSelectAll').change(function() {
  var checked_status = this.checked;
  $('div#item input[type=checkbox]').not(":disabled").prop("checked", checked_status);
  console.log($('#chkSelectAll1').is(':checked'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<th><input id="chkSelectAll" name="checkAll" type="checkbox" /></th>
<div id='item'>
<input id="chkSelectAll1" name="checkAll1" type="checkbox" disabled/>
<input id="chkSelectAll2" name="checkAll2" type="checkbox" />
<input id="chkSelectAll3" name="checkAll3" type="checkbox" />
</div>


问:
How to logout and redirect to login page using Laravel 5.3?
I am using Laravel 5.3 and trying to implement authentication system. I used php artisan command make:auth to setup it. I edited the views according to my layout and redirecting it my dashboard page instead of home (set as default in setup). Now, when I am trying to logout it throwing me this error

```<code>NotFoundHttpException in RouteCollection.php line 161
</code>```

My code in routes/web.php is:

```<code>Auth::routes();

Route::get('/pages/superadmin/dashboard', 'HomeController@index');
</code>```

HomeController.php

```<code><?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;

 class HomeController extends Controller
 {
/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth');
}

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return view('dashboard');
}
}
</code>```

Auth/Login Controller.php

```<code><?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = '/dashboard';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
}
}
</code>```

I tried the solutions on this page: How to set laravel 5.3 logout redirect path? but it didn't work and showing these errors:

```<code> ReflectionException in Route.php line 339:
 Class App\Http\Controllers\Auth\Request does not exist
</code>```

I want to redirect it to login page which is in auth/ folder.

答:
Redirecting logout action to login page means to me there is no page in the site available unless user is authenticated.

I am not a big fan of touching the vendor directory as it is suggested above. It is true, Laravel 5.4 vendor/laravel/framework/src/Illuminate/Foundation/Auth/AutenticateUser->logout() redirects to '/'. There is no parameter available to change it. So let's keep it that way and just add an 'auth protection' to the route '/' (home)

in /routes/web.php add
Route::get('/', function () { return view('home'); })->middleware('auth');

Isn't it the simplest way ?

Body:
I am using Laravel 5.3 and trying to implement authentication system. I used php artisan command make:auth to setup it. I edited the views according to my layout and redirecting it my dashboard page instead of home (set as default in setup). Now, when I am trying to logout it throwing me this error

NotFoundHttpException in RouteCollection.php line 161

My code in routes/web.php is:

Auth::routes();

Route::get('/pages/superadmin/dashboard', 'HomeController@index');

HomeController.php

<?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;

 class HomeController extends Controller
 {
/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('auth');
}

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return view('dashboard');
}
}

Auth/Login Controller.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/

use AuthenticatesUsers;

/**
 * Where to redirect users after login.
 *
 * @var string
 */
protected $redirectTo = '/dashboard';

/**
 * Create a new controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware('guest', ['except' => 'logout']);
}
}

I tried the solutions on this page: How to set laravel 5.3 logout redirect path? but it didn't work and showing these errors:

 ReflectionException in Route.php line 339:
 Class App\Http\Controllers\Auth\Request does not exist

I want to redirect it to login page which is in auth/ folder.


问:
How to write regex that can accept only numbers or fraction format?
I want to write regex that can only accept numbers or a fraction. For example:

```<code>12453  Valid
562    Valid
1142/75  Valid
65/1    Valid
1.2    Invalid
asd    Invalid
/45    Invalid
</code>```

Now i wrote this for fraction

```<code>^\d+\/\d+$
</code>```

It is working fine for 1/1,45/15 etc

This is for numbers only

```<code>^\d*$
</code>```

Now user can write only numbers or fraction. How i make a regex that can be used in this case?

答:
Now user can write only numbers or fraction. How i make a regex that can be used in this case?

You can make fraction part optional in your regex by grouping in in an optional group.

You can use:

```<code>^\d+(?:\/\d+)?$
</code>```

(?:\/\d+)? is optional non-capturing-group that makes fractional part optional in regex pattern.

Body:
I want to write regex that can only accept numbers or a fraction. For example:

12453  Valid
562    Valid
1142/75  Valid
65/1    Valid
1.2    Invalid
asd    Invalid
/45    Invalid

Now i wrote this for fraction

^\d+\/\d+$

It is working fine for 1/1,45/15 etc

This is for numbers only

^\d*$

Now user can write only numbers or fraction. How i make a regex that can be used in this case?

Body:
Now user can write only numbers or fraction. How i make a regex that can be used in this case?

You can make fraction part optional in your regex by grouping in in an optional group.

You can use:

^\d+(?:\/\d+)?$

(?:\/\d+)? is optional non-capturing-group that makes fractional part optional in regex pattern.


答:
Try any of these below code.

```<code>driver.findElement(By.linkText("Lantus 100 iu (Insulin)"));
</code>```

Explanation:- Using linkText locator click on Lantus 100 iu (Insulin) link.

OR

```<code>driver.findElement(By.xpath("//a[@class='ng-binding ng-scope']"));
</code>```

Explanation of xpath:- Use class attribute of  tag.

OR

```<code>driver.findElement(By.cssSelector("a.ng-binding.ng-scope"));

OR

driver.findElement(By.cssSelector("a[class='ng-binding ng-scope']"));
</code>```

Explanation of cssSelector :- Use class attribute of  tag.

Title: Selenium | Java | Can anyone suggest how to select this element?

Body:
Try any of these below code.

driver.findElement(By.linkText("Lantus 100 iu (Insulin)"));

Explanation:- Using linkText locator click on Lantus 100 iu (Insulin) link.

OR

driver.findElement(By.xpath("//a[@class='ng-binding ng-scope']"));

Explanation of xpath:- Use class attribute of <a> tag.

OR

driver.findElement(By.cssSelector("a.ng-binding.ng-scope"));

OR

driver.findElement(By.cssSelector("a[class='ng-binding ng-scope']"));

Explanation of cssSelector :- Use class attribute of <a> tag.


问:
gdb stops in a command file if there is an error. How to continue despite the error?
I my real gdb script while analyzing a core file I try to dereference a pointer and get "Error in sourced command file: Cannot access memory at address " and then my gdb script stops. What I want is just to go on executing my gdb script without stopping. Is it possible?

This is a test program and a test gdb script that demonstrates my problem. In this situation the pointer has NULL value but in a real situation the pointer will like have not null invalid value.

This is test C program:

```<code>#include <stdio.h>
struct my_struct {
  int v1;
  int v2;
};

int main()
{
  my_struct *p;
  printf("%d %d\n", p->v1, p->v2);
  return 0;
}
</code>```

This is a test gdb script:

```<code>>cat analyze.gdb
p p->v1
q
</code>```

And this is demonstration of the problem (what I want from gdb here is to get this error message and then go process quit command):

```<code>>gdb -silent a.out ./core.22384 -x ./analyze.gdb
Reading symbols from /a.out...done.
[New Thread 22384]
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x0000000000400598 in main () at main.cpp:11
11        printf("%d %d\n", p->v1, p->v2);
./analyze.gdb:1: Error in sourced command file:
Cannot access memory at address 0x0
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.80.el6.x86_64
</code>```

Update

Thanks to Tom. This is a gdb script that handles this problem:

```<code>>cat ./analyze.v2.gdb
python
def my_ignore_errors(arg):
  try:
    gdb.execute("print \"" + "Executing command: " + arg + "\"")
    gdb.execute (arg)
  except:
    gdb.execute("print \"" + "ERROR: " + arg + "\"")
    pass

my_ignore_errors("p p")
my_ignore_errors("p p->v1")
gdb.execute("quit")
</code>```

This is how it works:

```<code>>gdb -silent ./a.out -x ./analyze.v2.gdb -c ./core.15045
Reading symbols from /import/home/a.out...done.
[New Thread 15045]
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x0000000000400598 in main () at main.cpp:11
11        printf("%d %d\n", p->v1, p->v2);
$1 = "Executing command: p p"
$2 = (my_struct *) 0x0
$3 = "Executing command: p p->v1"
$4 = "ERROR: p p->v1"
$5 = "Executing command: quit"
</code>```

答:
If you just want to exit if any error occurs, you can use the -batch gdb option:

Run in batch mode. Exit with status 0 after processing all the command
  files specified with ‘-x’ (and all commands from initialization files,
  if not inhibited with ‘-n’). Exit with nonzero status if an error
  occurs in executing the GDB commands in the command files. [...]

Body:
I my real gdb script while analyzing a core file I try to dereference a pointer and get "Error in sourced command file: Cannot access memory at address " and then my gdb script stops. What I want is just to go on executing my gdb script without stopping. Is it possible?

This is a test program and a test gdb script that demonstrates my problem. In this situation the pointer has NULL value but in a real situation the pointer will like have not null invalid value.

This is test C program:

#include <stdio.h>
struct my_struct {
  int v1;
  int v2;
};

int main()
{
  my_struct *p;
  printf("%d %d\n", p->v1, p->v2);
  return 0;
}

This is a test gdb script:

>cat analyze.gdb
p p->v1
q

And this is demonstration of the problem (what I want from gdb here is to get this error message and then go process quit command):

>gdb -silent a.out ./core.22384 -x ./analyze.gdb
Reading symbols from /a.out...done.
[New Thread 22384]
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x0000000000400598 in main () at main.cpp:11
11        printf("%d %d\n", p->v1, p->v2);
./analyze.gdb:1: Error in sourced command file:
Cannot access memory at address 0x0
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.80.el6.x86_64

Update

Thanks to Tom. This is a gdb script that handles this problem:

>cat ./analyze.v2.gdb
python
def my_ignore_errors(arg):
  try:
    gdb.execute("print \"" + "Executing command: " + arg + "\"")
    gdb.execute (arg)
  except:
    gdb.execute("print \"" + "ERROR: " + arg + "\"")
    pass

my_ignore_errors("p p")
my_ignore_errors("p p->v1")
gdb.execute("quit")

This is how it works:

>gdb -silent ./a.out -x ./analyze.v2.gdb -c ./core.15045
Reading symbols from /import/home/a.out...done.
[New Thread 15045]
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0  0x0000000000400598 in main () at main.cpp:11
11        printf("%d %d\n", p->v1, p->v2);
$1 = "Executing command: p p"
$2 = (my_struct *) 0x0
$3 = "Executing command: p p->v1"
$4 = "ERROR: p p->v1"
$5 = "Executing command: quit"


答:
Your query failed because key is a reserved keyword in SQL. Try to change the name of the column key to something else. There is also a very usefull list with all the reseverd keywords.

If you don't prefer an other name for this column, you can try to escape it by using the following query:

```<code>SELECT * FROM channels ORDER BY `key` ASC
</code>```

List with reserved keywords can be found on https://dev.mysql.com/doc/refman/5.7/en/keywords.html

Goodluck!

Title: What's wrong with this MySQL query and PHP foreach

Body:
Your query failed because key is a reserved keyword in SQL. Try to change the name of the column key to something else. There is also a very usefull list with all the reseverd keywords.

If you don't prefer an other name for this column, you can try to escape it by using the following query:

SELECT * FROM channels ORDER BY `key` ASC

List with reserved keywords can be found on https://dev.mysql.com/doc/refman/5.7/en/keywords.html

Goodluck!


问:
Interval Vue.js not working
I am new to Vuejs. I am trying to set a interval to a function. Unfortunately It doesn't work. I get the following error out of it:

Uncaught TypeError: Cannot read property 'unshift' of undefined

Just a regular alert box IS working. So I guess the variable can't be accessed. How can I access the variable of message? I added a jsfiddle below.

JS

```<code>new Vue({

    el: '#app',

    data: {

        message: {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'},

        messages: [

            {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'tw'},
            {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'fb'},

        ],

        headerShow: false,
        programShow: false,
        sliderShow: true

    },

    methods: {

        addTweet: function() {
            if(this.message.message){
                this.messages.unshift(this.message);
                this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
            }
        },

        setTweet: function() {

            setInterval(function() {
                this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
                this.messages.unshift(this.message);
            }, 5000);

        }

    }

});
</code>```

https://jsfiddle.net/fLj5ac0L/

答:
It's because you lost the correct context into the setInterval, so this is not bounded to Vue object and this.message would return undefined.You can use arrow function to solve this, or keep context inside the another variable.

```<code>setTweet: function() {

    setInterval(() => {
        this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
        this.messages.unshift(this.message);
    }, 5000);

}
</code>```

or

```<code>setTweet: function() {
    var self = this;
    setInterval(function() {
        self.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
        self.messages.unshift(self.message);
    }, 5000);

}
</code>```

Title: Interval Vue.js not working

Body:
I am new to Vuejs. I am trying to set a interval to a function. Unfortunately It doesn't work. I get the following error out of it:

Uncaught TypeError: Cannot read property 'unshift' of undefined

Just a regular alert box IS working. So I guess the variable can't be accessed. How can I access the variable of message? I added a jsfiddle below.

JS

new Vue({

    el: '#app',

    data: {

        message: {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'},

        messages: [

            {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'tw'},
            {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'fb'},

        ],

        headerShow: false,
        programShow: false,
        sliderShow: true

    },

    methods: {

        addTweet: function() {
            if(this.message.message){
                this.messages.unshift(this.message);
                this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
            }
        },

        setTweet: function() {

            setInterval(function() {
                this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
                this.messages.unshift(this.message);
            }, 5000);

        }

    }

});

https://jsfiddle.net/fLj5ac0L/

Body:
It's because you lost the correct context into the setInterval, so this is not bounded to Vue object and this.message would return undefined.You can use arrow function to solve this, or keep context inside the another variable.

setTweet: function() {

    setInterval(() => {
        this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
        this.messages.unshift(this.message);
    }, 5000);

}

or

setTweet: function() {
    var self = this;
    setInterval(function() {
        self.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
        self.messages.unshift(self.message);
    }, 5000);

}


答:
You can NOT use this in function(){} to call outside variables, the function(){} create a new scope, you can modify you code like this:

```<code>setTweet: function() {
  var that = this;
  setInterval(function() {
    that.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
    that.messages.unshift(this.message);
  }, 5000);
}
</code>```

or you can use arrow function like this:

```<code>setTweet: function() {
  setInterval(() => {
    this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
    this.messages.unshift(this.message);
  }, 5000);
}
</code>```

You can get more about JavaScript variable scope on this question: What is the scope of variables in JavaScript?

Title: Interval Vue.js not working

Body:
You can NOT use this in function(){} to call outside variables, the function(){} create a new scope, you can modify you code like this:

setTweet: function() {
  var that = this;
  setInterval(function() {
    that.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
    that.messages.unshift(this.message);
  }, 5000);
}

or you can use arrow function like this:

setTweet: function() {
  setInterval(() => {
    this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
    this.messages.unshift(this.message);
  }, 5000);
}

You can get more about JavaScript variable scope on this question: What is the scope of variables in JavaScript?


问:
How to change the text " Material ActionBar"
How to change the text " Material ActionBar"?
I can't find the code to change it..help.

A Material ActionBar

答:
The "Material ActionBar" is called Toolbar and you can use these methods to change the titles:

```<code>setTitle()
setSubTitle()
</code>```

Body:
The "Material ActionBar" is called Toolbar and you can use these methods to change the titles:

setTitle()
setSubTitle()


答:
The most explicit way would be to have a dictionary of those functions:

```<code>funcs = {
    'function1': do_function1,
    'function2': do_function2,
    'function3': do_function3,
}

funcs[item]()
</code>```

That way you can also name your functions whatever you want, decouple from item names, make them methods, move to other modules etc without breaking the general design. The other way is globals, as already answered.

Title: Construct callable function from string

Body:
How to construct and call a function from a string?
For example, consider three different functions and a list of strings, I want to be able to use the items in list of strings to construct and call the appropriate function

def do_function1():
    return 'done function1'

def do_function2():
    return 'done function2'

def do_function3():
    return 'done function3'

listOfstr = ['function1','function2','function3']

for item in listOfstr:
    result = 'do_'+item()
    print(result)

result = 'do_'+item()
TypeError: 'str' object is not callable

Body:
The most explicit way would be to have a dictionary of those functions:

funcs = {
    'function1': do_function1,
    'function2': do_function2,
    'function3': do_function3,
}

funcs[item]()

That way you can also name your functions whatever you want, decouple from item names, make them methods, move to other modules etc without breaking the general design. The other way is globals, as already answered.


问:
Resusing select subquery/result
I am trying to optimize the speed of a query which uses a redundant query block. I am trying to do a row-wise join in sql server 2008 using the query below.

```<code>Select * from
(<complex subquery>) cq
join table1 t1 on (cq.id=t1.id)
union
Select * from
<complex subquery> cq
join table2 t2 on (cq.id=t2.id)
</code>```

The <complex subquery> is exactly the same on both the union sub query pieces except we need to join it with multiple different tables to obtain the same columnar data.

Is there any way i can either rewrite the query to make it faster without using a temporary table to cache results?

答:
Why not use a temporary table and see if that improves the execution stats?

In some circumstances the Query Optimizer will automatically add a spool to the plan that caches sub queries this is basically just a temporary table though.

Have you checked your current plan to be sure that the query is actually being evaluated more than once?

Title: Resusing select subquery/result

Body:
I am trying to optimize the speed of a query which uses a redundant query block. I am trying to do a row-wise join in sql server 2008 using the query below.

Select * from
(<complex subquery>) cq
join table1 t1 on (cq.id=t1.id)
union
Select * from
<complex subquery> cq
join table2 t2 on (cq.id=t2.id)

The <complex subquery> is exactly the same on both the union sub query pieces except we need to join it with multiple different tables to obtain the same columnar data.

Is there any way i can either rewrite the query to make it faster without using a temporary table to cache results?


问:
How to use `setTimeout` in ClojureScript?
I'm trying to make a sleep function in ClojureScript (w/ Reagent):

(ns cljweb.webpage
  (:require [reagent.core :as reagent]))

(def temp-atom (reagent/atom 0))

(defn sleep [msec]
  (js/setTimeout (fn []) msec))

(defn page []
  [:div
   [:p @temp-atom]
   [:button
    {:on-click
      (fn []
        (sleep 3000)
        (swap! temp-atom inc))}
    "Click me!"]])
```

<p>For some reason, this doesn't sleep properly - when I click the "Click me!" button, <code>temp-atom</code> increments instantly - when I time it, by putting this after in <code>page</code>:</p>

<pre class="lang-clj prettyprint-override"><code>[:p (time (sleep 3000))]
</code>```

I get this in the console:

"Elapsed time: 0.015000 msecs"
```

What did I do wrong in the code?

答:
Javascript's setTimeout function accepts two arguments: function and timeout in milliseconds. Its contract is to run the received function after the timeout passes.

Your code doesn't pass the function you would like to execute after 3 seconds but instead passes a no-op function ((fn [])).

Your sleep function should look like this (and it would be better named timeout or you could just call js/setTimeout directly in your on-click handler):

```<code>(defn sleep [f ms]
  (js/setTimeout f ms))
</code>```

You also need to change how you call this function:

```<code>(sleep #(swap! temp-atom inc) 3000)
</code>```

Or with calling js/setTimeout directly:

```<code>(js/setTimeout #(swap! temp-atom inc) 3000)
</code>```

Body:
I'm trying to make a sleep function in ClojureScript (w/ Reagent):

(ns cljweb.webpage
  (:require [reagent.core :as reagent]))

(def temp-atom (reagent/atom 0))

(defn sleep [msec]
  (js/setTimeout (fn []) msec))

(defn page []
  [:div
   [:p @temp-atom]
   [:button
    {:on-click
      (fn []
        (sleep 3000)
        (swap! temp-atom inc))}
    "Click me!"]])

For some reason, this doesn't sleep properly - when I click the "Click me!" button, temp-atom increments instantly - when I time it, by putting this after in page:

[:p (time (sleep 3000))]

I get this in the console:

"Elapsed time: 0.015000 msecs"

What did I do wrong in the code?

Body:
Javascript's setTimeout function accepts two arguments: function and timeout in milliseconds. Its contract is to run the received function after the timeout passes.

Your code doesn't pass the function you would like to execute after 3 seconds but instead passes a no-op function ((fn [])).

Your sleep function should look like this (and it would be better named timeout or you could just call js/setTimeout directly in your on-click handler):

(defn sleep [f ms]
  (js/setTimeout f ms))

You also need to change how you call this function:

(sleep #(swap! temp-atom inc) 3000)

Or with calling js/setTimeout directly:

(js/setTimeout #(swap! temp-atom inc) 3000)


问:
broken promise chaining in then callback function
How to stop the promise in chaining here:

```<code>    .then(resp => {
      if (xxxxx) {
        return nextPromise()
      } else {
        // stop promise chain
        return
      }
    })
    .then(resp => {
       // nextPromise callback function..
    })
</code>```

I thought the return would stop the chain but I was wrong.

答:
If you don't want to break the chain by throwing an error, a solution would be to nest the chain:

```<code>.then(resp => {
  if (xxxxx) {
    return nextPromise().then(resp => {
      // nextPromise callback function..
    });
  }
})
</code>```

This would still allow a global .catch() in which you don't have to explicitly check for an error thrown to end the chain. A drawback would be that if you have many of these conditions, you end up with something similar to "callback hell".

Body:
How to stop the promise in chaining here:

    .then(resp => {
      if (xxxxx) {
        return nextPromise()
      } else {
        // stop promise chain
        return
      }
    })
    .then(resp => {
       // nextPromise callback function..
    })

I thought the return would stop the chain but I was wrong.

Body:
If you don't want to break the chain by throwing an error, a solution would be to nest the chain:

.then(resp => {
  if (xxxxx) {
    return nextPromise().then(resp => {
      // nextPromise callback function..
    });
  }
})

This would still allow a global .catch() in which you don't have to explicitly check for an error thrown to end the chain. A drawback would be that if you have many of these conditions, you end up with something similar to "callback hell".


问:
Laravel 5.4 updated syntax
Hi guys got some problem....

```<code>Call to undefined method Illuminate\Database\Query\Builder::udpate()
</code>```

here's my update code...

```<code>DB::table('gpl_team')->where('id', $idteam)->udpate(['team_logo' => $logo, 'team_name' => $name, 'team_country' => $country, 'updated_at' => $updated_at]);
</code>```

答:
Try this i think its should be work

```<code>  DB::table('gpl_team')->whereId($idteam)->update(['team_logo' => $logo, 'team_name' => $name, 'team_country' => $country, 'updated_at' => $updated_at]);
</code>```

Title: Laravel 5.4 updated syntax

Body:
Hi guys got some problem....

Call to undefined method Illuminate\Database\Query\Builder::udpate()

here's my update code...

DB::table('gpl_team')->where('id', $idteam)->udpate(['team_logo' => $logo, 'team_name' => $name, 'team_country' => $country, 'updated_at' => $updated_at]);

Body:
Try this i think its should be work

  DB::table('gpl_team')->whereId($idteam)->update(['team_logo' => $logo, 'team_name' => $name, 'team_country' => $country, 'updated_at' => $updated_at]);


问:
Calculate sum of dynamically adding input fields with jquery
I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();

This code is calculating sum of rendered rows not the new created rows

```<code> $(document).ready(function(){

        $('.datepicker').datepicker();

        var $inst = $('.inst_amount');
            $inst_form = $('.inst_form');
            $total_amount = $('#total_amount');
            $total_price = $('#total_price');
            total = 0;

        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
         $total_price.html(Math.round(total));
         $total_amount.val(Math.round(total));

        $(document).on('blur','.inst_amount', function(){
            var total = 0;
            $.each($inst, function(index, val) {
                var val = ($(this).val() == "") ? 0 : $(this).val();
                total = total + parseFloat(val);
            });
            console.log(total);
            $total_price.html(Math.round(total));
            $total_amount.val(Math.round(total));
        });
});
</code>```

答:
Put these code outside the $(document).ready

```<code>$(document).on('blur','.inst_amount', function(){
        var total = 0;
        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
        console.log(total);
        $total_price.html(Math.round(total));
        $total_amount.val(Math.round(total));
    });
</code>```

because at a time of $(document).ready , new row is not added

Body:
I've a form where i am calculating sum of amounts. Rows are dynamically generated with jquery clone();

This code is calculating sum of rendered rows not the new created rows

 $(document).ready(function(){

        $('.datepicker').datepicker();

        var $inst = $('.inst_amount');
            $inst_form = $('.inst_form');
            $total_amount = $('#total_amount');
            $total_price = $('#total_price');
            total = 0;

        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
         $total_price.html(Math.round(total));
         $total_amount.val(Math.round(total));

        $(document).on('blur','.inst_amount', function(){
            var total = 0;
            $.each($inst, function(index, val) {
                var val = ($(this).val() == "") ? 0 : $(this).val();
                total = total + parseFloat(val);
            });
            console.log(total);
            $total_price.html(Math.round(total));
            $total_amount.val(Math.round(total));
        });
});

Body:
Put these code outside the $(document).ready

$(document).on('blur','.inst_amount', function(){
        var total = 0;
        $.each($inst, function(index, val) {
            var val = ($(this).val() == "") ? 0 : $(this).val();
            total = total + parseFloat(val);
        });
        console.log(total);
        $total_price.html(Math.round(total));
        $total_amount.val(Math.round(total));
    });

because at a time of $(document).ready , new row is not added


问:
Ruby - how to find the NEXT occurrence of a given hour?
I want to return a Ruby Time object (miliseconds) that represents the next X hour from a given DateTime.

Examples for the next 5am

if it currently is 9pm on 3/28, the NEXT 5am would be 3/29 5am

if it currently is 6am on 3/29, the NEXT 5am would be 3/30 5am

Code wise:

```<code># for the below attribute
@object.created_at
=> "2017-03-28 21:00:00"

# given the definition of the next X hour in question
next_hour_to_find = 5 # for 5am

# what's the equation to produce 3/29 5am?
</code>```

I'd like something flexible so that if next_hour_to_find = 14 then the function would be able to find the next 2pm. No worries about time zone, this is all within the scope of the time zone of the @object.created_at.

My current thinking is below, but I feel like there's a cleaner way...

```<code>if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)
</code>```

答:
This is a pure-Ruby answer. I assume a 24-hour clock. If a 12-hour clock is desired the 12-hour time (e.g 3pm) can be converted (to 15) as a preliminary step.

```<code>require 'time'

dt = DateTime.now
  #=> #<DateTime: 2017-03-31T00:18:08-07:00\
  #     ((2457844j,26288s,566004000n),-25200s,2299161j)>
</code>```

Suppose

```<code>next_hr = 15
</code>```

Then

```<code>Time.new(dt.year, dt.month, dt.day, dt.hour) +
  3600 * ((dt.hour < next_hr) ? next_hr - dt.hour : 24 + next_hr - dt_hour)
  #> 2017-03-31 15:00:00 -0700
</code>```

Body:
I want to return a Ruby Time object (miliseconds) that represents the next X hour from a given DateTime.

Examples for the next 5am

if it currently is 9pm on 3/28, the NEXT 5am would be 3/29 5am

if it currently is 6am on 3/29, the NEXT 5am would be 3/30 5am

Code wise:

# for the below attribute
@object.created_at
=> "2017-03-28 21:00:00"

# given the definition of the next X hour in question
next_hour_to_find = 5 # for 5am

# what's the equation to produce 3/29 5am?

I'd like something flexible so that if next_hour_to_find = 14 then the function would be able to find the next 2pm. No worries about time zone, this is all within the scope of the time zone of the @object.created_at.

My current thinking is below, but I feel like there's a cleaner way...

if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)

Body:
This is a pure-Ruby answer. I assume a 24-hour clock. If a 12-hour clock is desired the 12-hour time (e.g 3pm) can be converted (to 15) as a preliminary step.

require 'time'

dt = DateTime.now
  #=> #<DateTime: 2017-03-31T00:18:08-07:00\
  #     ((2457844j,26288s,566004000n),-25200s,2299161j)>

Suppose

next_hr = 15

Then

Time.new(dt.year, dt.month, dt.day, dt.hour) +
  3600 * ((dt.hour < next_hr) ? next_hr - dt.hour : 24 + next_hr - dt_hour)
  #> 2017-03-31 15:00:00 -0700