问:
Retrieving array value from object array
I want to retrieve the array value name under my onRegister function. But I don't think arrayFullNames.name is correct.</p>

```<code>     var arrayFullNames = [
        {name: 'David', surname: 'Jones', age: 29},
        {name: 'Jack', surname: 'Sparrow', age: 33},
        {name: 'Monkey', surname: 'Idontknow', age: 9},
        {name: 'JavaScript' , surname: 'Something', age: '6 weeks'}
    ];

    function onRegister(){
      var userQuestion = prompt("What is your name", '');

    if(userQuestion == arrayFullNames.name){
      alert('name match');
     }else{
      alert('no match');
     }
  }
</code>```

答:
Arrays works based on indexes not like objects. Try the following </p>

```<code>var arrayFullNames = [
    {name: 'David', surname: 'Jones', age: 29},
    {name: 'Jack', surname: 'Sparrow', age: 33},
    {name: 'Monkey', surname: 'Idontknow', age: 9},
    {name: 'JavaScript' , surname: 'Something', age: '6 weeks'}
];

function onRegister(){
  var userQuestion = prompt("What is your name", '');
  for(var i=0; i< arrayFullNames.length; i++){
    if(userQuestion == arrayFullNames[i].name){
      alert('name match');
      return true;
    }
  }
  alert('no match');
  return false;
}
</code>```

Body:
I want to retrieve the array value name under my onRegister function. But I don't think arrayFullNames.name is correct.

     var arrayFullNames = [
        {name: 'David', surname: 'Jones', age: 29},
        {name: 'Jack', surname: 'Sparrow', age: 33},
        {name: 'Monkey', surname: 'Idontknow', age: 9},
        {name: 'JavaScript' , surname: 'Something', age: '6 weeks'}
    ];

    function onRegister(){
      var userQuestion = prompt("What is your name", '');

    if(userQuestion == arrayFullNames.name){
      alert('name match');
     }else{
      alert('no match');
     }
  }

Body:
Arrays works based on indexes not like objects. Try the following

var arrayFullNames = [
    {name: 'David', surname: 'Jones', age: 29},
    {name: 'Jack', surname: 'Sparrow', age: 33},
    {name: 'Monkey', surname: 'Idontknow', age: 9},
    {name: 'JavaScript' , surname: 'Something', age: '6 weeks'}
];

function onRegister(){
  var userQuestion = prompt("What is your name", '');
  for(var i=0; i< arrayFullNames.length; i++){
    if(userQuestion == arrayFullNames[i].name){
      alert('name match');
      return true;
    }
  }
  alert('no match');
  return false;
}


来源: stackexchange

问:
Lambda expression question
```<code>string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/
</code>```

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

答:
Not quite sure what you're asking but try:

```<code>string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}
</code>```

Index is used in an overload of Select to describe the index of the object your lambda is currently iterating over.

ContentLicense: CC BY-SA 2.5

Title: Lambda expression question

Body:
string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

Body:
Not quite sure what you're asking but try:

string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

Index is used in an overload of Select to describe the index of the object your lambda is currently iterating over.


问:
Can I get "&&" or "-and" to work in PowerShell?
Note: This question originally asked in 2009, when powershell did not have support for the && operator.
In 2019, per Jay's answer, microsoft added support for && and || in Powershell 7.
https://stackoverflow.com/a/564092/234

Original Question

&& is notoriously hard to search for on Google Search, but the best I've found is this article which says to use -and.

Unfortunately it doesn't give any more information, and I can't find out what I'm supposed to do with -and (again, a notoriously hard thing to search for).

The context I'm trying to use it in is "execute cmd1, and if successful, execute cmd2", basically this:

```<code>csc /t:exe /out:a.exe SomeFile.cs && a.exe
</code>```

If you just want to run multiple commands on a single line and you don't care if the first one fails or not, you can use ; For most of my purposes this is fine.

For example: kill -n myapp; ./myapp.exe.

答:
I think a simple if statement can accomplish this. Once I saw mkelement0's response that the last exit status is stored in $?, I put the following together:

```<code># Set the first command to a variable
$a=somecommand

# Temporary variable to store exit status of the last command (since we can't write to "$?")
$test=$?

# Run the test
if ($test=$true) { 2nd-command }
</code>```

So for the OP's example, it would be:

```<code>a=(csc /t:exe /out:a.exe SomeFile.cs); $test = $?; if ($test=$true) { a.exe }
</code>```

OwnerDisplayName: Orion Edwards

ContentLicense: CC BY-SA 4.0

Body:
Note: This question originally asked in 2009, when powershell did not have support for the && operator.
In 2019, per Jay's answer, microsoft added support for && and || in Powershell 7.
https://stackoverflow.com/a/564092/234

Original Question

&& is notoriously hard to search for on Google Search, but the best I've found is this article which says to use -and.

Unfortunately it doesn't give any more information, and I can't find out what I'm supposed to do with -and (again, a notoriously hard thing to search for).

The context I'm trying to use it in is "execute cmd1, and if successful, execute cmd2", basically this:

csc /t:exe /out:a.exe SomeFile.cs && a.exe

If you just want to run multiple commands on a single line and you don't care if the first one fails or not, you can use ; For most of my purposes this is fine.

For example: kill -n myapp; ./myapp.exe.

LastEditorDisplayName: Orion Edwards

Body:
I think a simple if statement can accomplish this. Once I saw mkelement0's response that the last exit status is stored in $?, I put the following together:

# Set the first command to a variable
$a=somecommand

# Temporary variable to store exit status of the last command (since we can't write to "$?")
$test=$?

# Run the test
if ($test=$true) { 2nd-command }

So for the OP's example, it would be:

a=(csc /t:exe /out:a.exe SomeFile.cs); $test = $?; if ($test=$true) { a.exe }


问:
How can I check if strings match?
I have a Google Sheet document that I only have read access to.

It has a set of workers in it. One of the fields is for "job location", and another is for "house location". When these fields don't match, the worker is "remote".

I'm trying to add a calculated column to a data source in Google Data Studio, but I can't find any string function that checks for equivalence, and just going J=K doesn't work.

The CASE operator isn't able to compare columns either.

Is there a way to make a formula determine if two fields are equivalent?

答:
Currently, there is no direct solution in Data Studio to do this.

However, you can take one of two approaches:

Create a new Google Sheet. Use IMPORTRANGE to bring in entire dataset from the source Sheet and then add the comparison column in this worksheet. Use ARRAYFORMULA to extend the formula all the way to the end. (e.g. =ARRAYFORMULA(D:D=E:E) - can be further polished) This Sheet can then work as your data source.

Create a Community Connector to fetch data from the Sheet using the Sheets Service. Add the comparison as a column in Apps Script.

ContentLicense: CC BY-SA 3.0

Title: How can I check if strings match?


问:
SQL Server: Group By 30 Day Windows
I have developed this SQL script to do a Group By on 30 day windows:

```<code>SELECT MIN(id.customer_id),
       DATEADD(DAY, DATEDIFF(DAY, 0, e.transaction_datetime) / 30 * 30, 0) as [window_start_dt],
       DATEADD(DAY, DATEDIFF(DAY, -30, e.transaction_datetime) / 30 * 30, 0) as [window_end_dt],
FROM event as e
INNER JOIN customer_identity as id
      ON id.customer_id = e.customer_id
WHERE e.transaction_datetime BETWEEN '2003-01-06' AND '2017-12-31'
GROUP BY id.customer_id,
      DATEADD(DAY, DATEDIFF(DAY, 0, e.transaction_datetime) / 30 * 30, 0),
      DATEADD(DAY, DATEDIFF(DAY, -30, e.transaction_datetime) / 30 * 30, 0)
ORDER BY [window_start_dt], [window_end_dt]
</code>```

Which results in the this:

```<code>customer_id,window_start_dt,window_end_dt
1,2003-01-06,2003-02-05
</code>```

However that is not exactly the 30 day window that I want:

```<code>customer_id,window_start_dt,window_end_dt
1,2003-01-06,2003-02-05
</code>```

So my issue is with the window_end_dt being off.  Currently, I am using a -30 in a DATEDIFF which is a little odd, so I would be welcome to a better way for the window_end_dt.

EDIT:

Here is small example dataset for the first month at least:

```<code>customer_id, transaction_datetime
1, 2013-02-04
1, 2013-01-21
1, 2013-01-22
1, 2013-01-27
2, 2013-02-02
2, 2013-01-08
2, 2013-01-19
2, 2013-01-21
3, 2013-02-03
3, 2013-01-15
3, 2013-01-19
</code>```

Additionally, I would like to be able to pick an arbitrary start date for the windowing to begin if possible (not aligned to months). For example, I'd like to ideally start the windows on 2003-01-06.

Edit:

I made changes to reflect to the desired 2003-01-06 start date for 30 day windows and to avoid confusion. There are additional columns I am calculating in these windows. But I have removed them to keep it simple and focus on the date logic for the group bys.

答:
```<code>select customer_id,
       DATEADD(DAY,(DATEDIFF(DAY,'2013-01-06',transaction_datetime)/30)*30,'2013-01-06') window_start,
       DATEADD(DAY,(DATEDIFF(DAY,'2013-01-06',transaction_datetime)/30)*30+29,'2013-01-06') window_end
  from event
 where transaction_datetime>='2013-01-06'
 group by customer_id,DATEDIFF(DAY,'2013-01-06',transaction_datetime)/30
</code>```

test on sqlfiddle.com

Title: SQL Server: Group By 30 Day Windows

Body:
I have developed this SQL script to do a Group By on 30 day windows:

SELECT MIN(id.customer_id),
       DATEADD(DAY, DATEDIFF(DAY, 0, e.transaction_datetime) / 30 * 30, 0) as [window_start_dt],
       DATEADD(DAY, DATEDIFF(DAY, -30, e.transaction_datetime) / 30 * 30, 0) as [window_end_dt],
FROM event as e
INNER JOIN customer_identity as id
      ON id.customer_id = e.customer_id
WHERE e.transaction_datetime BETWEEN '2003-01-06' AND '2017-12-31'
GROUP BY id.customer_id,
      DATEADD(DAY, DATEDIFF(DAY, 0, e.transaction_datetime) / 30 * 30, 0),
      DATEADD(DAY, DATEDIFF(DAY, -30, e.transaction_datetime) / 30 * 30, 0)
ORDER BY [window_start_dt], [window_end_dt]

Which results in the this:

customer_id,window_start_dt,window_end_dt
1,2003-01-06,2003-02-05

However that is not exactly the 30 day window that I want:

customer_id,window_start_dt,window_end_dt
1,2003-01-06,2003-02-05

So my issue is with the window_end_dt being off.  Currently, I am using a -30 in a DATEDIFF which is a little odd, so I would be welcome to a better way for the window_end_dt.

EDIT:

Here is small example dataset for the first month at least:

customer_id, transaction_datetime
1, 2013-02-04
1, 2013-01-21
1, 2013-01-22
1, 2013-01-27
2, 2013-02-02
2, 2013-01-08
2, 2013-01-19
2, 2013-01-21
3, 2013-02-03
3, 2013-01-15
3, 2013-01-19

Additionally, I would like to be able to pick an arbitrary start date for the windowing to begin if possible (not aligned to months). For example, I'd like to ideally start the windows on 2003-01-06.

Edit:

I made changes to reflect to the desired 2003-01-06 start date for 30 day windows and to avoid confusion. There are additional columns I am calculating in these windows. But I have removed them to keep it simple and focus on the date logic for the group bys.

Body:
select customer_id,
       DATEADD(DAY,(DATEDIFF(DAY,'2013-01-06',transaction_datetime)/30)*30,'2013-01-06') window_start,
       DATEADD(DAY,(DATEDIFF(DAY,'2013-01-06',transaction_datetime)/30)*30+29,'2013-01-06') window_end
  from event
 where transaction_datetime>='2013-01-06'
 group by customer_id,DATEDIFF(DAY,'2013-01-06',transaction_datetime)/30

test on sqlfiddle.com


问:
Java - Factory, Instance
```<code>public class DataFactory {

    class SYNOP implements IDataSources {}
    class WRF implements IDataSources {}

    public abstract class Factory {
        public abstract IDataSources CreateModel();
    }

    public class SYNOPFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new SYNOP();
        }
    }

    public class WRFFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new WRF();
        }
    }

    public static void main(String[] args) {

        Factory factory = new WRFFactory();

    }
}
</code>```

And i got message error like this:

No enclosing instance of type DataFactory is accessible. Must qualify
  the allocation with an enclosing instance of type DataFactory (e.g.
  x.new A() where x is an instance of DataFactory).

What did i do wrong?

Regards

答:
SYNOPFactory and  WRFFactory are declared as inner class of DataFactory.

It means that instances of them require a instance of DataFactory.

You could instantiate them for example  as

```<code>Factory factory = new DataFactory().new WRFFactory();
</code>```

But in fact, it makes not really sense to make them inner classes.

Why do you would need to couple so tightly instances of them with DataFactory ?

You should rather declare them in their own class file.

And extract also other classes in their own classes. Otherwise you would have the same problem.

Note that if you want to hide IDataSources implementations from client, you could declare subclasses of them as private class member of the factory subclass that creates instances of them :

```<code>public class SYNOPFactory extends Factory {

    private class SYNOP implements IDataSources {
    }

    @Override
    public IDataSources CreateModel() {
       return new SYNOP();
    }
}

public class WRFFactory extends Factory {

    private class WRF implements IDataSources {
    }

    @Override
    public IDataSources CreateModel() {
       return new WRF();
    }
}
</code>```

In this way, this will compile fine as you program by interface :

```<code>Factory factory = new WRFFactory();
IDataSources dateSources = factory.CreateModel();
</code>```

But this will not as now WRF is private to the WRFFactory class :

```<code>WRF wrf = new ...;
</code>```

Note also that it is not required to create multiple instances of a factory.

And repeating the new DataFactory() idiom will finish by creating many factory instances.

A factory may create multiple instances of objects but why would you need to have multiple instances of a factory ?

A single one can create all objects you need.

So you should have a singleton instance of the factory.

To achieve it, you can use the singleton DP or the dependency injection (that is better).

Dependency injection requires a DI framework.
 You don't seem to use it.

As workaround, in plain java, you could implement a eager Singleton (thanks Bill Pugh) such as :

```<code>public class WRFFactory extends Factory {

    private class WRF implements IDataSources {
    }

    private static WRFFactory instance = new WRFFactory();

    private WRFFactory(){
    }

    public static WRFFactory getInstance(){
       return instance;
    }
    @Override
    public IDataSources CreateModel() {
       return new WRF();
    }
}
</code>```

Now, you can create your IDataSources   instances in this way :

```<code>IDataSources datasources = WRFFactory.getInstance().CreateModel();
</code>```

Title: Java - Factory, Instance

Body:
public class DataFactory {

    class SYNOP implements IDataSources {}
    class WRF implements IDataSources {}

    public abstract class Factory {
        public abstract IDataSources CreateModel();
    }

    public class SYNOPFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new SYNOP();
        }
    }

    public class WRFFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new WRF();
        }
    }

    public static void main(String[] args) {

        Factory factory = new WRFFactory();

    }
}

And i got message error like this:

No enclosing instance of type DataFactory is accessible. Must qualify
  the allocation with an enclosing instance of type DataFactory (e.g.
  x.new A() where x is an instance of DataFactory).

What did i do wrong?

Regards

Body:
SYNOPFactory and  WRFFactory are declared as inner class of DataFactory.

It means that instances of them require a instance of DataFactory.

You could instantiate them for example  as

Factory factory = new DataFactory().new WRFFactory();

But in fact, it makes not really sense to make them inner classes.

Why do you would need to couple so tightly instances of them with DataFactory ?

You should rather declare them in their own class file.

And extract also other classes in their own classes. Otherwise you would have the same problem.

Note that if you want to hide IDataSources implementations from client, you could declare subclasses of them as private class member of the factory subclass that creates instances of them :

public class SYNOPFactory extends Factory {

    private class SYNOP implements IDataSources {
    }

    @Override
    public IDataSources CreateModel() {
       return new SYNOP();
    }
}

public class WRFFactory extends Factory {

    private class WRF implements IDataSources {
    }

    @Override
    public IDataSources CreateModel() {
       return new WRF();
    }
}

In this way, this will compile fine as you program by interface :

Factory factory = new WRFFactory();
IDataSources dateSources = factory.CreateModel();

But this will not as now WRF is private to the WRFFactory class :

WRF wrf = new ...;

Note also that it is not required to create multiple instances of a factory.

And repeating the new DataFactory() idiom will finish by creating many factory instances.

A factory may create multiple instances of objects but why would you need to have multiple instances of a factory ?

A single one can create all objects you need.

So you should have a singleton instance of the factory.

To achieve it, you can use the singleton DP or the dependency injection (that is better).

Dependency injection requires a DI framework.
 You don't seem to use it.

As workaround, in plain java, you could implement a eager Singleton (thanks Bill Pugh) such as :

public class WRFFactory extends Factory {

    private class WRF implements IDataSources {
    }

    private static WRFFactory instance = new WRFFactory();

    private WRFFactory(){
    }

    public static WRFFactory getInstance(){
       return instance;
    }
    @Override
    public IDataSources CreateModel() {
       return new WRF();
    }
}

Now, you can create your IDataSources   instances in this way :

IDataSources datasources = WRFFactory.getInstance().CreateModel();


问:
AutodiscoverUrl throws an error but only when running on a network drive
I have a very strange issue. This code:

```<code>....
exchangeService [i].Credentials = new WebCredentials( "user", "pwd" );
exchangeService [i].AutodiscoverUrl( "the-user-email-address" );
</code>```

Running it on C: hard drive it works fine and I can add new entries to the calendar.

Running it on a any network drive the AutodiscoverUrl() throws the error:

The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

The content of the directories [HDD & Network] in which the program is located is equal!

My question:
What can be the reason this very simple program cannot be ran on a network drive?

Update:

It is running on Windows Server 2012 R2 and the network drive is a NFS drive which was connected via mount ...

答:
OK, dear Microsoft, this is a mystery:

It does not work on a NFS drive. When I try it on a samba network drive then it works. I don't believe even Microsoft could explain why it does not work on a NFS network drive.

Body:
I have a very strange issue. This code:

....
exchangeService [i].Credentials = new WebCredentials( "user", "pwd" );
exchangeService [i].AutodiscoverUrl( "the-user-email-address" );

Running it on C: hard drive it works fine and I can add new entries to the calendar.

Running it on a any network drive the AutodiscoverUrl() throws the error:

The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))

The content of the directories [HDD & Network] in which the program is located is equal!

My question:
What can be the reason this very simple program cannot be ran on a network drive?

Update:

It is running on Windows Server 2012 R2 and the network drive is a NFS drive which was connected via mount ...


问:
qws parameter for Qt-embedded is not working
I created a basic Qt application for Qt-embedded but when I executed that application in my target platform using the -qws parameter then an error message always appear, please see below,

#./test_app -qws

QWSSocket::connectToLocalFile could not connect:: Connection refused
QWSSocket::connectToLocalFile could not connect:: Connection refused
QWSSocket::connectToLocalFile could not connect:: Connection refused
QWSSocket::connectToLocalFile could not connect:: Connection refused
QWSSocket::connectToLocalFile could not connect:: Connection refused
QWSSocket::connectToLocalFile could not connect:: Connection refused

No Qt for Embedded Linux server appears to be running.
If you want to run this program as a server,
add the "-qws" command-line option.
terminate called without an active exception
Aborted

Please advice.

Thanks.

答:
Is "test_app" linked again qt/embedded?

What print "strace ./test_app"

Have you played with LD_DEBUG-environmnt variable?


问:
How to get X largest values from array
I have array:
[2 , 4 , 5, 1 , 4 , 20]

How to get X highest values from this array?

Like this:

```<code>getHighest(2): 25, 5
getHighest(3): 25, 5, 4
</code>```

答:
A naive C++ implementation is sorting the array descending by Quick Sort algorithm as in this example below:

```<code>void swapArray(int * tab, int ind1, int ind2) {
    int swap = tab[ind1];
    tab[ind1] = tab[ind2];
    tab[ind2] = swap;
}

int sortArray(int * tab, int min, int max) {
    int pivot = max;
    bool leftSwapping = true;
    while(min < max) {
        if(leftSwapping) {
            if(tab[min] < tab[pivot]) {
                swapArray(tab, min, pivot);
                pivot = min;
                max--;
                leftSwapping = false;
            } else {
                min++;
            }
        } else {
            if(tab[max] > tab[pivot]) {
                swapArray(tab, max, pivot);
                pivot = max;
                min++;
                leftSwapping = true;
            } else {
                max--;
            }
        }
    }
    return pivot;
}

void quickSort(int * tab, int min, int max) {
    if(min < max) {
        int pivot = sortArray(tab, min, max);

        quickSort(tab, min, pivot-1);
        quickSort(tab, pivot+1, max);
    }
};
</code>```

And you can loop as many values you need out of array. Note: that QuickSort is not a stable algorithm, so Merge Sort and Insertion Sort can be handy in this case depending on you cause. This is in the case that you want to use multiple times the getHighest function, if not just use the simple selection sort and take as many values as you want.

Title: How to get X largest values from array

Body:
I have array:
[2 , 4 , 5, 1 , 4 , 20]

How to get X highest values from this array?

Like this:

getHighest(2): 25, 5
getHighest(3): 25, 5, 4

Body:
A naive C++ implementation is sorting the array descending by Quick Sort algorithm as in this example below:

void swapArray(int * tab, int ind1, int ind2) {
    int swap = tab[ind1];
    tab[ind1] = tab[ind2];
    tab[ind2] = swap;
}

int sortArray(int * tab, int min, int max) {
    int pivot = max;
    bool leftSwapping = true;
    while(min < max) {
        if(leftSwapping) {
            if(tab[min] < tab[pivot]) {
                swapArray(tab, min, pivot);
                pivot = min;
                max--;
                leftSwapping = false;
            } else {
                min++;
            }
        } else {
            if(tab[max] > tab[pivot]) {
                swapArray(tab, max, pivot);
                pivot = max;
                min++;
                leftSwapping = true;
            } else {
                max--;
            }
        }
    }
    return pivot;
}

void quickSort(int * tab, int min, int max) {
    if(min < max) {
        int pivot = sortArray(tab, min, max);

        quickSort(tab, min, pivot-1);
        quickSort(tab, pivot+1, max);
    }
};

And you can loop as many values you need out of array. Note: that QuickSort is not a stable algorithm, so Merge Sort and Insertion Sort can be handy in this case depending on you cause. This is in the case that you want to use multiple times the getHighest function, if not just use the simple selection sort and take as many values as you want.


问:
Chrome Dev Tools: How to trace network for a link that opens a new tab?
I want to trace the network activity that happens when I click on a link. The problem is that the link opens a new tab, and apparently the Dev Tools works per tab it was open for. "Preserve Log Upon Navigation" does not help.

My current solution is to move to FireFox and HttpFox which does not have this issue. I wonder how all the developers for Chrome manage, this sounds pretty basic (of course I've searched for the answer, didn't find anything helpful).

答:
In Chrome 61.0.3163.100 you now have the following option available.
It is accessed by going to the Chrome Dev Tools Settings.  It's at the bottom.


答:
You can use the array.indexOf function to solve this issue:

```<code>if (arrayFullNames.indexOf(function(obj) {
  return userQuestion == obj.name;
}) > -1) {
  alert('name match');
} else {
  alert('no match');
}
</code>```

indexOf returns -1 if there was no match in the array, otherwise it returns the index of the match.

You could also use array.includes in a similar fashion.

Title: Retrieving array value from object array

Body:
You can use the array.indexOf function to solve this issue:

if (arrayFullNames.indexOf(function(obj) {
  return userQuestion == obj.name;
}) > -1) {
  alert('name match');
} else {
  alert('no match');
}

indexOf returns -1 if there was no match in the array, otherwise it returns the index of the match.

You could also use array.includes in a similar fashion.


问:
Problems creating HTML email from a file
I'm trying to send an HTML email via Python, argparse, and command line. Ideally I'd like to supply an HTML file that is read and transcribed into the body of the email but it seems all I've been able to do is attach the actual HTML file. I've omitted unnecessary code for an example. </p>

```<code>def send_mail(args):
    message = MIMEMultipart()
    ...
    part2 = MIMEText(args.html, 'html')
    message.attach(part2)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('html_file', help='The HTML file intended for use in the body of the email')
    args = parser.parse_args()
    args.html = open(args.html_file).read()

    send_mail(args)
</code>```

答:
For future travelers, you have to ensure that

```<code>message = MIMEMultipart()
</code>```

is actually

```<code>message = MIMEMultipart('alternative')
</code>```

otherwise it attaches the file instead of embedding it.

Body:
I'm trying to send an HTML email via Python, argparse, and command line. Ideally I'd like to supply an HTML file that is read and transcribed into the body of the email but it seems all I've been able to do is attach the actual HTML file. I've omitted unnecessary code for an example.

def send_mail(args):
    message = MIMEMultipart()
    ...
    part2 = MIMEText(args.html, 'html')
    message.attach(part2)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('html_file', help='The HTML file intended for use in the body of the email')
    args = parser.parse_args()
    args.html = open(args.html_file).read()

    send_mail(args)

Body:
For future travelers, you have to ensure that

message = MIMEMultipart()

is actually

message = MIMEMultipart('alternative')

otherwise it attaches the file instead of embedding it.


问:
Get the last day of the month
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn't support that, does the dateutil package support this?

答:
The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.

```<code>import datetime as dt
from dateutil.relativedelta import relativedelta

thisDate = dt.datetime(2017, 11, 17)

last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month
</code>```

Output:

```<code>datetime.datetime(2017, 11, 30, 0, 0)
</code>```

PS: This code runs faster as compared to the import calendarapproach; see below:

```<code>import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta

someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]

start1 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)

print ('Time Spent= ', dt.datetime.now() - start1)

start2 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year,
                          thisDate.month,
                          calendar.monthrange(thisDate.year, thisDate.month)[1])

print ('Time Spent= ', dt.datetime.now() - start2)
</code>```

OUTPUT:

```<code>Time Spent=  0:00:00.097814
Time Spent=  0:00:00.109791
</code>```

This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)

OwnerDisplayName: Cristian

Title: Get the last day of the month

Body:
The easiest way (without having to import calendar), is to get the first day of the next month, and then subtract a day from it.

import datetime as dt
from dateutil.relativedelta import relativedelta

thisDate = dt.datetime(2017, 11, 17)

last_day_of_the_month = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)
print last_day_of_the_month

Output:

datetime.datetime(2017, 11, 30, 0, 0)

PS: This code runs faster as compared to the import calendarapproach; see below:

import datetime as dt
import calendar
from dateutil.relativedelta import relativedelta

someDates = [dt.datetime.today() - dt.timedelta(days=x) for x in range(0, 10000)]

start1 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year, (thisDate + relativedelta(months=1)).month, 1) - dt.timedelta(days=1)

print ('Time Spent= ', dt.datetime.now() - start1)

start2 = dt.datetime.now()
for thisDate in someDates:
    lastDay = dt.datetime(thisDate.year,
                          thisDate.month,
                          calendar.monthrange(thisDate.year, thisDate.month)[1])

print ('Time Spent= ', dt.datetime.now() - start2)

OUTPUT:

Time Spent=  0:00:00.097814
Time Spent=  0:00:00.109791

This code assumes that you want the date of the last day of the month (i.e., not just the DD part, but the entire YYYYMMDD date)


问:
Angular Form Array of object is not working
```<code>// setup the form
const formGroup = {};
for (const prop of Object.keys(this.dataObject)) {
  try {
    const cpv = this.dataObject[prop].cpv;
    const value = this.dataObject[prop].value;
    formGroup['componentDetails'] = new FormArray([
      new FormControl({'cpv': cpv, 'value': value})
    ]);
  } catch (e) {
    console.log('Exception in Form setup - ' + e);
  }
}
</code>```

I have the above code to set-up form control and form array for my form. The resulting JSON that is generated does not add value property :(

What I get:

"componentDetails": [
    {
      "cpv": "CPV_1"
    }
  ]

What I need

"componentDetails": [
    {
      "cpv": "CPV_1",
      "value": "test value"
    }
  ]

I do not see any errors. Was wondering if you anyone faced the same issue and how they solved it?

答:
As @AJT_82 suggested value would have to be another FormControl:

```<code>formGroup['componentDetails'] = new FormArray([
  new FormControl({'cpv': cpv}),
  new FormControl({''value': value})
]);
</code>```

EDIT: If they need to go as a pair:

```<code>const cpv = this.dataObject[prop].cpv;
const value = this.dataObject[prop].value;
let pair: any = { 'cpv': cpv, 'value': value };

formGroup['componentDetails'] = new FormArray([
    new FormControl(pair)
]);
</code>```

See: https://angular.io/api/forms/FormArray

Body:
// setup the form
const formGroup = {};
for (const prop of Object.keys(this.dataObject)) {
  try {
    const cpv = this.dataObject[prop].cpv;
    const value = this.dataObject[prop].value;
    formGroup['componentDetails'] = new FormArray([
      new FormControl({'cpv': cpv, 'value': value})
    ]);
  } catch (e) {
    console.log('Exception in Form setup - ' + e);
  }
}

I have the above code to set-up form control and form array for my form. The resulting JSON that is generated does not add value property :(

What I get:

"componentDetails": [
    {
      "cpv": "CPV_1"
    }
  ]

What I need

"componentDetails": [
    {
      "cpv": "CPV_1",
      "value": "test value"
    }
  ]

I do not see any errors. Was wondering if you anyone faced the same issue and how they solved it?

Body:
As @AJT_82 suggested value would have to be another FormControl:

formGroup['componentDetails'] = new FormArray([
  new FormControl({'cpv': cpv}),
  new FormControl({''value': value})
]);

EDIT: If they need to go as a pair:

const cpv = this.dataObject[prop].cpv;
const value = this.dataObject[prop].value;
let pair: any = { 'cpv': cpv, 'value': value };

formGroup['componentDetails'] = new FormArray([
    new FormControl(pair)
]);

See: https://angular.io/api/forms/FormArray


问:
Number of pairs that can be made with X elements without repeating a pair?
I would like to make pairs out of X number of database objects.

Order of pairs does not matter.

Pairs will be made over multiple rounds.

I do not want pairs to be repeated in a subsequent round.

If I have:

```<code>A
B
C
D
</code>```

The first round might be:

```<code>AB
CD
</code>```

Second round might be:

```<code>AD
CB
</code>```

Third round might be:

```<code>AC
DB
</code>```

And there would be no other possibilities.

So for 4 elements, I could do 3 rounds before I have to repeat a pair.

What is the formula to help me with this for any number of elements?

Related How do I get the total number of unique pairs of a set in the database?

答:
You can use round-robin tournament algorithm to generate all possible pairs. Your example shows r-r algo in action: make two rows of elements, fix the first one (A) and rotate other elements in cyclic manner.

Note that N elements form N*(N-1)/2 pairs, and (N-1) rounds are needed to generate all of them

Body:
I would like to make pairs out of X number of database objects.

Order of pairs does not matter.

Pairs will be made over multiple rounds.

I do not want pairs to be repeated in a subsequent round.

If I have:

A
B
C
D

The first round might be:

AB
CD

Second round might be:

AD
CB

Third round might be:

AC
DB

And there would be no other possibilities.

So for 4 elements, I could do 3 rounds before I have to repeat a pair.

What is the formula to help me with this for any number of elements?

Related How do I get the total number of unique pairs of a set in the database?


问:
Asp.net open-source project as a learning source in c#
I am looking for an open-source asp.net (preferably .net 2.0) project in c#. It doesn't matter if it is some kind of a shop or cms or anything else. What matters is the size of the project that must be at least of medium size (not a simple app that was done in 2 weeks by one developer) and it would be a great advantage if the project contained unit tests and some kind of case study.

I want to use this project as a learning source. I know there are many books and web resources about asp.net but i would like to see how bigger projects are implemented. I am especially interested in implementation of user rights to certain parts of application, separation between html and application logic and i would like to see if developers use .net web controls or write their own custom controls.

Thanks in advance.

答: There are lots of open source asp.net projects at http://www.codeplex.com or you can also check out any number of the example sites at the ASP.NET homepage at http://www.asp.net</p>

OwnerDisplayName: empi

OwnerDisplayName: TheTXI


问:
Find a database with a particular table OR Find a table in every database of SQL Server
I have a SQL Server with hundreds of databases and each database having hundreds of tables.
Now I would like to find where in these databases is a table that I am looking for.

I could find if a table existed in individual database using

```<code>use myDatabase
select * from sys.tables  where name = 'mytable'
GO
</code>```

but using this means I have to manually change the database for hundreds of times .
I would like to find the database name only.
Is there a way out ?

答:
```<code>exec 'select ''?'', name from [?].sys.tables where name = ''yourTable'''
</code>```

Body:
I have a SQL Server with hundreds of databases and each database having hundreds of tables.
Now I would like to find where in these databases is a table that I am looking for.

I could find if a table existed in individual database using

use myDatabase
select * from sys.tables  where name = 'mytable'
GO

but using this means I have to manually change the database for hundreds of times .
I would like to find the database name only.
Is there a way out ?


问:
Scala Play connecting to MySql shows runtime error "Table 'token' doesn't exist"
I am attempting to read and write from a remote MySQL database from a Play for Scala controller using jdbc, and SBT is displaying at runtime the error:

"Table '{dbname}.token' doesn't exist"

Sql calls (selects) complete as expected despite this error.

My questions are:

What is this 'token' table and why would I want it?

Is there a way to turn off the requirement for the 'token' table

I have googled this aggressively and not found an answer, or indeed anything about this token table.

the details are as follows:

versions:

scala 2.11.6

play 2.2.6

relevant configurations in application.conf:

```<code>evolutionplugin=disabled
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://152.135.194.149/mydb"
db.default.user=someuser
db.default.password="somepassword"
</code>```

relevant parts of the controller:

```<code>import play.api.db._
import play.api.Play.current
def test = Action {

  DB.withConnection { conn =>
    val stm = conn.createStatement()
    val res = stm.executeQuery("""
    SELECT  *
    FROM    sometable
    """.stripMargin)

    while (res.next()) {
      // this println succeeds in showing the selected data
      println(res.getString(1), res.getString(2), res.getString(3), res.getString(4))
    }

  }

  Status(200)("good enough")
} // test
</code>```

complete error message from SBT:

```<code>[ERROR] [11/15/2017 16:31:43.041] [play-akka.actor.default-dispatcher-3] [TaskInvocation] Table 'mydb.token' doesn't exist
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydb.token' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2825)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2459)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2376)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2360)
    at com.jolbox.bonecp.PreparedStatementHandle.executeUpdate(PreparedStatementHandle.java:205)
    at anorm.Sql$class.executeUpdate(Anorm.scala:473)
    at anorm.SqlQuery.executeUpdate(Anorm.scala:481)
    at service.PgSqlUserService$$anonfun$deleteExpiredTokens$1.apply(PgSqlUserService.scala:521)
    at service.PgSqlUserService$$anonfun$deleteExpiredTokens$1.apply(PgSqlUserService.scala:512)
    at play.api.db.DBApi$class.withConnection(DB.scala:82)
    at play.api.db.BoneCPApi.withConnection(DB.scala:276)
    at play.api.db.DB$$anonfun$withConnection$3.apply(DB.scala:162)
    at play.api.db.DB$$anonfun$withConnection$3.apply(DB.scala:162)
    at scala.Option.map(Option.scala:145)
    at play.api.db.DB$.withConnection(DB.scala:162)
    at service.PgSqlUserService.deleteExpiredTokens(PgSqlUserService.scala:512)
    at securesocial.core.UserServicePlugin$$anonfun$onStart$1.apply$mcV$sp(UserService.scala:137)
    at akka.actor.Scheduler$$anon$9.run(Scheduler.scala:80)
    at akka.actor.LightArrayRevolverScheduler$$anon$3$$anon$2.run(Scheduler.scala:241)
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:42)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

[error] a.d.TaskInvocation - Table 'mydb.token' doesn't exist
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydb.token' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_151]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_151]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_151]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) ~[mysql-connector-java-5.1.27.jar:na]
    at com.mysql.jdbc.Util.getInstance(Util.java:386) ~[mysql-connector-java-5.1.27.jar:na]
</code>```

The permissions of the MySQL user:

```<code>mysql> select Host, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Alter_priv, Super_priv, Create_tmp_table_priv, Create_tablespace_priv from user where Host="%" and User="someuser";
+------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+------------+-----------------------+------------------------+
| Host | User       | Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv | Drop_priv | Alter_priv | Super_priv | Create_tmp_table_priv | Create_tablespace_priv |
+------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+------------+-----------------------+------------------------+
| %    | someuser   | Y           | Y           | Y           | Y           | Y           | Y         | Y          | Y          | Y                     | Y                      |
+------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+------------+-----------------------+------------------------+
1 row in set (0.00 sec)
</code>```

Notes:

I am additionally using Securesocial, which utilizes Postgres.

I intend in the future to enable evolution.

Any help would be greatly appreciated. Thank you in advance!

答:
the issue turns out to be related to securesocial competing for the db.default configuration.

since this project is deployed on heroku, the db.* configurations were set in the Procfile, rather than application.conf, and were set to use postgres on a different server.

redeclaring db.default in application.conf cause securesocial to attempt to query the mysql database and, thus, the 'table token doesn't exist' error.

the solution was to provide db configuration other than default and use that:

application.conf: use 'custom' (or any other string) instead of 'default'

```<code>db.custom.driver=com.mysql.jdbc.Driver
db.custom.url="jdbc:mysql://152.135.194.149/mydb"
db.custom.user=someuser
db.custom.password="somepassword"
</code>```

controller: call withConnection() with config from above

```<code>import play.api.db._
import play.api.Play.current
def test = Action {

  // note the 'custom'
  DB.withConnection("custom") { conn =>
    val stm = conn.createStatement()
    val res = stm.executeQuery("""
    SELECT  *
    FROM    sometable
    """.stripMargin)

    while (res.next()) {
      // this println succeeds in showing the selected data
      println(res.getString(1), res.getString(2), res.getString(3), res.getString(4))
    }

  }

  Status(200)("good enough")
} // test
</code>```

Body:
I am attempting to read and write from a remote MySQL database from a Play for Scala controller using jdbc, and SBT is displaying at runtime the error:

"Table '{dbname}.token' doesn't exist"

Sql calls (selects) complete as expected despite this error.

My questions are:

What is this 'token' table and why would I want it?

Is there a way to turn off the requirement for the 'token' table

I have googled this aggressively and not found an answer, or indeed anything about this token table.

the details are as follows:

versions:

scala 2.11.6

play 2.2.6

relevant configurations in application.conf:

evolutionplugin=disabled
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://152.135.194.149/mydb"
db.default.user=someuser
db.default.password="somepassword"

relevant parts of the controller:

import play.api.db._
import play.api.Play.current
def test = Action {

  DB.withConnection { conn =>
    val stm = conn.createStatement()
    val res = stm.executeQuery("""
    SELECT  *
    FROM    sometable
    """.stripMargin)

    while (res.next()) {
      // this println succeeds in showing the selected data
      println(res.getString(1), res.getString(2), res.getString(3), res.getString(4))
    }

  }

  Status(200)("good enough")
} // test

complete error message from SBT:

[ERROR] [11/15/2017 16:31:43.041] [play-akka.actor.default-dispatcher-3] [TaskInvocation] Table 'mydb.token' doesn't exist
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydb.token' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2617)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2778)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2825)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2156)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2459)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2376)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2360)
    at com.jolbox.bonecp.PreparedStatementHandle.executeUpdate(PreparedStatementHandle.java:205)
    at anorm.Sql$class.executeUpdate(Anorm.scala:473)
    at anorm.SqlQuery.executeUpdate(Anorm.scala:481)
    at service.PgSqlUserService$$anonfun$deleteExpiredTokens$1.apply(PgSqlUserService.scala:521)
    at service.PgSqlUserService$$anonfun$deleteExpiredTokens$1.apply(PgSqlUserService.scala:512)
    at play.api.db.DBApi$class.withConnection(DB.scala:82)
    at play.api.db.BoneCPApi.withConnection(DB.scala:276)
    at play.api.db.DB$$anonfun$withConnection$3.apply(DB.scala:162)
    at play.api.db.DB$$anonfun$withConnection$3.apply(DB.scala:162)
    at scala.Option.map(Option.scala:145)
    at play.api.db.DB$.withConnection(DB.scala:162)
    at service.PgSqlUserService.deleteExpiredTokens(PgSqlUserService.scala:512)
    at securesocial.core.UserServicePlugin$$anonfun$onStart$1.apply$mcV$sp(UserService.scala:137)
    at akka.actor.Scheduler$$anon$9.run(Scheduler.scala:80)
    at akka.actor.LightArrayRevolverScheduler$$anon$3$$anon$2.run(Scheduler.scala:241)
    at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:42)
    at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

[error] a.d.TaskInvocation - Table 'mydb.token' doesn't exist
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'mydb.token' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_151]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_151]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_151]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_151]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) ~[mysql-connector-java-5.1.27.jar:na]
    at com.mysql.jdbc.Util.getInstance(Util.java:386) ~[mysql-connector-java-5.1.27.jar:na]

The permissions of the MySQL user:

mysql> select Host, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Alter_priv, Super_priv, Create_tmp_table_priv, Create_tablespace_priv from user where Host="%" and User="someuser";
+------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+------------+-----------------------+------------------------+
| Host | User       | Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv | Drop_priv | Alter_priv | Super_priv | Create_tmp_table_priv | Create_tablespace_priv |
+------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+------------+-----------------------+------------------------+
| %    | someuser   | Y           | Y           | Y           | Y           | Y           | Y         | Y          | Y          | Y                     | Y                      |
+------+------------+-------------+-------------+-------------+-------------+-------------+-----------+------------+------------+-----------------------+------------------------+
1 row in set (0.00 sec)

Notes:

I am additionally using Securesocial, which utilizes Postgres.

I intend in the future to enable evolution.

Any help would be greatly appreciated. Thank you in advance!

Body:
the issue turns out to be related to securesocial competing for the db.default configuration.

since this project is deployed on heroku, the db.* configurations were set in the Procfile, rather than application.conf, and were set to use postgres on a different server.

redeclaring db.default in application.conf cause securesocial to attempt to query the mysql database and, thus, the 'table token doesn't exist' error.

the solution was to provide db configuration other than default and use that:

application.conf: use 'custom' (or any other string) instead of 'default'

db.custom.driver=com.mysql.jdbc.Driver
db.custom.url="jdbc:mysql://152.135.194.149/mydb"
db.custom.user=someuser
db.custom.password="somepassword"

controller: call withConnection() with config from above

import play.api.db._
import play.api.Play.current
def test = Action {

  // note the 'custom'
  DB.withConnection("custom") { conn =>
    val stm = conn.createStatement()
    val res = stm.executeQuery("""
    SELECT  *
    FROM    sometable
    """.stripMargin)

    while (res.next()) {
      // this println succeeds in showing the selected data
      println(res.getString(1), res.getString(2), res.getString(3), res.getString(4))
    }

  }

  Status(200)("good enough")
} // test


问:
Convert a string to a template string
Is it possible to create a template string as a usual string,

```<code>let a = "b:${b}";
</code>```

and then convert it into a template string,

```<code>let b = 10;
console.log(a.template()); // b:10
</code>```

without eval, new Function and other means of dynamic code generation?

答:
Similar to Daniel's answer (and s.meijer's gist) but more readable:

```<code>const regex = /\${[^{]+}/g;

export default function interpolate(template, variables, fallback) {
    return template.replace(regex, (match) => {
        const path = match.slice(2, -1).trim();
        return getObjPath(path, variables, fallback);
    });
}

//get the specified property or nested property of an object
function getObjPath(path, obj, fallback = '') {
    return path.split('.').reduce((res, key) => res[key] || fallback, obj);
}
</code>```

Note: This slightly improves s.meijer's original, since it won't match things like ${foo{bar} (the regex only allows non-curly brace characters inside ${ and }).

UPDATE: I was asked for an example using this, so here you go:

```<code>const replacements = {
    name: 'Bob',
    age: 37
}

interpolate('My name is ${name}, and I am ${age}.', replacements)
</code>```

Title: Convert a string to a template string

Body:
Is it possible to create a template string as a usual string,

let a = "b:${b}";

and then convert it into a template string,

let b = 10;
console.log(a.template()); // b:10

without eval, new Function and other means of dynamic code generation?

Body:
Similar to Daniel's answer (and s.meijer's gist) but more readable:

const regex = /\${[^{]+}/g;

export default function interpolate(template, variables, fallback) {
    return template.replace(regex, (match) => {
        const path = match.slice(2, -1).trim();
        return getObjPath(path, variables, fallback);
    });
}

//get the specified property or nested property of an object
function getObjPath(path, obj, fallback = '') {
    return path.split('.').reduce((res, key) => res[key] || fallback, obj);
}

Note: This slightly improves s.meijer's original, since it won't match things like ${foo{bar} (the regex only allows non-curly brace characters inside ${ and }).

UPDATE: I was asked for an example using this, so here you go:

const replacements = {
    name: 'Bob',
    age: 37
}

interpolate('My name is ${name}, and I am ${age}.', replacements)


问:
strtok segmentation fault error in C
I know this question is frequently asked but none of other
questions are helpful. I have a code

```<code>char *hamlet[] = {"Give every man thy ear, but few thy voice.",
        "Neither a borrower nor a lender be.",
        "For loan oft loses both itself and friend",
        "And borrowing dulls the edge of husbandry.",
        "This above all: to thine own self be true."};
    int i;
    for (i = 0; i < NUM_SENTENCES; i++) {
    int size;
    char **words = splitString(hamlet[i], &size);
</code>```

and in another .c file I have

```<code>char** splitString(char theString[], int *arraySize){
int numWords = 1;
int i=0;
numWords += countSpaces(theString);
char **wordArray = malloc(numWords * sizeof(char*));

char *token;
token = strtok(theString, " ");

return wordArray;
</code>```

Problem is, I always get segmentation fault when I link them and run it. I believe this is error caused by memory since first code and second code are located in different .c files. I can't really find a way to solve it

答:
The contents of the hamlet array are all string literals.  These are not modifiable and typically resided in a read-only section of memory.  The strtok function modifies its argument, so that's why you get a crash.

You need to make a copy of the string you're working on using strdup.  Then you can copy out the substrings.

Title: strtok segmentation fault error in C

Body:
I know this question is frequently asked but none of other
questions are helpful. I have a code

char *hamlet[] = {"Give every man thy ear, but few thy voice.",
        "Neither a borrower nor a lender be.",
        "For loan oft loses both itself and friend",
        "And borrowing dulls the edge of husbandry.",
        "This above all: to thine own self be true."};
    int i;
    for (i = 0; i < NUM_SENTENCES; i++) {
    int size;
    char **words = splitString(hamlet[i], &size);

and in another .c file I have

char** splitString(char theString[], int *arraySize){
int numWords = 1;
int i=0;
numWords += countSpaces(theString);
char **wordArray = malloc(numWords * sizeof(char*));

char *token;
token = strtok(theString, " ");

return wordArray;

Problem is, I always get segmentation fault when I link them and run it. I believe this is error caused by memory since first code and second code are located in different .c files. I can't really find a way to solve it


问:
Removing parts of a string with endsWith
my goal here to remove the word "like" if it appears at the end of the users input which gets replicated as a string. But I am struggling to see what the problem is with my work.

When this is ran, anything before the word "like" is removed and I can't understand why so any advice would be appreciated, thanks in advance.

```<code>System.out.println("Type in an input, plez?");
String userInput4 = inputScanner.nextLine();
int userInput4Length = userInput4.length();
if (userInput4.toLowerCase().endsWith("like")) {
    String partOfString3 = userInput4.substring(userInput4Length- 4);
    System.out.println("There is a 'like' in your input, let me remove that for you:- " +partOfString3);
} else {
    System.out.println(userInput4);
}
</code>```

答:
substring() method's first parameter is beginIndex. So, you should write

```<code>String partOfString3 = userInput4.substring(0, userInput4Length- 4);
</code>```

instead of

```<code>String partOfString3 = userInput4.substring(userInput4Length- 4);
</code>```

Body:
my goal here to remove the word "like" if it appears at the end of the users input which gets replicated as a string. But I am struggling to see what the problem is with my work.

When this is ran, anything before the word "like" is removed and I can't understand why so any advice would be appreciated, thanks in advance.

System.out.println("Type in an input, plez?");
String userInput4 = inputScanner.nextLine();
int userInput4Length = userInput4.length();
if (userInput4.toLowerCase().endsWith("like")) {
    String partOfString3 = userInput4.substring(userInput4Length- 4);
    System.out.println("There is a 'like' in your input, let me remove that for you:- " +partOfString3);
} else {
    System.out.println(userInput4);
}

Body:
substring() method's first parameter is beginIndex. So, you should write

String partOfString3 = userInput4.substring(0, userInput4Length- 4);

instead of

String partOfString3 = userInput4.substring(userInput4Length- 4);


问:
running 3 threads in sequence java
I have 3 threads
1st printing A
2nd printing B
3rd printing C

I want to print in sequence A B C A B C A B C and so on.....

So I wrote the program below, but I am not able to achieve the same.
I am aware of the problem that when status=1 at that time say for example B1 and C1 thread are waiting and when I do notifyAll() both waiting thread wake up and depending on CPU allocation it might print B or C.

in this case I want only B to be printed after A.

what modification I need to do.

```<code>public class NotifyAllExample {

    int status=1;
    public static void main(String[] args) {

        NotifyAllExample notifyAllExample = new NotifyAllExample();

        A1 a=new A1(notifyAllExample);
        B1 b=new B1(notifyAllExample);
        C1 c=new C1(notifyAllExample);

        a.start();
        b.start();
        c.start();
    }
}

class A1 extends Thread{
    NotifyAllExample notifyAllExample;

    A1(NotifyAllExample notifyAllExample){
        this.notifyAllExample = notifyAllExample;
    }

    @Override
    public void run() {

        try{
            synchronized (notifyAllExample) {

                for (int i = 0; i < 100; i++) {

                    if(notifyAllExample.status!=1){
                        notifyAllExample.wait();
                    }

                    System.out.print("A ");
                    notifyAllExample.status = 2;
                    notifyAllExample.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 1 :"+e.getMessage());
        }

    }

}

class B1 extends Thread{

    NotifyAllExample notifyAllExample;

    B1(NotifyAllExample notifyAllExample){
        this.notifyAllExample = notifyAllExample;
    }

    @Override
    public void run() {

        try{
            synchronized (notifyAllExample) {

                for (int i = 0; i < 100; i++) {

                    if(notifyAllExample.status!=2){
                        notifyAllExample.wait();
                    }

                    System.out.print("B ");
                    notifyAllExample.status = 3;
                    notifyAllExample.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 2 :"+e.getMessage());
        }

    }
}

class C1 extends Thread{

    NotifyAllExample notifyAllExample;

    C1(NotifyAllExample notifyAllExample){
        this.notifyAllExample = notifyAllExample;
    }

    @Override
    public void run() {

        try{
            synchronized (notifyAllExample) {

                for (int i = 0; i < 100; i++) {

                    if(notifyAllExample.status!=3){
                        notifyAllExample.wait();
                    }

                    System.out.print("C ");
                    notifyAllExample.status = 1;
                    notifyAllExample.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 3 :"+e.getMessage());
        }

    }
}
</code>```

答:
The simplest solution to solve this can be following way:

```<code>public class PrintInOrder implements Runnable {

private int valueToPrint;
private int id;
private static int turn = 1;
private static int RESET_TURN_THRESHOLD = 3;

public PrintInOrder() {
    this.valueToPrint = -1;
}

public PrintInOrder(int id, int val) {
    this.id = id;
    this.valueToPrint = val;
}

@Override
public void run() {
        while(true) {
            if (turn == this.id) {
                System.out.println(Thread.currentThread().getName() + "::::" + valueToPrint);
                turn++;
            }
            if (turn > RESET_TURN_THRESHOLD) {
                turn = 1;
            }
        }

}

public static void main(String []args) {
    Thread t1 = new Thread(new PrintInOrder(1, 1));
    t1.setName("THREAD-1");
    t1.start();
    Thread t2 = new Thread(new PrintInOrder(2, 2));
    t2.setName("THREAD-2");
    t2.start();
    Thread t3 = new Thread(new PrintInOrder(3, 3));
    t3.setName("THREAD-3");
    t3.start();
}
</code>```

}

```<code>/*
OUTPUT::::
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
...
*/
</code>```

Title: running 3 threads in sequence java

Body:
I have 3 threads
1st printing A
2nd printing B
3rd printing C

I want to print in sequence A B C A B C A B C and so on.....

So I wrote the program below, but I am not able to achieve the same.
I am aware of the problem that when status=1 at that time say for example B1 and C1 thread are waiting and when I do notifyAll() both waiting thread wake up and depending on CPU allocation it might print B or C.

in this case I want only B to be printed after A.

what modification I need to do.

public class NotifyAllExample {

    int status=1;
    public static void main(String[] args) {

        NotifyAllExample notifyAllExample = new NotifyAllExample();

        A1 a=new A1(notifyAllExample);
        B1 b=new B1(notifyAllExample);
        C1 c=new C1(notifyAllExample);

        a.start();
        b.start();
        c.start();
    }
}

class A1 extends Thread{
    NotifyAllExample notifyAllExample;

    A1(NotifyAllExample notifyAllExample){
        this.notifyAllExample = notifyAllExample;
    }

    @Override
    public void run() {

        try{
            synchronized (notifyAllExample) {

                for (int i = 0; i < 100; i++) {

                    if(notifyAllExample.status!=1){
                        notifyAllExample.wait();
                    }

                    System.out.print("A ");
                    notifyAllExample.status = 2;
                    notifyAllExample.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 1 :"+e.getMessage());
        }

    }

}

class B1 extends Thread{

    NotifyAllExample notifyAllExample;

    B1(NotifyAllExample notifyAllExample){
        this.notifyAllExample = notifyAllExample;
    }

    @Override
    public void run() {

        try{
            synchronized (notifyAllExample) {

                for (int i = 0; i < 100; i++) {

                    if(notifyAllExample.status!=2){
                        notifyAllExample.wait();
                    }

                    System.out.print("B ");
                    notifyAllExample.status = 3;
                    notifyAllExample.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 2 :"+e.getMessage());
        }

    }
}

class C1 extends Thread{

    NotifyAllExample notifyAllExample;

    C1(NotifyAllExample notifyAllExample){
        this.notifyAllExample = notifyAllExample;
    }

    @Override
    public void run() {

        try{
            synchronized (notifyAllExample) {

                for (int i = 0; i < 100; i++) {

                    if(notifyAllExample.status!=3){
                        notifyAllExample.wait();
                    }

                    System.out.print("C ");
                    notifyAllExample.status = 1;
                    notifyAllExample.notifyAll();
                }

            }
        }catch (Exception e) {
            System.out.println("Exception 3 :"+e.getMessage());
        }

    }
}

Body:
The simplest solution to solve this can be following way:

public class PrintInOrder implements Runnable {

private int valueToPrint;
private int id;
private static int turn = 1;
private static int RESET_TURN_THRESHOLD = 3;

public PrintInOrder() {
    this.valueToPrint = -1;
}

public PrintInOrder(int id, int val) {
    this.id = id;
    this.valueToPrint = val;
}

@Override
public void run() {
        while(true) {
            if (turn == this.id) {
                System.out.println(Thread.currentThread().getName() + "::::" + valueToPrint);
                turn++;
            }
            if (turn > RESET_TURN_THRESHOLD) {
                turn = 1;
            }
        }

}

public static void main(String []args) {
    Thread t1 = new Thread(new PrintInOrder(1, 1));
    t1.setName("THREAD-1");
    t1.start();
    Thread t2 = new Thread(new PrintInOrder(2, 2));
    t2.setName("THREAD-2");
    t2.start();
    Thread t3 = new Thread(new PrintInOrder(3, 3));
    t3.setName("THREAD-3");
    t3.start();
}

}

/*
OUTPUT::::
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
THREAD-1::::1
THREAD-2::::2
THREAD-3::::3
...
*/


问:
How do I collect rows from QItemSelection
What is the best way to collect a list of QModelIndex per row from a QItemSelection. Currently QItemSelection returns a list of QModelIndex for each row and each column. I only need it for each row.

答:
If you are using a view where the selection behaviour is to select rows, the simplest method would be this:

```<code>def selected_rows(self, selection):
    indexes = []
    for index in selection.indexes():
        if index.column() == 0:
            indexes.append(index)
    return indexes
</code>```

A somewhat shorter (but not much faster) alternative to the above would be:

```<code>from itertools import filterfalse

def selected_rows(self, selection):
    return list(filterfalse(QtCore.QModelIndex.column, selection.indexes()))
</code>```

However, if the selection behaviour is to select items, you would need this:

```<code>def selected_rows(self, selection):
    seen = set()
    indexes = []
    model = self.tree.model()
    for index in selection.indexes():
        if index.row() not in seen:
            indexes.append(model.index(index.row(), 0))
            # or if you don't care about the specific column
            # indexes.append(index)
            seen.add(index.row())
    return indexes
</code>```

Body:
If you are using a view where the selection behaviour is to select rows, the simplest method would be this:

def selected_rows(self, selection):
    indexes = []
    for index in selection.indexes():
        if index.column() == 0:
            indexes.append(index)
    return indexes

A somewhat shorter (but not much faster) alternative to the above would be:

from itertools import filterfalse

def selected_rows(self, selection):
    return list(filterfalse(QtCore.QModelIndex.column, selection.indexes()))

However, if the selection behaviour is to select items, you would need this:

def selected_rows(self, selection):
    seen = set()
    indexes = []
    model = self.tree.model()
    for index in selection.indexes():
        if index.row() not in seen:
            indexes.append(model.index(index.row(), 0))
            # or if you don't care about the specific column
            # indexes.append(index)
            seen.add(index.row())
    return indexes


问:
php code, is it slow or wrong?
"multiple annotations found at this line"

i have been using aptana and other IDE before, but never gave me this error, but yesterday i installed zend studio and it was giving following error in all my code where i have assigned and also check if condition at same time.

```<code>code:
line 16: if ($message_array = @unserialize($e->getMessage()))
line 17:    $message = $message_array;
</code>```

on all if condition, where i assigned the value to a variable and also check if the variable is true/false, it gives me error "multiple annotations found at this line"

答:
Yeah, that syntax is typically flagged by most decent IDEs as "Accidental Assignment" (since it's not obvious if you meant = or ==).  Most will allow you to wrap it in a () to silence the error (since then it's apparent you want the result rather than a test):

```<code>if (($message_array = @unserialize($e->getMessage()))) {
}
</code>```

Also, for readability and maintainability, I would suggest a few things there.

First, use braces.  Since it's only a special case that lets you not use them, I personally think it's better form to always use them so that it's clear what was meant.

Second, do all asignment outside of the if clause.  It makes it more explicit and easier to tell at a quick glance what you meant.  Plus it looks less cluttered.

```<code>$message_array = @unserialize($e->getMessage());
if ($message_array) {
    ...
}
</code>```

Third, I would suggest avoiding the @ operator.  To me it's a sign of code-rot.  While I know it's easy to use and easier than properly handling the error, I think it's just a short-cut that will make life harder for you.  You can avoid it in a few ways.  First, you can check the string before you pass it to unserialize.  Make sure it's non-empty, a string, etc.  Secondly, you can install an error handler to throw exceptions on PHP errors (what I do).  That way, you just wrap the unserialize call in a try {} catch(){} block.  It's nicer since you actually can inspect the error rather than just trusting that the thrown error is what you think it is...

Title: php code, is it slow or wrong?

Body:
"multiple annotations found at this line"

i have been using aptana and other IDE before, but never gave me this error, but yesterday i installed zend studio and it was giving following error in all my code where i have assigned and also check if condition at same time.

code:
line 16: if ($message_array = @unserialize($e->getMessage()))
line 17:    $message = $message_array;

on all if condition, where i assigned the value to a variable and also check if the variable is true/false, it gives me error "multiple annotations found at this line"

Body:
Yeah, that syntax is typically flagged by most decent IDEs as "Accidental Assignment" (since it's not obvious if you meant = or ==).  Most will allow you to wrap it in a () to silence the error (since then it's apparent you want the result rather than a test):

if (($message_array = @unserialize($e->getMessage()))) {
}

Also, for readability and maintainability, I would suggest a few things there.

First, use braces.  Since it's only a special case that lets you not use them, I personally think it's better form to always use them so that it's clear what was meant.

Second, do all asignment outside of the if clause.  It makes it more explicit and easier to tell at a quick glance what you meant.  Plus it looks less cluttered.

$message_array = @unserialize($e->getMessage());
if ($message_array) {
    ...
}

Third, I would suggest avoiding the @ operator.  To me it's a sign of code-rot.  While I know it's easy to use and easier than properly handling the error, I think it's just a short-cut that will make life harder for you.  You can avoid it in a few ways.  First, you can check the string before you pass it to unserialize.  Make sure it's non-empty, a string, etc.  Secondly, you can install an error handler to throw exceptions on PHP errors (what I do).  That way, you just wrap the unserialize call in a try {} catch(){} block.  It's nicer since you actually can inspect the error rather than just trusting that the thrown error is what you think it is...


问:
Python won't print anything past my def in my Text Adventure
```<code>#Asks player for their name and whether they wish to enter or not
character_name = input(" Welcome to The Tenabris Manor, what is your
name?:")
print("")
print(" The towering gates stand before you to the large Manor, do you
enter?")
print("")
inp = ""
while inp != "enter" and inp != "leave":
inp = input(" enter enter or leave: ")
if inp != "enter" and inp != "leave":
    print(" You must type enter or leave")

if inp == "enter":
print(" You push with all your might on the large gates, it swings open with
a loud clunk.")
if inp == "leave":
print("")
print(" You turn around and go back, probably for the best.")
print("")
print(" Your character", character_name, "turned back and never returned.")
input(" Press enter to exit")
SystemExit("")

def choose_room():
#key = False is so the person does not have the key until going upstairs
global key
key = False
while True:
    print("")
    print(" Bookshelfs line the walls, a staircase is to the left and a door
is straight ahead.")
    print("")
    print(" Type 'a' to: Go up the stairs")
    print(" Type 'b' to: To go through the door")
    print(" Type 'c' to: To check the bookshelfs")
    ans = input("")
    if ans=='a':
        print(" You walk up the creaking stairs")
        print(" At the top of the spiral staircase is a small observatory.")
        print(" Looking around on some of stacks of books littering the room
you")
        print(" find a small key!")
        key = True
        continue
    elif ans=='b':
#The door detects whether the key is True or not/they have the key or not.
         if key == True:
             print(" You open the door with the small key.")
         elif key == False:
             print(" The door is locked, you will need a key to go through
it.")
             continue
             return
             choose_room()
         else:
             print("The door is locked, you will need a key to go through
it.")
             continue
             return
             choose_room()

    else:
        ans == 'c'
        print(" You look through the thousands of books.")
        print(" None of them interest you.")
        continue
        return
    choose_room()
</code>```

Excuse my terrible Coding, this is my first project and I am surprised it works in the first place.

Also this is my first post on stack overflow.

My problem is this code worked perfectly did everything I needed it to, but then when I went to add some more detail to it, I decided to do that later and deleted everything I "added" now the code doesn't run anything but the first part before def choose_room():

No error message appears when I run it, it just does the first part then ignores the bit at "def choose_room():" completely.

Well that's all I can think of to add that might help find the cause. Next time I will make a copy of the file before changing anything so this doesn't happen again.

If nobody can find what the problem is, I will just try to remake the program from scratch again.

答:
In Python, indentation is part of the syntax, so if you have things improperly indented your code won't behave as you would expect it to.

Corrected indentation:

```<code>#Asks player for their name and whether they wish to enter or not
character_name = input(" Welcome to The Tenabris Manor, what is your name?:")
print("")
print(" The towering gates stand before you to the large Manor, do you enter?")
print("")
inp = ""
while inp != "enter" and inp != "leave":
    inp = input(" enter enter or leave: ")
    if inp != "enter" and inp != "leave":
        print(" You must type enter or leave")

    if inp == "enter":
        print(" You push with all your might on the large gates, it swings open with a loud clunk.")
    if inp == "leave":
        print("")
        print(" You turn around and go back, probably for the best.")
        print("")
        print(" Your character", character_name, "turned back and never returned.")
        input(" Press enter to exit")
        SystemExit("")

def choose_room():
    #key = False is so the person does not have the key until going upstairs
    global key
    key = False
    while True:
        print("")
        print(" Bookshelfs line the walls, a staircase is to the left and a door is straight ahead.")
        print("")
        print(" Type 'a' to: Go up the stairs")
        print(" Type 'b' to: To go through the door")
        print(" Type 'c' to: To check the bookshelfs")
        ans = input("")
        if ans=='a':
            print(" You walk up the creaking stairs")
            print(" At the top of the spiral staircase is a small observatory.")
            print(" Looking around on some of stacks of books littering the room you")
            print(" find a small key!")
            key = True
            continue
        elif ans=='b':
             #The door detects whether the key is True or not/they have the key or not.
             if key == True:
                 print(" You open the door with the small key.")
             elif key == False:
                 print(" The door is locked, you will need a key to go through it.")
                 continue
                 return
                 choose_room()
             else:
                 print("The door is locked, you will need a key to go through it.")
                 continue
                 return
                 choose_room()

        else:
            ans == 'c'
            print(" You look through the thousands of books.")
            print(" None of them interest you.")
            continue
            return
choose_room()
</code>```

Body:
#Asks player for their name and whether they wish to enter or not
character_name = input(" Welcome to The Tenabris Manor, what is your
name?:")
print("")
print(" The towering gates stand before you to the large Manor, do you
enter?")
print("")
inp = ""
while inp != "enter" and inp != "leave":
inp = input(" enter enter or leave: ")
if inp != "enter" and inp != "leave":
    print(" You must type enter or leave")

if inp == "enter":
print(" You push with all your might on the large gates, it swings open with
a loud clunk.")
if inp == "leave":
print("")
print(" You turn around and go back, probably for the best.")
print("")
print(" Your character", character_name, "turned back and never returned.")
input(" Press enter to exit")
SystemExit("")

def choose_room():
#key = False is so the person does not have the key until going upstairs
global key
key = False
while True:
    print("")
    print(" Bookshelfs line the walls, a staircase is to the left and a door
is straight ahead.")
    print("")
    print(" Type 'a' to: Go up the stairs")
    print(" Type 'b' to: To go through the door")
    print(" Type 'c' to: To check the bookshelfs")
    ans = input("")
    if ans=='a':
        print(" You walk up the creaking stairs")
        print(" At the top of the spiral staircase is a small observatory.")
        print(" Looking around on some of stacks of books littering the room
you")
        print(" find a small key!")
        key = True
        continue
    elif ans=='b':
#The door detects whether the key is True or not/they have the key or not.
         if key == True:
             print(" You open the door with the small key.")
         elif key == False:
             print(" The door is locked, you will need a key to go through
it.")
             continue
             return
             choose_room()
         else:
             print("The door is locked, you will need a key to go through
it.")
             continue
             return
             choose_room()

    else:
        ans == 'c'
        print(" You look through the thousands of books.")
        print(" None of them interest you.")
        continue
        return
    choose_room()

Excuse my terrible Coding, this is my first project and I am surprised it works in the first place.

Also this is my first post on stack overflow.

My problem is this code worked perfectly did everything I needed it to, but then when I went to add some more detail to it, I decided to do that later and deleted everything I "added" now the code doesn't run anything but the first part before def choose_room():

No error message appears when I run it, it just does the first part then ignores the bit at "def choose_room():" completely.

Well that's all I can think of to add that might help find the cause. Next time I will make a copy of the file before changing anything so this doesn't happen again.

If nobody can find what the problem is, I will just try to remake the program from scratch again.

Body:
In Python, indentation is part of the syntax, so if you have things improperly indented your code won't behave as you would expect it to.

Corrected indentation:

#Asks player for their name and whether they wish to enter or not
character_name = input(" Welcome to The Tenabris Manor, what is your name?:")
print("")
print(" The towering gates stand before you to the large Manor, do you enter?")
print("")
inp = ""
while inp != "enter" and inp != "leave":
    inp = input(" enter enter or leave: ")
    if inp != "enter" and inp != "leave":
        print(" You must type enter or leave")

    if inp == "enter":
        print(" You push with all your might on the large gates, it swings open with a loud clunk.")
    if inp == "leave":
        print("")
        print(" You turn around and go back, probably for the best.")
        print("")
        print(" Your character", character_name, "turned back and never returned.")
        input(" Press enter to exit")
        SystemExit("")

def choose_room():
    #key = False is so the person does not have the key until going upstairs
    global key
    key = False
    while True:
        print("")
        print(" Bookshelfs line the walls, a staircase is to the left and a door is straight ahead.")
        print("")
        print(" Type 'a' to: Go up the stairs")
        print(" Type 'b' to: To go through the door")
        print(" Type 'c' to: To check the bookshelfs")
        ans = input("")
        if ans=='a':
            print(" You walk up the creaking stairs")
            print(" At the top of the spiral staircase is a small observatory.")
            print(" Looking around on some of stacks of books littering the room you")
            print(" find a small key!")
            key = True
            continue
        elif ans=='b':
             #The door detects whether the key is True or not/they have the key or not.
             if key == True:
                 print(" You open the door with the small key.")
             elif key == False:
                 print(" The door is locked, you will need a key to go through it.")
                 continue
                 return
                 choose_room()
             else:
                 print("The door is locked, you will need a key to go through it.")
                 continue
                 return
                 choose_room()

        else:
            ans == 'c'
            print(" You look through the thousands of books.")
            print(" None of them interest you.")
            continue
            return
choose_room()


问:
Get arguments and file name from specific path
I'm trying to extract argument and file name from path like below:

```<code>C:\Users\user\Desktop\foo.exe foo://action/bar
</code>```

I tried to use Path.GetFileName but since argument contains directory separators, it returns bar instead of foo.exe

Is there any way to get argument and file name?

答:
You can get the command line argument from the string [] args passed to the Main method.

Or you can use the static method Environment.GetCommandLineArgs https://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx

Body:
I'm trying to extract argument and file name from path like below:

C:\Users\user\Desktop\foo.exe foo://action/bar

I tried to use Path.GetFileName but since argument contains directory separators, it returns bar instead of foo.exe

Is there any way to get argument and file name?


答:
You defined the function choose_room() but never used/called it. It would go something like this.

```<code>#...
if inp == "enter":
    print(" You push with all your might on the large gates, it swings open with a loud clunk.")
    choose_room()
#...
</code>```

Make sure to define the function before calling it. Place the def choose_room():... on top of the script or before actually choose_room

Title: Python won't print anything past my def in my Text Adventure

Body:
You defined the function choose_room() but never used/called it. It would go something like this.

#...
if inp == "enter":
    print(" You push with all your might on the large gates, it swings open with a loud clunk.")
    choose_room()
#...

Make sure to define the function before calling it. Place the def choose_room():... on top of the script or before actually choose_room


问:
Clickhouse connection refuse
I have a problem with connection to clickhouse-server by http over 8123 port. All parameters are default.

```<code>Status: Downloaded newer image for yandex/clickhouse-server:latest
Include not found: clickhouse_remote_servers
Include not found: clickhouse_compression
2017.11.09 13:05:37.975332 [ 1 ] <Warning> Application: Logging to console
2017.11.09 13:05:37.978638 [ 1 ] <Information> : Starting daemon with revision 54310
2017.11.09 13:05:37.978733 [ 1 ] <Information> Application: starting up
2017.11.09 13:05:37.979947 [ 1 ] <Debug> Application: rlimit on number of file descriptors is 1048576
2017.11.09 13:05:37.979979 [ 1 ] <Debug> Application: Initializing DateLUT.
2017.11.09 13:05:37.980015 [ 1 ] <Trace> Application: Initialized DateLUT with time zone Zulu'.
2017.11.09 13:05:37.980651 [ 1 ] <Debug> Application: Configuration parameter 'interserver_http_host' doesn't exist or exists and empty. Will use 'c9a1a0a75b97' as replica host.
2017.11.09 13:05:37.980783 [ 1 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/users.xml'
2017.11.09 13:05:37.983605 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.983633 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.984168 [ 1 ] <Information> Application: Loading metadata.
2017.11.09 13:05:37.984738 [ 1 ] <Information> DatabaseOrdinary (default): Total 0 tables.
2017.11.09 13:05:37.984766 [ 1 ] <Information> DatabaseOrdinary (default): Starting up tables.
2017.11.09 13:05:37.984999 [ 1 ] <Debug> Application: Loaded metadata.
2017.11.09 13:05:37.985454 [ 1 ] <Information> Application: Listening http://0.0.0.0:8123
2017.11.09 13:05:37.987644 [ 1 ] <Information> Application: Listening tcp: 0.0.0.0:9000
2017.11.09 13:05:37.987692 [ 1 ] <Information> Application: Listening interserver: 0.0.0.0:9009
2017.11.09 13:05:37.988186 [ 1 ] <Information> Application: Available RAM = 1.95 GiB; physical cores = 4; threads = 4.
2017.11.09 13:05:37.988212 [ 1 ] <Information> Application: Ready for connections.
2017.11.09 13:05:39.980980 [ 2 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/config.xml'
2017.11.09 13:05:39.985393 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_remote_servers
2017.11.09 13:05:39.985462 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_compression

$ curl 'http://localhost:8123/'
curl: (7) Failed to connect to localhost port 8123: Connection refused
</code>```

Please help me to resolve this problem.

答:
First of all check if even you clickhouse-server is running properly or not using this command:

sudo lsof -i :8123

You should be able to see a similar output:

```<code>COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME

clickhous 8752 root    9u  IPv6  38265      0t0  TCP ip6-localhost:8123 (LISTEN)

clickhous 8752 root   12u  IPv4  38268      0t0  TCP localhost:8123 (LISTEN)
</code>```

Make sure that you have these entries in the config.xml file located at /etc/clickhouse-server

```<code><listen_host>::1</listen_host>
<!-- Localhost Binding -->
<listen_host>127.0.0.1</listen_host>
<!-- Remote Access Binding -->
<listen_host>< IP / URL></listen_host>
</code>```

Once you make sure these entries exist, run these commands to restart your server:

```<code>cd /usr/bin
sudo ./clickhouse-server --config /etc/clickhouse-server/config.xml &
</code>```

Again execute sudo lsof -i :8123 to see if your clickhouse-server is listening at that port.

Title: Clickhouse connection refuse

Body:
I have a problem with connection to clickhouse-server by http over 8123 port. All parameters are default.

Status: Downloaded newer image for yandex/clickhouse-server:latest
Include not found: clickhouse_remote_servers
Include not found: clickhouse_compression
2017.11.09 13:05:37.975332 [ 1 ] <Warning> Application: Logging to console
2017.11.09 13:05:37.978638 [ 1 ] <Information> : Starting daemon with revision 54310
2017.11.09 13:05:37.978733 [ 1 ] <Information> Application: starting up
2017.11.09 13:05:37.979947 [ 1 ] <Debug> Application: rlimit on number of file descriptors is 1048576
2017.11.09 13:05:37.979979 [ 1 ] <Debug> Application: Initializing DateLUT.
2017.11.09 13:05:37.980015 [ 1 ] <Trace> Application: Initialized DateLUT with time zone Zulu'.
2017.11.09 13:05:37.980651 [ 1 ] <Debug> Application: Configuration parameter 'interserver_http_host' doesn't exist or exists and empty. Will use 'c9a1a0a75b97' as replica host.
2017.11.09 13:05:37.980783 [ 1 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/users.xml'
2017.11.09 13:05:37.983605 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.983633 [ 1 ] <Warning> ConfigProcessor: Include not found: networks
2017.11.09 13:05:37.984168 [ 1 ] <Information> Application: Loading metadata.
2017.11.09 13:05:37.984738 [ 1 ] <Information> DatabaseOrdinary (default): Total 0 tables.
2017.11.09 13:05:37.984766 [ 1 ] <Information> DatabaseOrdinary (default): Starting up tables.
2017.11.09 13:05:37.984999 [ 1 ] <Debug> Application: Loaded metadata.
2017.11.09 13:05:37.985454 [ 1 ] <Information> Application: Listening http://0.0.0.0:8123
2017.11.09 13:05:37.987644 [ 1 ] <Information> Application: Listening tcp: 0.0.0.0:9000
2017.11.09 13:05:37.987692 [ 1 ] <Information> Application: Listening interserver: 0.0.0.0:9009
2017.11.09 13:05:37.988186 [ 1 ] <Information> Application: Available RAM = 1.95 GiB; physical cores = 4; threads = 4.
2017.11.09 13:05:37.988212 [ 1 ] <Information> Application: Ready for connections.
2017.11.09 13:05:39.980980 [ 2 ] <Debug> ConfigReloader: Loading config /etc/clickhouse-server/config.xml'
2017.11.09 13:05:39.985393 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_remote_servers
2017.11.09 13:05:39.985462 [ 2 ] <Warning> ConfigProcessor: Include not found: clickhouse_compression

$ curl 'http://localhost:8123/'
curl: (7) Failed to connect to localhost port 8123: Connection refused

Please help me to resolve this problem.

Body:
First of all check if even you clickhouse-server is running properly or not using this command:

sudo lsof -i :8123

You should be able to see a similar output:

COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME

clickhous 8752 root    9u  IPv6  38265      0t0  TCP ip6-localhost:8123 (LISTEN)

clickhous 8752 root   12u  IPv4  38268      0t0  TCP localhost:8123 (LISTEN)

Make sure that you have these entries in the config.xml file located at /etc/clickhouse-server

<listen_host>::1</listen_host>
<!-- Localhost Binding -->
<listen_host>127.0.0.1</listen_host>
<!-- Remote Access Binding -->
<listen_host>< IP / URL></listen_host>

Once you make sure these entries exist, run these commands to restart your server:

cd /usr/bin
sudo ./clickhouse-server --config /etc/clickhouse-server/config.xml &

Again execute sudo lsof -i :8123 to see if your clickhouse-server is listening at that port.


问:
What does it mean for a dropout layer to be trainable in keras?
Keras implements dropout as a layer (just like Dense or Conv2D). Any layer has the trainable property that can be set to false if you want to freeze the weights. What does it mean for the dropout layer to be trainable, since there are no weights involved here?</p>

答:
When the layer has no weights, the trainable parameter is irrelevant. </p>

<p>In Keras, the trainable parameters just defines if the weights are going to be constant or not. </p>

Body:
When the layer has no weights, the trainable parameter is irrelevant.

In Keras, the trainable parameters just defines if the weights are going to be constant or not.