问:
Install mongo db and start mongo service using WiX toolset installer
I am creating a .msi installer using WiX Toolset which will:-
1. Install mongo db on client machine by running its mongodb-win32-x86_64-2008plus-ssl-3.4.4-signed.msi
2. Make directories for \data\db and \log and config file
3. Start mongo service as a Window service.

I am new to Wix. I was able to set it up and create a installer which is packaging mongo setup msi and config file to Wix installer. But it is just copying these files to install flocation. I want all the above steps to performed by WiX installer. Below are important section:-

```<code><Directory Id='TARGETDIR' Name='SourceDir'>
      <Directory Id='EMERSONMONGO' Name="$(var.rootFolder)">
        <Directory Id='PFWMONGOFOLDER' Name='$(var.subRootFolder)'>
          <Directory Id='MONGO' Name='$(var.installFolder)'>
            <Component Id="mongodb.msi" Guid="99B82660-F66B-4012-B742-D875623B1C16">
                <File Id="mongodb.msi" Source="$(var.mongoSourceDir)\mongodb-win32-x86_64-2008plus-ssl-3.4.4-signed.msi" KeyPath="yes" Checksum="yes"/>
            </Component>
          </Directory>
        </Directory>
      </Directory>
    </Directory>

<Feature Id='Complete' Title='PFWMongo Installer' Description='PFWMongo Installer' Level='1'>
      <ComponentRef Id="mongodb.msi" />
 </Feature>

<CustomAction Id="RunMongoMsi" Return="ignore" Execute="deferred"
                  FileKey="mongodb.msi" ExeCommand=""
                  HideTarget="no" Impersonate="no" />

<InstallExecuteSequence>
        <Custom Action='RunMongoMsi' Before='InstallFinalize'/>
        <RemoveExistingProducts After="InstallInitialize" >
             UNINSTALLPREVVERSIONS
        </RemoveExistingProducts>
        <Custom Action="NewerVersion" After="FindRelatedProducts">NEWERVERSIONDETECTED</Custom>
</InstallExecuteSequence>
</code>```

Any help is much appreciated.

答:
What you want to do is use the WiX Bootstrapper/Burn for this. You would then add the install to the chain similar to this.

<Chain>
      <MsiPackage Id="mongodb.msi" SourceFile="$(var.mongoSourceDir)\mongodb-win32-x86_64-2008plus-ssl-3.4.4-signed.msi" EnableFeatureSelection="yes" DisplayInternalUI="yes" Compressed="yes" Visible="yes" />
</Chain>

Body:
I am creating a .msi installer using WiX Toolset which will:-
1. Install mongo db on client machine by running its mongodb-win32-x86_64-2008plus-ssl-3.4.4-signed.msi
2. Make directories for \data\db and \log and config file
3. Start mongo service as a Window service.

I am new to Wix. I was able to set it up and create a installer which is packaging mongo setup msi and config file to Wix installer. But it is just copying these files to install flocation. I want all the above steps to performed by WiX installer. Below are important section:-

<Directory Id='TARGETDIR' Name='SourceDir'>
      <Directory Id='EMERSONMONGO' Name="$(var.rootFolder)">
        <Directory Id='PFWMONGOFOLDER' Name='$(var.subRootFolder)'>
          <Directory Id='MONGO' Name='$(var.installFolder)'>
            <Component Id="mongodb.msi" Guid="99B82660-F66B-4012-B742-D875623B1C16">
                <File Id="mongodb.msi" Source="$(var.mongoSourceDir)\mongodb-win32-x86_64-2008plus-ssl-3.4.4-signed.msi" KeyPath="yes" Checksum="yes"/>
            </Component>
          </Directory>
        </Directory>
      </Directory>
    </Directory>

<Feature Id='Complete' Title='PFWMongo Installer' Description='PFWMongo Installer' Level='1'>
      <ComponentRef Id="mongodb.msi" />
 </Feature>

<CustomAction Id="RunMongoMsi" Return="ignore" Execute="deferred"
                  FileKey="mongodb.msi" ExeCommand=""
                  HideTarget="no" Impersonate="no" />

<InstallExecuteSequence>
        <Custom Action='RunMongoMsi' Before='InstallFinalize'/>
        <RemoveExistingProducts After="InstallInitialize" >
             UNINSTALLPREVVERSIONS
        </RemoveExistingProducts>
        <Custom Action="NewerVersion" After="FindRelatedProducts">NEWERVERSIONDETECTED</Custom>
</InstallExecuteSequence>

Any help is much appreciated.


来源: stackexchange

问:
Pyspark - Using reducebykey on spark dataframe column that is lists
So I have a spark dataframe called ngram_df that looks something like this

```<code>--------------------------------
 Name   | nGrams               |
--------|--------------------- |
 Alice  | [ALI, LIC, ICE]      |
 Alicia | [ALI, LIC, ICI, CIA] |
--------------------------------
</code>```

And I want to produce an output in a dictionary form such as:

ALI: 2, LIC: 2, ICE: 1, ICI: 1, CIA: 1

I've been trying to turn the nGrams column into a RDD so that I can use the reduceByKey function

```<code>rdd = ngram_df.map(lambda row: row['nGrams'])
test = rdd.reduceByKey(add).collect()
</code>```

However I get the error:

ValueError: too many values to unpack

Even using flatmap doesn't help as I get the error:

ValueError: need more than 1 value to unpack

答:
this is possible with a combination of flatMap and reduceByKey method.</p>

```<code>rdd = spark.sparkContext.parallelize([('Alice', ['ALI', 'LIC', 'ICE']), ('Alicia', ['ALI', 'LIC', 'ICI', 'CIA'])])

result = rdd.flatMap(lambda x: [(y, 1) for y in x[1]] ).reduceByKey(lambda x,y: x+y)

result.collect()
[('ICI', 1), ('CIA', 1), ('ALI', 2), ('ICE', 1), ('LIC', 2)]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have a spark dataframe called ngram_df that looks something like this

--------------------------------
 Name   | nGrams               |
--------|--------------------- |
 Alice  | [ALI, LIC, ICE]      |
 Alicia | [ALI, LIC, ICI, CIA] |
--------------------------------

And I want to produce an output in a dictionary form such as:

ALI: 2, LIC: 2, ICE: 1, ICI: 1, CIA: 1

I've been trying to turn the nGrams column into a RDD so that I can use the reduceByKey function

rdd = ngram_df.map(lambda row: row['nGrams'])
test = rdd.reduceByKey(add).collect()

However I get the error:

ValueError: too many values to unpack

Even using flatmap doesn't help as I get the error:

ValueError: need more than 1 value to unpack

Body:
this is possible with a combination of flatMap and reduceByKey method.

rdd = spark.sparkContext.parallelize([('Alice', ['ALI', 'LIC', 'ICE']), ('Alicia', ['ALI', 'LIC', 'ICI', 'CIA'])])

result = rdd.flatMap(lambda x: [(y, 1) for y in x[1]] ).reduceByKey(lambda x,y: x+y)

result.collect()
[('ICI', 1), ('CIA', 1), ('ALI', 2), ('ICE', 1), ('LIC', 2)]


问:
Unexpected output with python `normpath`
I am trying to convert Windows file path to Unix using os.path.normpath. I am getting unexpected characters in file path.

```<code>import os
path1 = 'C:\Users\abcd\dir1'
path2 = os.path.normpath(path1)
path2
</code>```

I want to replace "\" by "/". But output is  'C:\\Users\x07bcd\\dir1'. I am wondering how x07` comes in the picture and how to get rid of it.

Alternatively, I tried regex to replace "\" by "/".

Desired output is: 'C:/Users/abcd/dir1'

I tried using answer of Python how to replace backslash with re.sub() but could not get it to work.
If I want to use it, can someone suggest how to do it?

path3 = re.sub(path1 +"\\" "//")

But there is error. I am new to python, so could not figure out proper syntax.

答:
Use raw string or double slash in this case :

```<code>path1 = 'C:\\Users\\abcd\dir1'
</code>```

or

```<code>path1 = r'C:\Users\abcd\dir1'
</code>```

Body:
I am trying to convert Windows file path to Unix using os.path.normpath. I am getting unexpected characters in file path.

import os
path1 = 'C:\Users\abcd\dir1'
path2 = os.path.normpath(path1)
path2

I want to replace "\" by "/". But output is  'C:\\Users\x07bcd\\dir1'. I am wondering how x07` comes in the picture and how to get rid of it.

Alternatively, I tried regex to replace "\" by "/".

Desired output is: 'C:/Users/abcd/dir1'

I tried using answer of Python how to replace backslash with re.sub() but could not get it to work.
If I want to use it, can someone suggest how to do it?

path3 = re.sub(path1 +"\\" "//")

But there is error. I am new to python, so could not figure out proper syntax.

Body:
Use raw string or double slash in this case :

path1 = 'C:\\Users\\abcd\dir1'

or

path1 = r'C:\Users\abcd\dir1'


问:
How to find elapsed time interval
```<code>void Wait(Single wait_time)
{
    Single start_time;
    Single end_time;
    Single ellapsed_time;

    ellapsed_time = 0;
    start_time = DateTime.Now.Second;
    while (ellapsed_time<=wait_time)
    {
        end_time = DateTime.Now.Second;
        ellapsed_time = end_time - start_time;
    }
}
</code>```

The code above is in C# and it works according to my colleague. The goal is to tell the machine to wait for a certain time, then continue after that. For example, when Wait(5) is triggered, the machine won't continue until elapsed time is greater than 5.  I'm trying to do the same thing in C++/CLI. Here is my code :

```<code>void Wait(Single wait_time)
{
    Single start_time;
    Single end_time;
    Single ellapsed_time;

    ellapsed_time = 0;
    start_time = DateTime::Now;

    while (ellapsed_time <= wait_time) {
        end_time = DateTime::Now;
        ellapsed_time = end_time - start_time;

    }

}
</code>```

I get this error:

no suitable conversion function from System::DateTime to float exists

I tried TimeSpan as well, but it didn't work. Is there a better way to do this?

答:
C++/CLI

```<code>using namespace System::Threading;

void wait(int seconds)
{
    //1000 miliseconds = 1 second
    Thread::Sleep(seconds * 1000);
}

int main()
{
    std::cout << "test1" << std::endl;
    wait(5);  // wait for 5 secs
    std::cout << "test2" << std::endl;
}
</code>```

Side note, you wouldn't want to waste precious CPU cycles going through a redundant loop. Give it a break!

Title: How to find elapsed time interval

Body:
void Wait(Single wait_time)
{
    Single start_time;
    Single end_time;
    Single ellapsed_time;

    ellapsed_time = 0;
    start_time = DateTime.Now.Second;
    while (ellapsed_time<=wait_time)
    {
        end_time = DateTime.Now.Second;
        ellapsed_time = end_time - start_time;
    }
}

The code above is in C# and it works according to my colleague. The goal is to tell the machine to wait for a certain time, then continue after that. For example, when Wait(5) is triggered, the machine won't continue until elapsed time is greater than 5.  I'm trying to do the same thing in C++/CLI. Here is my code :

void Wait(Single wait_time)
{
    Single start_time;
    Single end_time;
    Single ellapsed_time;

    ellapsed_time = 0;
    start_time = DateTime::Now;

    while (ellapsed_time <= wait_time) {
        end_time = DateTime::Now;
        ellapsed_time = end_time - start_time;

    }

}

I get this error:

no suitable conversion function from System::DateTime to float exists

I tried TimeSpan as well, but it didn't work. Is there a better way to do this?

Body:
C++/CLI

using namespace System::Threading;

void wait(int seconds)
{
    //1000 miliseconds = 1 second
    Thread::Sleep(seconds * 1000);
}

int main()
{
    std::cout << "test1" << std::endl;
    wait(5);  // wait for 5 secs
    std::cout << "test2" << std::endl;
}

Side note, you wouldn't want to waste precious CPU cycles going through a redundant loop. Give it a break!


问:
Javascript document.getElement innerHTML undefined
I am trying to make the outcome of a function appear in a  element outside the script. Instead of the outcome I get an "undefined" message. It is probably just a matter of syntax, but I don't get it to work.

Here is what I did:

1 + 2 =

here goes the range of solutions to select of

here goes the quote

<form id="myForm">

</FORM>

```

So, what I want is the following:

- show the range of answers to select from within the span above.

- show the answer (correct/not correct) in the span above.

Well, maybe it is possible to make the whole code more elegant, but these are my predominant problems here.

答:
The reason you're getting undefined is that you never return anything from the function which is assigned to the variable sr (and subsequently set as the content of a div with that same id)

```<code>var sr = (function(val) {
    btn = document.createElement('button');
    btn.data = val;
    btn.innerHTML = val;
    btn.addEventListener('click', checkAnswer);
    document.body.appendChild(btn);
})(myarray[i]);
document.getElementById("sr").innerHTML = sr;
              sr has the value undefined --^
</code>```

It is not clear what you meant to put as the innerHTML of the div with an id of sr.

Body:
I am trying to make the outcome of a function appear in a  element outside the script. Instead of the outcome I get an "undefined" message. It is probably just a matter of syntax, but I don't get it to work.

Here is what I did:

1 + 2 =

here goes the range of solutions to select of

here goes the quote

<form id="myForm">

</FORM>

So, what I want is the following:

- show the range of answers to select from within the span above.

- show the answer (correct/not correct) in the span above.

Well, maybe it is possible to make the whole code more elegant, but these are my predominant problems here.

Body:
The reason you're getting undefined is that you never return anything from the function which is assigned to the variable sr (and subsequently set as the content of a div with that same id)

var sr = (function(val) {
    btn = document.createElement('button');
    btn.data = val;
    btn.innerHTML = val;
    btn.addEventListener('click', checkAnswer);
    document.body.appendChild(btn);
})(myarray[i]);
document.getElementById("sr").innerHTML = sr;
              sr has the value undefined --^

It is not clear what you meant to put as the innerHTML of the div with an id of sr.


问:
How to run traci.start for Sumo simulation
I have sumo 0.29 and traci it's supposed to be automatically implemented on this version.

I'm running the traci_tls tutorial and I want to get the execution time in real time and not in steps as the GUI gives.

I'm getting this error in CLI. when executing the GUI.

```<code>traci_tls ./runner16.py Could not connect to TraCI server at
localhost:51595 [Errno 111] Connection refused  Retrying in 1 seconds
Loading configuration... done.
</code>```

Any idea? Thanks.

答: This is not a severe error message, it is more like a warning. It is just saying that the first connection attempt failed probably because the GUI was slow to start. As the message says it will retry and I suppose the second attempt was successful (at least if there are no more messages below).</p>

Body:
I have sumo 0.29 and traci it's supposed to be automatically implemented on this version.

I'm running the traci_tls tutorial and I want to get the execution time in real time and not in steps as the GUI gives.

I'm getting this error in CLI. when executing the GUI.

traci_tls ./runner16.py Could not connect to TraCI server at
localhost:51595 [Errno 111] Connection refused  Retrying in 1 seconds
Loading configuration... done.

Any idea? Thanks.


问:
Suggestive Search From JS Array, Possible?
Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.

So imagine a javascript object or array that is full of people's names:

```<code>var array = (jack,tom,john,sarah,barry,...etc);
</code>```

I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.

I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.

Hope someone can help me with this!

W.

答:
as the name suggests, this finds elements of an array starting with the given string s. </p>

```<code>Array.prototype.findElementsStartingWith = function(s) {
   var r = [];
   for(var i = 0; i < this.length; i++)
      if(this[i].toString().indexOf(s) === 0)
         r.push(this[i]);
   return r;
}

// example

a = ["foo", "bar", "fooba", "quu", "foooba"];
console.log(a.findElementsStartingWith("fo"))
</code>```

<p>the rest is basically the same as in ajax-based scripts. </p>

ContentLicense: CC BY-SA 2.5

Body:
Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.

So imagine a javascript object or array that is full of people's names:

var array = (jack,tom,john,sarah,barry,...etc);

I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.

I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.

Hope someone can help me with this!

W.

Body:
as the name suggests, this finds elements of an array starting with the given string s.

Array.prototype.findElementsStartingWith = function(s) {
   var r = [];
   for(var i = 0; i < this.length; i++)
      if(this[i].toString().indexOf(s) === 0)
         r.push(this[i]);
   return r;
}

// example

a = ["foo", "bar", "fooba", "quu", "foooba"];
console.log(a.findElementsStartingWith("fo"))

the rest is basically the same as in ajax-based scripts.


问:
spring Batch flow job Vs spring composed task
I want to execute my apps using spring-complex-task and I have already build complex spring-batch Flow Jobs which executes perfectly fine.

could you please explain what is difference between spring Batch flow job Vs spring composed task? and which is best among them?

答:
A composed task within Spring Cloud Data Flow is actually built on Spring Batch in that the transition from task to task is managed by a dynamically generated Spring Batch job.  This model allows the decomposition of a batch job into reusable parts that can be independently tested, deployed, and orchestrated at a level higher than a job.  This allows for things like writing a single step job that is reusable across multiple workflows.

They are really complimentary.  You can use a composed task within Spring Cloud Data Flow to orchestrate both Spring Cloud Tasks as well as Spring Batch jobs (run as tasks).  It really depends on how you want to slice up your process.  If you have processes that are tightly coupled, package them as a single job.  From there, you can orchestrate them with Spring Cloud Data Flow's composed task functionality.


问:
Symfony 3 Too many parameters
I'm new to Symfony, and I got an error while running a query :

```<code>public function getFilteredArticles($page, $nbPerPage, $data) {
        $query = $this->createQueryBuilder('a')
                ->leftJoin('a.images', 'i')
                ->addSelect('i')
                ->leftJoin('a.type_stockage', 't')
                ->addSelect('t')
                ->leftJoin('a.famille', 'f')
                ->addSelect('f');
        if ($data['famille'] != '') {
            $query->where('f.id = :famille')
                    ->setParameter('famille', $data['famille']);
        }
        if ($data['rds'] == false) {
            $query->where('a.stock_actuel > 0');
        }
        if ($data['recherche'] != '' && $data['recherche'] != null) {
            $query->where('a.ref_article LIKE :recherche')
                    ->setParameter('recherche', '%' . $data['recherche'] . '%');
        }
        $query->leftJoin('a.sousfamille', 's')
                ->orderBy('a.ref_article', 'ASC')
                ->getQuery();

        $query->setFirstResult(($page - 1) * $nbPerPage)
                ->setMaxResults($nbPerPage);

        return new Paginator($query, true);
    }
</code>```

This query have conditionnals parameters as you can see, that returns the list of articles I need for a table. But when I run this query to fill my table, I got the error :

An exception has been thrown during the rendering of a template ("Too
  many parameters: the query defines 0 parameters and you bound 1").

I don't know why he is expecting 0 parameters. I tried using setParameters instead, but the result is the same.

Does anyone has an idea?

答:
You should use andWhere() methods instead of where().

where() method removes all previous where, but setParameter() does not. That's why he found more parameters than where clauses.

I personally never use where if the condition has no sense to be the first condition, to avoid this kinds of errors.

```<code>    if ($data['famille'] != '') {
        $query->andWhere('f.id = :famille')
                ->setParameter('famille', $data['famille']);
    }
    if ($data['rds'] == false) {
        $query->andWhere('a.stock_actuel > 0');
    }
    if ($data['recherche'] != '' && $data['recherche'] != null) {
        $query->andWhere('a.ref_article LIKE :recherche')
                ->setParameter('recherche', '%' . $data['recherche'] . '%');
    }
</code>```

where() php doc

Specifies one or more restrictions to the query result.

    Replaces any previously specified restrictions, if any.

andWhere() php doc

Adds one or more restrictions to the query results, forming a logical
    conjunction with any previously specified restrictions.

Title: Symfony 3 Too many parameters

Body:
I'm new to Symfony, and I got an error while running a query :

public function getFilteredArticles($page, $nbPerPage, $data) {
        $query = $this->createQueryBuilder('a')
                ->leftJoin('a.images', 'i')
                ->addSelect('i')
                ->leftJoin('a.type_stockage', 't')
                ->addSelect('t')
                ->leftJoin('a.famille', 'f')
                ->addSelect('f');
        if ($data['famille'] != '') {
            $query->where('f.id = :famille')
                    ->setParameter('famille', $data['famille']);
        }
        if ($data['rds'] == false) {
            $query->where('a.stock_actuel > 0');
        }
        if ($data['recherche'] != '' && $data['recherche'] != null) {
            $query->where('a.ref_article LIKE :recherche')
                    ->setParameter('recherche', '%' . $data['recherche'] . '%');
        }
        $query->leftJoin('a.sousfamille', 's')
                ->orderBy('a.ref_article', 'ASC')
                ->getQuery();

        $query->setFirstResult(($page - 1) * $nbPerPage)
                ->setMaxResults($nbPerPage);

        return new Paginator($query, true);
    }

This query have conditionnals parameters as you can see, that returns the list of articles I need for a table. But when I run this query to fill my table, I got the error :

An exception has been thrown during the rendering of a template ("Too
  many parameters: the query defines 0 parameters and you bound 1").

I don't know why he is expecting 0 parameters. I tried using setParameters instead, but the result is the same.

Does anyone has an idea?

Body:
You should use andWhere() methods instead of where().

where() method removes all previous where, but setParameter() does not. That's why he found more parameters than where clauses.

I personally never use where if the condition has no sense to be the first condition, to avoid this kinds of errors.

    if ($data['famille'] != '') {
        $query->andWhere('f.id = :famille')
                ->setParameter('famille', $data['famille']);
    }
    if ($data['rds'] == false) {
        $query->andWhere('a.stock_actuel > 0');
    }
    if ($data['recherche'] != '' && $data['recherche'] != null) {
        $query->andWhere('a.ref_article LIKE :recherche')
                ->setParameter('recherche', '%' . $data['recherche'] . '%');
    }

where() php doc

Specifies one or more restrictions to the query result.

    Replaces any previously specified restrictions, if any.

andWhere() php doc

Adds one or more restrictions to the query results, forming a logical
    conjunction with any previously specified restrictions.


问:
Python Sockets - How to shut down the server?
I tried to make a simple chat system with the socket module in Python. everything works, except, that i need to kill the process everytime when i want to shutdown the server. And i don't want to do this everytime.
So my question is:

How can i make a function, that when i type shutdown in the server terminal, it shutdowns the whole server?

I already tried to do this:

def close(self):
    server.close(self)
    server.shutdown(self)

But it doesn't work. When i type close(), nothing happens. Nothing.

Heres the full code of the server.py:
https://pastebin.com/gA4QYmQe
Every help is useful. Thanks.

答:
Well... there are many problems with the code (your "MY IP" and "SERVERIP" are probably not what you want, but this is beside the point.

Your close() function has a "self" parameter, which is pointless as this is not a class. You also need to move the close function to the beginning of your code if you want to call it from your try-except -structure. You need to call shutdown() first and then close(), and shutdown takes an argument. I modified your close() to do this and it works.

```<code>def close():
    server.shutdown(socket.SHUT_RDWR)
    server.close()
    print ("closed")
</code>```

When you open your socket, you should also set SO_REUSEADDR to make the address reusable (meaning you can start the server again if you shut it down, instead of waiting for a minute for TIME_WAIT status to finish with your server port):

```<code>server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
</code>```

But how exactly are you calling close() when you type "shutdown" somewhere? You are not doing this. Your program is in the socket loop and is not reading keyboard input.

I see no point whatsoever adding keyboard input to this program. First, it adds complexity as you are operating with two possibly blocking inputs (socket input and keyboard input) and you would need to manage this. It is possible but definitely complicated. Second, it is faster to press Control + C instead of typing "shutdown" and hitting enter.

You currently do not call close after a keyboard interrupt. I added this to the inner KeyboardInterrupt (the outer you can remove - it is not doing anything and is never reached) and it now shuts down your program neatly, closing all connections. Remember to move close() function from the bottom of your code to the front before the try: statement:

```<code>    except KeyboardInterrupt:
        print("[!] Keyboard Interrupted!")
        close()
        break
</code>```

If you want a remote shutdown (server shuts down if you type "shutdown" to the socket), you can add this to your server loop:

```<code>if message == "shutdown":
    close()
    exit(0)
</code>```

There are other problems as well. For example, if you start your server, connect to it and shut down the connection, your server exits as it does not return to listen().

This is also (in my opinion), somewhat bad programming, as you use "server" as a global variable. I would rather create a class and put all socket operations in it, but if style is not important, this should work.

Hannu

Body:
Well... there are many problems with the code (your "MY IP" and "SERVERIP" are probably not what you want, but this is beside the point.

Your close() function has a "self" parameter, which is pointless as this is not a class. You also need to move the close function to the beginning of your code if you want to call it from your try-except -structure. You need to call shutdown() first and then close(), and shutdown takes an argument. I modified your close() to do this and it works.

def close():
    server.shutdown(socket.SHUT_RDWR)
    server.close()
    print ("closed")

When you open your socket, you should also set SO_REUSEADDR to make the address reusable (meaning you can start the server again if you shut it down, instead of waiting for a minute for TIME_WAIT status to finish with your server port):

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

But how exactly are you calling close() when you type "shutdown" somewhere? You are not doing this. Your program is in the socket loop and is not reading keyboard input.

I see no point whatsoever adding keyboard input to this program. First, it adds complexity as you are operating with two possibly blocking inputs (socket input and keyboard input) and you would need to manage this. It is possible but definitely complicated. Second, it is faster to press Control + C instead of typing "shutdown" and hitting enter.

You currently do not call close after a keyboard interrupt. I added this to the inner KeyboardInterrupt (the outer you can remove - it is not doing anything and is never reached) and it now shuts down your program neatly, closing all connections. Remember to move close() function from the bottom of your code to the front before the try: statement:

    except KeyboardInterrupt:
        print("[!] Keyboard Interrupted!")
        close()
        break

If you want a remote shutdown (server shuts down if you type "shutdown" to the socket), you can add this to your server loop:

if message == "shutdown":
    close()
    exit(0)

There are other problems as well. For example, if you start your server, connect to it and shut down the connection, your server exits as it does not return to listen().

This is also (in my opinion), somewhat bad programming, as you use "server" as a global variable. I would rather create a class and put all socket operations in it, but if style is not important, this should work.

Hannu


问:
Wordpress Doesn't Play Nice When Not FIlling in All Fields When Commenting
When someone tries to make a comment on a Wordpress site I have, and they don't fill in all required fields, I get this weird array output which opens in new page:

http://www.screencast.com/users/iamwill/folders/Jing/media/121b2789-b212-4eb3-a4b1-61eed9fb6f52

This is happening on WP 3.0.3, and WPMU 2.9. Any help would be greatly appreciated in finding out the cause of this issue.

答: From the looks of it, someone forgot a print_r inside the error handling method... you could try finding it and patching it by hand, until an official fix comes around.


问:
Do while loop runs more than once with flag set?
I am having trouble getting this loop to only run once. I have a flag set and my understanding is it will run through once, change flag = 1, then not run through again but when I execute it, the loop runs over and over again. Any help is appreciated.

EDIT: The issue I'm finding is even when my voltage satisfies the if statement, the loop continues to run.

```<code>voltage = analogRead(A0); //reads in voltage from pin A0
Serial.println(voltage);

//Calibration routine
do {
  if ((voltage >= 1) && (voltage <= 10)) {
    //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    digitalWrite(calibrationLED, LOW);
    delay(1000);
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    Serial.println("Calibrated");
    delay(5000);
    voltageInitial = analogRead(A0);
    //stores the initial voltage to a separate variable, does not change over the course of the crimp
    Serial.println("Initial Voltage: ");
    Serial.println(voltageInitial);
    flag = 1;
  }
} while (flag == 0);
</code>```

答:
"the loop runs over and over again. "
It smells the loop never enter inside if ((voltage >= 1) && (voltage <= 10)) ,
thus never set flag = 1;

So naturally it keep running.

Body:
I am having trouble getting this loop to only run once. I have a flag set and my understanding is it will run through once, change flag = 1, then not run through again but when I execute it, the loop runs over and over again. Any help is appreciated.

EDIT: The issue I'm finding is even when my voltage satisfies the if statement, the loop continues to run.

voltage = analogRead(A0); //reads in voltage from pin A0
Serial.println(voltage);

//Calibration routine
do {
  if ((voltage >= 1) && (voltage <= 10)) {
    //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
    //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    digitalWrite(calibrationLED, LOW);
    delay(1000);
    digitalWrite(calibrationLED, HIGH);
    delay(2000);
    Serial.println("Calibrated");
    delay(5000);
    voltageInitial = analogRead(A0);
    //stores the initial voltage to a separate variable, does not change over the course of the crimp
    Serial.println("Initial Voltage: ");
    Serial.println(voltageInitial);
    flag = 1;
  }
} while (flag == 0);


问:
swift 3.0 let a href from html to call a swift function
I have a html string come from the api service, for example :

```<code><html><body><a href="testFunction" target = blank>link test</a>...</body></html>
</code>```

Please note that I put the html string in UILabel and not in uiwebView

And in my ViewController.swift, I have a function :

```<code>func testFunction() {
  print("I am here")
}
</code>```

What I need is how to call the function testFunction when the user click on the link test?

Thanks,

答:
Maybe you can read this article : http://codelle.com/blog/2016/2/calling-methods-from-strings-in-swift/

With NSSelectorFromString, you can call a method with a string.

Another link : Call a method from a String in Swift

Body:
I have a html string come from the api service, for example :

link test...

Please note that I put the html string in UILabel and not in uiwebView

And in my ViewController.swift, I have a function :

func testFunction() {
  print("I am here")
}

What I need is how to call the function testFunction when the user click on the link test?

Thanks,


问:
How to use ng-if or ng-show to make md-select removed(hide)?
I am trying to make a md-select removed or hide when a checkbox is not checked.
I have tired both ng-if or ng-show, but once the md-select is displayed, it cannot be removed or hide. My code is as follows:

Using ng-if:

```<code><md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
Add Dependency
</md-checkbox>

<p>Checkbox value: {{ checked }}</p>
<md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-if ="checked">
<md-option>testOption1</md-option>
<md-option>testOption2</md-option>
<md-option>testOption3</md-option>
</md-select>
</code>```

Using ng-show

```<code><md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
Add Dependency
</md-checkbox>

<p>Checkbox value: {{ checked }}</p>
<md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-show ="checked">
<md-option>testOption1</md-option>
<md-option>testOption2</md-option>
<md-option>testOption3</md-option>
</md-select>
</code>```

Where did I do wrong? Thank you.

答:
This is because you have "ng-true-value" and "ng-false-value" as true/false strings not bools.  You can fix this by either...

Change ng-true-value="'true'" to ng-true-value="true"

angular.module('sandbox', ['ngMaterial']);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-aria.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-animate.js"></script>
<script src="https://rawgit.com/angular/bower-material/master/angular-material.js"></script>
<link href="https://rawgit.com/angular/bower-material/master/angular-material.css" rel="stylesheet"/>
<div ng-app="sandbox">
  <md-checkbox ng-model="checked" ng-true-value="true" ng-false-value="false">
  Add Dependency
  </md-checkbox>

  <p>Checkbox value: {{ checked }}</p>
  <md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-show ="checked">
  <md-option>testOption1</md-option>
  <md-option>testOption2</md-option>
  <md-option>testOption3</md-option>
  </md-select>
</div></code>```

OR

Change ng-show="checked" to ng-show="checked === 'true'"

angular.module('sandbox', ['ngMaterial']);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-aria.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-animate.js"></script>
<script src="https://rawgit.com/angular/bower-material/master/angular-material.js"></script>
<link href="https://rawgit.com/angular/bower-material/master/angular-material.css" rel="stylesheet"/>
<div ng-app="sandbox">
  <md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
  Add Dependency
  </md-checkbox>

  <p>Checkbox value: {{ checked }}</p>
  <md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-show ="checked === 'true'">
  <md-option>testOption1</md-option>
  <md-option>testOption2</md-option>
  <md-option>testOption3</md-option>
  </md-select>
</div></code>```

Body:
I am trying to make a md-select removed or hide when a checkbox is not checked.
I have tired both ng-if or ng-show, but once the md-select is displayed, it cannot be removed or hide. My code is as follows:

Using ng-if:

<md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
Add Dependency
</md-checkbox>

Checkbox value: {{ checked }}

<md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-if ="checked">
<md-option>testOption1</md-option>
<md-option>testOption2</md-option>
<md-option>testOption3</md-option>
</md-select>

Using ng-show

<md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
Add Dependency
</md-checkbox>

Checkbox value: {{ checked }}

<md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-show ="checked">
<md-option>testOption1</md-option>
<md-option>testOption2</md-option>
<md-option>testOption3</md-option>
</md-select>

Where did I do wrong? Thank you.

Body:
This is because you have "ng-true-value" and "ng-false-value" as true/false strings not bools.  You can fix this by either...

Change ng-true-value="'true'" to ng-true-value="true"

angular.module('sandbox', ['ngMaterial']);

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-aria.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-animate.js"></script>
<script src="https://rawgit.com/angular/bower-material/master/angular-material.js"></script>
<link href="https://rawgit.com/angular/bower-material/master/angular-material.css" rel="stylesheet"/>
<div ng-app="sandbox">
  <md-checkbox ng-model="checked" ng-true-value="true" ng-false-value="false">
  Add Dependency
  </md-checkbox>

  <p>Checkbox value: {{ checked }}</p>
  <md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-show ="checked">
  <md-option>testOption1</md-option>
  <md-option>testOption2</md-option>
  <md-option>testOption3</md-option>
  </md-select>
</div>

OR

Change ng-show="checked" to ng-show="checked === 'true'"

angular.module('sandbox', ['ngMaterial']);

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-aria.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular-animate.js"></script>
<script src="https://rawgit.com/angular/bower-material/master/angular-material.js"></script>
<link href="https://rawgit.com/angular/bower-material/master/angular-material.css" rel="stylesheet"/>
<div ng-app="sandbox">
  <md-checkbox ng-model="checked" ng-true-value="'true'" ng-false-value="'false'">
  Add Dependency
  </md-checkbox>

  <p>Checkbox value: {{ checked }}</p>
  <md-select  placeholder="Dependency" ng-model="test" style="min-width: 300px;" ng-show ="checked === 'true'">
  <md-option>testOption1</md-option>
  <md-option>testOption2</md-option>
  <md-option>testOption3</md-option>
  </md-select>
</div>


答:
You are passing to md-checkbox a true and false value which are 'true' (string) and 'false' (string). So when you write ng-if="checked" or ng-show="checked", angular is just checking your "checked" string variable is not undefined.

Try to remove this :

ng-true-value="'true'" ng-false-value="'false'"

Title: How to use ng-if or ng-show to make md-select removed(hide)?


答:
The flag variable will only get set to 1 if the if condition is true.  This happens when voltage has a value from 1 to 10.

If the value of voltage is not in the range 1 - 10, flag will not be set.  And since voltage is never modified inside of the loop, you have an infinite loop.

Title: Do while loop runs more than once with flag set?


问:
Generate new OAuthAccessToken and OAuthAccessTokenSecret in code
Can I generate new OAuthAccessToken and OAuthAccessTokenSecret in code? May be using twitter4j? I have:

```<code>configurationBuilder.setDaemonEnabled(true)
    .setOAuthConsumerKey("MyCoonsumerKey")
    .setOAuthConsumerSecret("MyConsumerSecret")
    .setOAuthAccessToken("MyAccessToken")
    .setOAuthAccessTokenSecret("MyAccessTokenSecret");
</code>```

But I want generate new Tokens in process in code. Can I do it? How?

答:
The simple answer to that is:

No, you can't generate OAuthAccessToken or OAuthAccessTokenSecret by yourself via Twitter4J.

Taken from https://dev.twitter.com/oauth/overview, we learn:

In order to make authorized calls to Twitter’s APIs, an application must first obtain an OAuth access token on behalf of a Twitter user (or, issue Application-only authenticated requests, when user context is not required).

Moreover, ...

... an access token will be invalidated if a user explicitly revokes an application in the their Twitter account settings, or if Twitter suspends an application.

Conclusion:

You have to generate access token & secret in "their Twitter account settings". For reference, please find the full guide under: https://dev.twitter.com/oauth/overview/introduction

Note well, a mobile phone number is required.

Body:
Can I generate new OAuthAccessToken and OAuthAccessTokenSecret in code? May be using twitter4j? I have:

configurationBuilder.setDaemonEnabled(true)
    .setOAuthConsumerKey("MyCoonsumerKey")
    .setOAuthConsumerSecret("MyConsumerSecret")
    .setOAuthAccessToken("MyAccessToken")
    .setOAuthAccessTokenSecret("MyAccessTokenSecret");

But I want generate new Tokens in process in code. Can I do it? How?


问:
Tableau: Conditional Formatting Rows based on a data range
Any help you can provide would be appreciated. I can't find any tableau tutorials that deal with conditional formatting based on dates.  Plenty of formatting based on cell values, but that doesn't help in this case.

I am trying to create a tableau report that shows the change records that are due within the below criteria and color code the rows accordingly.

The next seven days represented by "red"
The next 14 days represented by "yellow"
Greater than 14 days out represented by "green"
Everything else would have a white background

答:
Something I did that sounds similar was around due dates:

Create a calculated field called "Due Date Traffic Lights" to work out your days amount. The below gives the date difference between the given date field and today:

```<code>DATEDIFF('day',MAX([Due Date]), MAX(TODAY()))
</code>```

Create calculated field "if" function called "Due Date Range" to categrorise these results:

```<code>if [Due Date Traffic Lights] < -7 THEN "GREEN: Over One Week Left"
ELSEIF [Due Date Traffic Lights] > -7 AND [Due Date Traffic Lights] <0
THEN "ORANGE: Due in one Week"
ELSE "RED: Overdue"
END
</code>```

So on your rows you can then drag the "Due Date Range" into your "Color Icon" and set the color for each of the 3.

Body:
Something I did that sounds similar was around due dates:

Create a calculated field called "Due Date Traffic Lights" to work out your days amount. The below gives the date difference between the given date field and today:

DATEDIFF('day',MAX([Due Date]), MAX(TODAY()))

Create calculated field "if" function called "Due Date Range" to categrorise these results:

if [Due Date Traffic Lights] < -7 THEN "GREEN: Over One Week Left"
ELSEIF [Due Date Traffic Lights] > -7 AND [Due Date Traffic Lights] <0
THEN "ORANGE: Due in one Week"
ELSE "RED: Overdue"
END

So on your rows you can then drag the "Due Date Range" into your "Color Icon" and set the color for each of the 3.


问:
Angular 2 how to test content shown / hidden by *ngIf
I am having some difficulties with a unit test that is reading some html which is being added/removed from the DOM with *ngIf.

This is the DOM:

```<code><div class="detailacc" (click)="showDet()">
    <i class="fa" [class.fa-caret-right]="!showHideDet " [class.fa-caret-down]="showHideDet " aria-hidden="true"></i>
    <h4>Expandable</h4>
</div>
<div *ngIf="showHideDet">
    <p class="detailHeader">Details header</p>
</div>
</code>```

This is the component function which gets called on the click event of the first div:

```<code>private showDet() {
    console.log('show called');
    this.showHideDet = !this.showHideDet;
}
</code>```

And finally this is the spec:

```<code>it('should show the header when the expandable elem is clicked', async(() =>
{
    const fixture = TestBed.createComponent(DetailsComponent);
    const compiled = fixture.debugElement.nativeElement;
    let detPresent: boolean = false;
    for (let node of compiled.querySelectorAll('.detailacc')) {
        node.click();
    }

    setTimeout(() => {
        console.log(compiled.querySelectorAll('.detailHeader'));
        for (let node of compiled.querySelectorAll('.detailHeader')) {
            if (node.textContent === 'Details header') {
                detPresent = true;
                break;
            }
        }
        expect(detPresent).toBeFalsy();
    }, 0);
}));
</code>```

As you can see I've wrapped the code which searches for those DOM elements that are shown only when the *ngIf is true in a setTimeout as in this How to check whether ngIf has taken effect but I still do not get anything.

Also if you're wondering if the click gets called in that test, it does because that console.log in the component function gets shown in the Karma console. The console.log inside the setTimeout shows a NodeList(0), basically no nodes with the class .detailHeader where found.

答: Ok, so after more trial and error I found out that if you call fixture.detectChanges() inside the setTimeout it will show the *ngIf DOM

Body:
I am having some difficulties with a unit test that is reading some html which is being added/removed from the DOM with *ngIf.

This is the DOM:

Expandable

Details header

This is the component function which gets called on the click event of the first div:

private showDet() {
    console.log('show called');
    this.showHideDet = !this.showHideDet;
}

And finally this is the spec:

it('should show the header when the expandable elem is clicked', async(() =>
{
    const fixture = TestBed.createComponent(DetailsComponent);
    const compiled = fixture.debugElement.nativeElement;
    let detPresent: boolean = false;
    for (let node of compiled.querySelectorAll('.detailacc')) {
        node.click();
    }

    setTimeout(() => {
        console.log(compiled.querySelectorAll('.detailHeader'));
        for (let node of compiled.querySelectorAll('.detailHeader')) {
            if (node.textContent === 'Details header') {
                detPresent = true;
                break;
            }
        }
        expect(detPresent).toBeFalsy();
    }, 0);
}));

As you can see I've wrapped the code which searches for those DOM elements that are shown only when the *ngIf is true in a setTimeout as in this How to check whether ngIf has taken effect but I still do not get anything.

Also if you're wondering if the click gets called in that test, it does because that console.log in the component function gets shown in the Karma console. The console.log inside the setTimeout shows a NodeList(0), basically no nodes with the class .detailHeader where found.


答:
You set the inner HTML to sr, which is the return value of the function:

```<code>var sr = (function(val) {
    // ...
    // nothing is returned
})(myarray[i]);

document.getElementById("sr").innerHTML = sr;
</code>```

But this function doesn't return anything!

Make it return something using the return keyword.

```<code>var sr = (function(val) {
    // ...
    return "I <3 Stack Overflow";
})(myarray[i]);
</code>```

Title: Javascript document.getElement innerHTML undefined

Body:
You set the inner HTML to sr, which is the return value of the function:

var sr = (function(val) {
    // ...
    // nothing is returned
})(myarray[i]);

document.getElementById("sr").innerHTML = sr;

But this function doesn't return anything!

Make it return something using the return keyword.

var sr = (function(val) {
    // ...
    return "I <3 Stack Overflow";
})(myarray[i]);


问:
SSIS. Import 500 files
I need to import big number of files. How can I write script/C# to supply SSIS package with file names to import?

SQL 2008

答: Use the ForEach container and set it to a File Enumerator.  You'll need a variable to contain the path to the file and you'll need to set an expression on your file connector to pick up the files as they're enumerated.</p>

Title: SSIS. Import 500 files


问:
Passing a php array to a javascript array inside a PHP function
I know this question has been asked a lot on StackOverflow, although I can't find any solution that can be applied to my problem.

I'm working on a platform that regroups all videos and pictures of my company (I'm taking back the project after my ex-coworker), my issue is on the Lightbox that displays the pictures.

I have a PHP function that returns HTML/CSS/Javascript in string format like this :

```<code>$block = '<div id="myModal" class="modal" style="margin:auto">'
            .'<span style="float:right;margin-right:33px"><a href="'.HTTP_IHM_PATH.'Suppression.php?id='.$records[$i]['Access_Key'].'" onclick="return confirm(\'Êtes-vous sûr de vouloir continuer cette suppression ? Elle sera définitive.\');"><img src="'.HTTP_IMG_PATH.'corbeille.jpg" style="width:20px;height:auto;"></a></span>'
            .'<span class="close cursor" onclick="closeModal()" style="color:#585858; font-size:60px;float:right;">×</span>'
[...]
return $block;
</code>```

I call the function like this : <?php echo function() ?>

In here, I have a PHP array $records that contains all informations about the pictures I want to display in my LightBox, I want later in my code to use those informations into my javascript functions.

I've heard that I can translate the array in javascript by using  but it doesn't work !

In the end what I want to do is when the user clicks on a picture, it opens up my LightBox and for every pictures he is watching, I want to call my php function UpdateViews() that add 1 to the number of views of the picture.

I tried using Ajax, but since it's pretty new to me I may be doing stupid mistakes (this is still in string format in the variable $block):

```<code>$block .= '//getSlideIndex returns slideIndex wich is the id of the <img/>
$(\'#\' + getSlideIndex()).on(\'click\', function (){
                    alert("Ok onclick" + records[getSlideIndex()]["Access_Key"];
                    //"Access_Key" is the property I need (primary key of the table)
                    $.ajax({
                        type:\'GET\',
                        url: \'/picture.php\',
                        data: {id=\' + records[getSlideIndex()]["Access_Key"] + \'},
                        success: function(data){
                            alert(\'success\' + data);
                        },
                        error: function(exception){
                            alert(\'Exception: \' + exception);
                        }
                    });
                    e.preventDefault();
                });';
</code>```

NOTE : My ex-coworker already used some Ajax in his code, so at the time I'm on this page, a $_GET is already set : Will I be able to make my ajax work in this case ?

Thank you if you read until this point, I hope you can help me get on the right track.

答:
I've heard that I can translate the array in javascript by using  but it doesn't work !

That doesn't work because you didn't echo the result, you're simply running the JSON process and then discarding the result. Add an echo:

```<code><script>var records = <?php echo json_encode($records) ?></script>
</code>```

and contrary to the other answer, do not try to JSON.parse this because it is already a valid JavaScript object.

Edit: if you're trying to concatenate the JSON to a response string then don't use <?php tags, instead you can do:

```<code>$block .= '<script>var records = ' . json_encode($records) . '; </script>';
</code>```

Body:
I know this question has been asked a lot on StackOverflow, although I can't find any solution that can be applied to my problem.

I'm working on a platform that regroups all videos and pictures of my company (I'm taking back the project after my ex-coworker), my issue is on the Lightbox that displays the pictures.

I have a PHP function that returns HTML/CSS/Javascript in string format like this :

$block = '
'
            .''
            .'×'
[...]
return $block;

I call the function like this : <?php echo function() ?>

In here, I have a PHP array $records that contains all informations about the pictures I want to display in my LightBox, I want later in my code to use those informations into my javascript functions.

I've heard that I can translate the array in javascript by using  but it doesn't work !

In the end what I want to do is when the user clicks on a picture, it opens up my LightBox and for every pictures he is watching, I want to call my php function UpdateViews() that add 1 to the number of views of the picture.

I tried using Ajax, but since it's pretty new to me I may be doing stupid mistakes (this is still in string format in the variable $block):

$block .= '//getSlideIndex returns slideIndex wich is the id of the
$(\'#\' + getSlideIndex()).on(\'click\', function (){
                    alert("Ok onclick" + records[getSlideIndex()]["Access_Key"];
                    //"Access_Key" is the property I need (primary key of the table)
                    $.ajax({
                        type:\'GET\',
                        url: \'/picture.php\',
                        data: {id=\' + records[getSlideIndex()]["Access_Key"] + \'},
                        success: function(data){
                            alert(\'success\' + data);
                        },
                        error: function(exception){
                            alert(\'Exception: \' + exception);
                        }
                    });
                    e.preventDefault();
                });';

NOTE : My ex-coworker already used some Ajax in his code, so at the time I'm on this page, a $_GET is already set : Will I be able to make my ajax work in this case ?

Thank you if you read until this point, I hope you can help me get on the right track.

Body:
I've heard that I can translate the array in javascript by using <script>var records = <?php json_encode($records) ?></script> but it doesn't work !

That doesn't work because you didn't echo the result, you're simply running the JSON process and then discarding the result. Add an echo:

<script>var records = <?php echo json_encode($records) ?></script>

and contrary to the other answer, do not try to JSON.parse this because it is already a valid JavaScript object.

Edit: if you're trying to concatenate the JSON to a response string then don't use <?php tags, instead you can do:

$block .= '<script>var records = ' . json_encode($records) . '; </script>';


问:
Disable Reply and Reply to all outlook options in Java
My application is Java based web application and I have a requirement here to send private email to the employee of the organization. Here I need to disable Reply, Reply to all and forward options on Outlook.  As per my understanding these things can be done through manipulating macros but I'm not sure if we can do this through Java code or not. I'm looking for you valuable suggestions here.

I have just started working over it but could not find any generic solution over it.

Thanks in advance.
I have s

答:
If this was possible, then this would be a huge security issue!

Gladly it is not possible and you cannot manipulate a recipients Outlook by sending him an email containing macros.

This is easy to answer as "not possible", because this would be a security issue if person A could manipulate the Outlook of person B by sending an email to person B.


问:
"contains" method with Set does not work even after overriding the equals method
There is an entity :

```<code>@Entity
@Table(name = "menu")
public class Menu {

    @Id
    @SequenceGenerator(name="s_menu", sequenceName="s_menu", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_menu")
    @Column(name = "menu_id")
    private int id;

    @Column(name = "gmnu_code")
    private Integer groupeMenu;

    @Column(name = "menu_lib")
    private String lib;

    @Column(name = "menu_ordre")
    private Integer ordre;

    @Column(name = "menu_visible")
    private Integer visible;

    @Column(name = "menu_deleted")
    private Integer deleted;

    @Column(name = "menu_bouton")
    private Integer bouton;

    @Column(name = "menu_parent")
    private Integer parent;

    @Column(name = "menu_controlleur")
    private String controlleur;

    @Column(name = "menu_navigation")
    private String navigation;

    @Column(name = "menu_flag_trace")
    private Integer flag_trace;

    @Column(name = "menu_trace")
    private String trace;

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "menus")
    @JsonBackReference
    private Set<Role> roles = new HashSet<Role>();

    @Transient
    private int depth;

    @Transient
    private boolean affectedToARole;

    @Transient
    private Environment env;

    public Menu() {
        super();
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace, Set<Role> roles) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
        this.roles = roles;
    }

    public int getId() {
        return id;
    }

    public void setId(int menu_id) {
        this.id = menu_id;
    }

    public Integer getGroupeMenu() {
        return groupeMenu;
    }

    public void setGroupeMenu(Integer gmnu_code) {
        this.groupeMenu = gmnu_code;
    }

    public String getLib() {
        if (this.env != null)
            return env.getProperty(lib.trim());
        return lib;
    }

    public void setLib(String menu_lib) {
        this.lib = menu_lib;
    }

    public Integer getOrdre() {
        return ordre;
    }

    public void setOrdre(Integer menu_ordre) {
        this.ordre = menu_ordre;
    }

    public Integer getVisible() {
        return visible;
    }

    public void setVisible(Integer menu_visible) {
        this.visible = menu_visible;
    }

    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer menu_deleted) {
        this.deleted = menu_deleted;
    }

    public Integer getBouton() {
        return bouton;
    }

    public void setBouton(Integer menu_bouton) {
        this.bouton = menu_bouton;
    }

    public Integer getParent() {
        return parent;
    }

    public void setParent(Integer menu_parent) {
        this.parent = menu_parent;
    }

    public String getControlleur() {
        return controlleur;
    }

    public void setControlleur(String menu_controlleur) {
        this.controlleur = menu_controlleur;
    }

    public String getNavigation() {
        try {
            if (this.env != null)
                return env.getProperty(navigation.trim());
            return navigation.trim();
        } catch (NullPointerException npe) {
            return " --- ";
        }
    }

    public void setNavigation(String menu_navigation) {
        this.navigation = menu_navigation;
    }

    public String getTrace() {
        if (this.env != null)
            return HtmlUtils.htmlUnescape(env.getProperty(trace));
        return trace;
    }

    public void setTrace(String menu_trace) {
        this.trace = HtmlUtils.htmlUnescape(menu_trace);
    }

    public Integer getFlag_trace() {
        return flag_trace;
    }

    public void setFlag_trace(Integer menu_flag_trace) {
        this.flag_trace = menu_flag_trace;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

    public boolean isAffectedToARole() {
        return affectedToARole;
    }

    public void setAffectedToARole(boolean affectedToARole) {
        this.affectedToARole = affectedToARole;
    }

    @Override
    public boolean equals(Object obj) { // pour pouvoir utiliser la méthode "contains" sur une liste de Menu

        if (this == null && obj == null)
            return true;

        if (this != null && obj != null && obj instanceof Menu)
            return id == ((Menu)obj).getId();

        return super.equals(obj);

    }

}
</code>```

I want to test if a Set of Menu's contains a particular Menu :

```<code>Set<Menu> affected_menus = roleDao.getListMenu(role_code); // gets all menus affected to a role_code

for (Menu menu : temp) {
    if (!affected_menus.isEmpty() && affected_menus.contains(menu))
        menu.setAffectedToARole(true);
    else
        menu.setAffectedToARole(false);
}
</code>```

At runtime all code goes to menu.setAffectedToARole(false);

So what is wrong ?

答:
When overriding equals you must always override hashCode as well. Both methods are used together across Java Collections, etc.

In your case, this implementation might be enough:

```<code>@Override
public int hashCode() {
    return id;
}
</code>```

Also, your equals implementation could use some help as well:

```<code>@Override
public boolean equals(Object obj) {
    if (obj instanceof Menu)
        return id == ((Menu)obj).getId();
    return false;
 }
</code>```

Body:
There is an entity :

@Entity
@Table(name = "menu")
public class Menu {

    @Id
    @SequenceGenerator(name="s_menu", sequenceName="s_menu", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_menu")
    @Column(name = "menu_id")
    private int id;

    @Column(name = "gmnu_code")
    private Integer groupeMenu;

    @Column(name = "menu_lib")
    private String lib;

    @Column(name = "menu_ordre")
    private Integer ordre;

    @Column(name = "menu_visible")
    private Integer visible;

    @Column(name = "menu_deleted")
    private Integer deleted;

    @Column(name = "menu_bouton")
    private Integer bouton;

    @Column(name = "menu_parent")
    private Integer parent;

    @Column(name = "menu_controlleur")
    private String controlleur;

    @Column(name = "menu_navigation")
    private String navigation;

    @Column(name = "menu_flag_trace")
    private Integer flag_trace;

    @Column(name = "menu_trace")
    private String trace;

    @ManyToMany(fetch = FetchType.EAGER, mappedBy = "menus")
    @JsonBackReference
    private Set<Role> roles = new HashSet<Role>();

    @Transient
    private int depth;

    @Transient
    private boolean affectedToARole;

    @Transient
    private Environment env;

    public Menu() {
        super();
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
    }

    public Menu(Integer gmnu_code, String menu_lib, Integer menu_ordre, Integer menu_visible, Integer menu_deleted, Integer menu_bouton, Integer menu_parent, String menu_controlleur, String menu_navigation, Integer menu_flag_trace, String menu_trace, Set<Role> roles) {
        super();
        this.groupeMenu = gmnu_code;
        this.lib = menu_lib;
        this.ordre = menu_ordre;
        this.visible = menu_visible;
        this.deleted = menu_deleted;
        this.bouton = menu_bouton;
        this.parent = menu_parent;
        this.controlleur = menu_controlleur;
        this.navigation = menu_navigation;
        this.flag_trace = menu_flag_trace;
        this.trace = menu_trace;
        this.roles = roles;
    }

    public int getId() {
        return id;
    }

    public void setId(int menu_id) {
        this.id = menu_id;
    }

    public Integer getGroupeMenu() {
        return groupeMenu;
    }

    public void setGroupeMenu(Integer gmnu_code) {
        this.groupeMenu = gmnu_code;
    }

    public String getLib() {
        if (this.env != null)
            return env.getProperty(lib.trim());
        return lib;
    }

    public void setLib(String menu_lib) {
        this.lib = menu_lib;
    }

    public Integer getOrdre() {
        return ordre;
    }

    public void setOrdre(Integer menu_ordre) {
        this.ordre = menu_ordre;
    }

    public Integer getVisible() {
        return visible;
    }

    public void setVisible(Integer menu_visible) {
        this.visible = menu_visible;
    }

    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer menu_deleted) {
        this.deleted = menu_deleted;
    }

    public Integer getBouton() {
        return bouton;
    }

    public void setBouton(Integer menu_bouton) {
        this.bouton = menu_bouton;
    }

    public Integer getParent() {
        return parent;
    }

    public void setParent(Integer menu_parent) {
        this.parent = menu_parent;
    }

    public String getControlleur() {
        return controlleur;
    }

    public void setControlleur(String menu_controlleur) {
        this.controlleur = menu_controlleur;
    }

    public String getNavigation() {
        try {
            if (this.env != null)
                return env.getProperty(navigation.trim());
            return navigation.trim();
        } catch (NullPointerException npe) {
            return " --- ";
        }
    }

    public void setNavigation(String menu_navigation) {
        this.navigation = menu_navigation;
    }

    public String getTrace() {
        if (this.env != null)
            return HtmlUtils.htmlUnescape(env.getProperty(trace));
        return trace;
    }

    public void setTrace(String menu_trace) {
        this.trace = HtmlUtils.htmlUnescape(menu_trace);
    }

    public Integer getFlag_trace() {
        return flag_trace;
    }

    public void setFlag_trace(Integer menu_flag_trace) {
        this.flag_trace = menu_flag_trace;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public void setEnv(Environment env) {
        this.env = env;
    }

    public int getDepth() {
        return depth;
    }

    public void setDepth(int depth) {
        this.depth = depth;
    }

    public boolean isAffectedToARole() {
        return affectedToARole;
    }

    public void setAffectedToARole(boolean affectedToARole) {
        this.affectedToARole = affectedToARole;
    }

    @Override
    public boolean equals(Object obj) { // pour pouvoir utiliser la méthode "contains" sur une liste de Menu

        if (this == null && obj == null)
            return true;

        if (this != null && obj != null && obj instanceof Menu)
            return id == ((Menu)obj).getId();

        return super.equals(obj);

    }

}

I want to test if a Set of Menu's contains a particular Menu :

Set<Menu> affected_menus = roleDao.getListMenu(role_code); // gets all menus affected to a role_code

for (Menu menu : temp) {
    if (!affected_menus.isEmpty() && affected_menus.contains(menu))
        menu.setAffectedToARole(true);
    else
        menu.setAffectedToARole(false);
}

At runtime all code goes to menu.setAffectedToARole(false);

So what is wrong ?

Body:
When overriding equals you must always override hashCode as well. Both methods are used together across Java Collections, etc.

In your case, this implementation might be enough:

@Override
public int hashCode() {
    return id;
}

Also, your equals implementation could use some help as well:

@Override
public boolean equals(Object obj) {
    if (obj instanceof Menu)
        return id == ((Menu)obj).getId();
    return false;
 }


问:
Initializing an enum of generic type from rawValue
I'm experimenting with custom operators in Swift (EXPERIMENTING. I do not need a lecture about why custom operators are bad) and I thought, hmm, EnumType(rawValue:) is a bit long. Maybe I could fix this with an operator? So I wrote:

```<code>infix operator ∑
func ∑ <T,U:RawRepresentable>(lhs:T,rhs:U.Type) {
    rhs(rawValue: lhs)
}
</code>```

Which as intended would be used like this example:

```<code>enum DiceResult: Int {
    case one = 1, two, three, four, five, six
}
let roll = 1 ∑ DiceResult //DiceResult.one
</code>```

But the code I wrote gives me this error:

Non-nominal type 'U' does not support explicit initialization

Honestly I didn't expect what I wrote to work anyway, and I'm not even certain something like what I'm trying to write is at all possible in Swift. Can anybody shed some light whether I can do something like this, and if so how?

答:
The main error is that you treat the operand types U, T as independent. But the type of the left operand must be the RawValue type of the right operand. So this would compile:

```<code>infix operator ∑
func ∑ <U: RawRepresentable>(lhs: U.RawValue, rhs: U.Type) -> U? {
    return rhs.init(rawValue: lhs)
}
</code>```

You can then use it as

```<code>enum DiceResult: Int {
    case one = 1, two, three, four, five, six
}
let roll = 1 ∑ DiceResult.self
</code>```

.self is required to access the type as a value.
Unfortunately this is not much shorter than

```<code>let roll = DiceResult(rawValue: 1)
</code>```

Body:
I'm experimenting with custom operators in Swift (EXPERIMENTING. I do not need a lecture about why custom operators are bad) and I thought, hmm, EnumType(rawValue:) is a bit long. Maybe I could fix this with an operator? So I wrote:

infix operator ∑
func ∑ <T,U:RawRepresentable>(lhs:T,rhs:U.Type) {
    rhs(rawValue: lhs)
}

Which as intended would be used like this example:

enum DiceResult: Int {
    case one = 1, two, three, four, five, six
}
let roll = 1 ∑ DiceResult //DiceResult.one

But the code I wrote gives me this error:

Non-nominal type 'U' does not support explicit initialization

Honestly I didn't expect what I wrote to work anyway, and I'm not even certain something like what I'm trying to write is at all possible in Swift. Can anybody shed some light whether I can do something like this, and if so how?

Body:
The main error is that you treat the operand types U, T as independent. But the type of the left operand must be the RawValue type of the right operand. So this would compile:

infix operator ∑
func ∑ <U: RawRepresentable>(lhs: U.RawValue, rhs: U.Type) -> U? {
    return rhs.init(rawValue: lhs)
}

You can then use it as

enum DiceResult: Int {
    case one = 1, two, three, four, five, six
}
let roll = 1 ∑ DiceResult.self

.self is required to access the type as a value.
Unfortunately this is not much shorter than

let roll = DiceResult(rawValue: 1)


问:
Which is more efficient: Python docstrings or type-hints?
I want to add some support for auto-completion to my Python code with Jedi. This can be done by using either function docstrings or type hints (or both).

```<code>def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    :type param1: int
    :type param2: str
    :rtype: bool
    """

def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
    """Example function with PEP 484 type annotations."""
</code>```

Which method of documenting types adds less overhead in terms of memory usage and running time? I'm interested in the efficiency of the Python code itself first, then Jedi.

答:
TL;DR: Use type annotations, they are awesome.

For both Python and jedi it does not make a difference wheter you use docstrings or function annotations. Both performance and memory impact should not be noticeable. There is obviously a small runtime overhead in both cases.

Docstrings are simply converted to Python strings and stored in the attribute function.__doc__. This takes a few bytes of memory, but you shouldn't care about that. A very large docstring of 1000 characters still only uses 1kB of RAM. If your memory is constrained you may simply use python -o to get rid of docstrings (and asserts as well, look it up).

Type annotations (PEP 484, e.g. def foo(a: int) -> str:) are stored in function.__annotations__:

```<code>>>> def foo(bar: int): pass
...
>>> foo.__annotations__
{'bar': <class 'int'>}
</code>```

These annotations obviously also use some space (but even less than docstrings). However they have no influence on runtime execution (except if you explicitly play with __annotations__.

I would recommend you to use type annotations. They have been introduced, because of static analysis/IDEs and are definitely the future when it comes to documenting your types. There's also a lot of work happing on mypy, jedi and other tools to make type annotations more usable in verifying programs. Use type annotations already and you will be ready for the future.

Body:
I want to add some support for auto-completion to my Python code with Jedi. This can be done by using either function docstrings or type hints (or both).

def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    :type param1: int
    :type param2: str
    :rtype: bool
    """

def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
    """Example function with PEP 484 type annotations."""

Which method of documenting types adds less overhead in terms of memory usage and running time? I'm interested in the efficiency of the Python code itself first, then Jedi.

Body:
TL;DR: Use type annotations, they are awesome.

For both Python and jedi it does not make a difference wheter you use docstrings or function annotations. Both performance and memory impact should not be noticeable. There is obviously a small runtime overhead in both cases.

Docstrings are simply converted to Python strings and stored in the attribute function.__doc__. This takes a few bytes of memory, but you shouldn't care about that. A very large docstring of 1000 characters still only uses 1kB of RAM. If your memory is constrained you may simply use python -o to get rid of docstrings (and asserts as well, look it up).

Type annotations (PEP 484, e.g. def foo(a: int) -> str:) are stored in function.__annotations__:

>>> def foo(bar: int): pass
...
>>> foo.__annotations__
{'bar': <class 'int'>}

These annotations obviously also use some space (but even less than docstrings). However they have no influence on runtime execution (except if you explicitly play with __annotations__.

I would recommend you to use type annotations. They have been introduced, because of static analysis/IDEs and are definitely the future when it comes to documenting your types. There's also a lot of work happing on mypy, jedi and other tools to make type annotations more usable in verifying programs. Use type annotations already and you will be ready for the future.


问:
Android JSOUP ExceptionInInitializerError
I updated my dex classes with amigo library (it's changing one apk for another apk with the same key and signature, all is working except JSOUP)

Error:

FATAL EXCEPTION: Thread-1567
                                                     Process: com.smedic.tubtub, PID: 26102
                                                     java.lang.ExceptionInInitializerError
                                                         at org.jsoup.nodes.Document$OutputSettings.(Document.java:372)
                                                         at org.jsoup.nodes.Document.(Document.java:19)
                                                         at org.jsoup.parser.TreeBuilder.initialiseParse(TreeBuilder.java:32)
                                                         at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:42)
                                                         at org.jsoup.parser.HtmlTreeBuilder.parse(HtmlTreeBuilder.java:56)
                                                         at org.jsoup.parser.Parser.parseInput(Parser.java:32)
                                                         at org.jsoup.helper.DataUtil.parseByteData(DataUtil.java:104)
                                                         at org.jsoup.helper.HttpConnection$Response.parse(HttpConnection.java:666)
                                                         at org.jsoup.helper.HttpConnection.get(HttpConnection.java:225)
                                                         at com.power.mati.VideosAdapter$4.run(VideosAdapter.java:177)
                                                         at java.lang.Thread.run(Thread.java:818)
                                                      Caused by: java.lang.IllegalStateException: Could not read resource
  entities-xhtml.properties. Make sure you copy resources for
  org.jsoup.nodes.Entities
                                                         at org.jsoup.nodes.Entities.load(Entities.java:289)
                                                         at org.jsoup.nodes.Entities.access$000(Entities.java:25)
                                                         at org.jsoup.nodes.Entities$EscapeMode.(Entities.java:48)

Any idea how to fix it?

I am using jars and maven, same situation.

答:
I saw something similar and my solution is in proguard</p>

```<code>-keep class org.jsoup.**
</code>```

Body:
I saw something similar and my solution is in proguard

-keep class org.jsoup.**


问:
r: subsetting with square brackets not working
I made data frame called x:

```<code>a  b
1  2
3  NA
3  32
21 7
12 8
</code>```

When I run

```<code>y <- x["a">2,]
</code>```

The object y returned is identical to x. If I run

```<code>y <- x["a" == 1,]
</code>```

y is an empty frame.

I made sure that the names of the x data frame have no white spaces (I named them myself with names() ) and also that a and are numeric.

PS: If I try

```<code> y <- x["a">2]
</code>```

y is also returned as identical to x.

答:
You're making an error in referencing the column of your data.frame x.

"a">2 means character a bigger than two, not variable a of data.frame x. You need to add either x$a or x["a"] to reference your data.frame column.

try

y <- x[x$a >2 ,]

or

y <- x[x["a"] >2 ,]

or even more clear

```<code>ix <- x["a"] > 2

y <- x[ix,]
</code>```

Body:
I made data frame called x:

a  b
1  2
3  NA
3  32
21 7
12 8

When I run

y <- x["a">2,]

The object y returned is identical to x. If I run

y <- x["a" == 1,]

y is an empty frame.

I made sure that the names of the x data frame have no white spaces (I named them myself with names() ) and also that a and are numeric.

PS: If I try

 y <- x["a">2]

y is also returned as identical to x.

Body:
You're making an error in referencing the column of your data.frame x.

"a">2 means character a bigger than two, not variable a of data.frame x. You need to add either x$a or x["a"] to reference your data.frame column.

try

y <- x[x$a >2 ,]

or

y <- x[x["a"] >2 ,]

or even more clear

ix <- x["a"] > 2

y <- x[ix,]


问:
How to close a JavaFX application on window close?
In Swing you can simply use setDefaultCloseOperation() to shut down the entire application when the window is closed.

However in JavaFX I can't find an equivalent. I have multiple windows open and I want to close the entire application if a window is closed. What is the way to do that in JavaFX?

Edit:

I understand that I can override setOnCloseRequest() to perform some operation on window close. The question is what operation should be performed to terminate the entire application?

```<code>stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        stop();
    }
});
</code>```

The stop() method defined in Application class does nothing.

答:
You MUST override the "stop()" method in your Application instance to make it works. If you have overridden even empty "stop()" then the application shuts down gracefully after the last stage is closed (actually the last stage must be the primary stage to make it works completely as in supposed to be).
No any additional Platform.exit or setOnCloseRequest calls are need in such case.</p>

Body:
In Swing you can simply use setDefaultCloseOperation() to shut down the entire application when the window is closed.

However in JavaFX I can't find an equivalent. I have multiple windows open and I want to close the entire application if a window is closed. What is the way to do that in JavaFX?

Edit:

I understand that I can override setOnCloseRequest() to perform some operation on window close. The question is what operation should be performed to terminate the entire application?

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        stop();
    }
});

The stop() method defined in Application class does nothing.


问:
PHP MySQL while loop not returning anything
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.

I have the following code:

```<code><?php

$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);

$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);

echo "<b>Quests Available for ".$npcname."</b><br>";

while($row=mysql_fetch_array($listquests2)) {

echo $row['name'];

}
?>
</code>```

To go with this I have some tables whcih look like this:

```<code>npcs
name|location|npcid

quests
name|qid|npcid
</code>```

So a quest is associated to a NPC via the npcid field.

I have one entry in each table.

```<code>Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1
</code>```

As you can see the quest and Bob both share the npcid of 1.

In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.

If I put the code:

```<code>  $listquests3['name'];
</code>```

Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.

If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.

Thank You.

答:
It may be a good idea to print out the SQL and run this against your database to see what results you get.
Looking at this it looks like there may only be one result which is fetched in the

```<code>$listquests3=mysql_fetch_array($listquests2);
</code>```

line. Since there are no more results there is nothing to loop over.

Body:
I'm quite new to php and mysql so hopefully someone with more experience will be able to give me some guidance here.

I have the following code:

<?php

$npcname = $_GET['npcname'];
$npcinfo="SELECT * from npcs where name='$npcname'";
$npcinfo2=mysql_query($npcinfo) or die("could not get npc!");
$npcinfo3=mysql_fetch_array($npcinfo2);

$listquests = "SELECT * from quests where npcid = '$npcinfo3[npcid]'";
$listquests2 = mysql_query($listquests) or die("No Quests to list");
$listquests3=mysql_fetch_array($listquests2);

echo "Quests Available for ".$npcname."
";

while($row=mysql_fetch_array($listquests2)) {

echo $row['name'];

}
?>

To go with this I have some tables whcih look like this:

npcs
name|location|npcid

quests
name|qid|npcid

So a quest is associated to a NPC via the npcid field.

I have one entry in each table.

Bob|Scrapyard|1
AND
Sort Scrap Metal|1|1

As you can see the quest and Bob both share the npcid of 1.

In my loop I am trying to list all of the quests for Bob. However on running the code I do not get any quests listed.

If I put the code:

  $listquests3['name'];

Outside of my loop it successfully displays "Sort Scrap Metal" as expected. The reason I have used the loop is to display multiple quests when I add them.

If somebody could be kind enough to take a look at the code and tell me what I have done wrong I would be grateful.

Thank You.

Body:
It may be a good idea to print out the SQL and run this against your database to see what results you get.
Looking at this it looks like there may only be one result which is fetched in the

$listquests3=mysql_fetch_array($listquests2);

line. Since there are no more results there is nothing to loop over.


问:
Export Julia output to PDF
Is it possible to record output of Julia script both console output and plotted figures. And export it as PDF file?

I know about Jupyter but don't like it and would like to use something different. Basically I'd like to store results of script calculations in some sort of PDF report.

答:
Check out https://github.com/mpastell/Weave.jl

Here is some extra text which appears to be required by StackOverflow.

Title: Export Julia output to PDF


问:
How to edit the value of a variable in a TPL file
I'm trying to edit a TPL file from the OpenCart platform, I would put the "price" divided into 6 parts, but when I put $pricecard = $ price / 6; And Echo $ pricecard; No value is returned.

Here's my code

```<code>  <span> <?php echo "Ou em 6x de: " ?></span>
  <?php $a = 6; ?>
  <?php $pricecard = $price; ?>
  <span><?php $pricecard = $tbData->priceFormat($pricecard); ?></span>
  <span class="price-cartao"><?php echo $pricecard; ?></span>
</code>```

I put $pricecard getting the value of $price and displayed normally, any suggestions?

答:
Usually all the calculations and the variables should be inside the controller before the load of the view.

In your product.tpl the $price is already loaded as string because it has the currency symbol in it, so you cannot divide it by other variable.

I will attach a solution but by using the product controller.

So you open the file: catalog/controller/product/product.php and you search for line:

For Opencart 1.5.x

$this->data['options'] = array();

Before that line, you add:

$a = 6;
$this->data['custom_price'] = $product_info['price'] / $a;

For Opencart 2.x

$data['options'] = array();

Before that line, you add:

$a = 6;
$data['custom_price'] = $product_info['price'] / $a;

Of course you need to change the $a variable to whatever you want to have there.

Then you open the product.tpl file and you just show the information easily.
For example:

<?php echo $custom_price; ?>

Hope I helped you. Cheers

Body:
I'm trying to edit a TPL file from the OpenCart platform, I would put the "price" divided into 6 parts, but when I put $pricecard = $ price / 6; And Echo $ pricecard; No value is returned.

Here's my code

   <?php echo "Ou em 6x de: " ?>
  <?php $a = 6; ?>
  <?php $pricecard = $price; ?>
  <?php $pricecard = $tbData->priceFormat($pricecard); ?>
  <?php echo $pricecard; ?>

I put $pricecard getting the value of $price and displayed normally, any suggestions?

Body:
Usually all the calculations and the variables should be inside the controller before the load of the view.

In your product.tpl the $price is already loaded as string because it has the currency symbol in it, so you cannot divide it by other variable.

I will attach a solution but by using the product controller.

So you open the file: catalog/controller/product/product.php and you search for line:

For Opencart 1.5.x

$this->data['options'] = array();

Before that line, you add:

$a = 6;
$this->data['custom_price'] = $product_info['price'] / $a;

For Opencart 2.x

$data['options'] = array();

Before that line, you add:

$a = 6;
$data['custom_price'] = $product_info['price'] / $a;

Of course you need to change the $a variable to whatever you want to have there.

Then you open the product.tpl file and you just show the information easily.
For example:

<span><?php echo $custom_price; ?></span>

Hope I helped you. Cheers


问:
Google Sheet formula for cumulative sum with condition
I have a Google Sheet with the following layout:

```<code>  Number |  Counted?  |  Cumulative Total
    4    |     Y      |         4
    2    |            |         6
    9    |     Y      |        15
   ...   |    ...     |        ...
</code>```

The first cell in the Cumulative Total column is populated with this formula:

```<code>=ArrayFormula((SUMIF(ROW(C2:C1000),"<="&ROW(C2:1000),C2:C1000)
</code>```

However this counts all rows in the 'Number' column. How can I make the Cumulative Total only count rows where the Counted? cell is Y?

答:
Assuming "Number" in column A and "Counted?" in column B, try in C1

```<code>={"SUM"; ArrayFormula(if(ISBLANK(B2:B),,mmult(transpose(if(transpose(row(B2:B))>=row(B2:B), if(B2:B="Y", A2:A,0), 0)),row(B2:B)^0)))}
</code>```

(Change ranges to suit).

Example

Body:
I have a Google Sheet with the following layout:

  Number |  Counted?  |  Cumulative Total
    4    |     Y      |         4
    2    |            |         6
    9    |     Y      |        15
   ...   |    ...     |        ...

The first cell in the Cumulative Total column is populated with this formula:

=ArrayFormula((SUMIF(ROW(C2:C1000),"<="&ROW(C2:1000),C2:C1000)

However this counts all rows in the 'Number' column. How can I make the Cumulative Total only count rows where the Counted? cell is Y?

Body:
Assuming "Number" in column A and "Counted?" in column B, try in C1

={"SUM"; ArrayFormula(if(ISBLANK(B2:B),,mmult(transpose(if(transpose(row(B2:B))>=row(B2:B), if(B2:B="Y", A2:A,0), 0)),row(B2:B)^0)))}

(Change ranges to suit).

Example


问:
Kotlin: how to use multiple Generic in Class?
i'm trying to convert this c# class to kotlin for android:

```<code>public class ChildItemCollection<P, T, C> : ICollection<T>
    where P : class
    where T : ChildItem<P>
    where C : class, ICollection<T>
{

    private P _parent;
    private C _collection;

    public ChildItemCollection(P parent, C collection)
    {
        this._parent = parent;
        this._collection = collection;
    }

...

}

public class ChildItemCollection<P, T> : ChildItemCollection<P, T, List<T>>
        where P : class
        where T : ChildItem<P>
    {
        #region Constructors
        public ChildItemCollection(P parent)
            : base(parent, new List<T>()) { }

        public ChildItemCollection(P parent, ICollection<T> collection)
            : this(parent)
        {
            foreach (T item in collection)
                this.Add(item);
        }
        #endregion Constructors
    }
</code>```

I have tried many things without success.

I didn't understand how to use the "where" lines either.

答:
In Kotlin, you can specify the type parameter upper bounds at their declaration:

```<code>class ChildItemCollection<P, T : ChildItem<P>, C : Collection<T>> : ...
</code>```

If you have multiple upper bounds, they should be specified separately with where, see another Q&A.

Also, Kotlin does not have a class upper bound, because there's no distinction between value types and classes.

Body:
i'm trying to convert this c# class to kotlin for android:

public class ChildItemCollection
 : ICollection<T>
    where P : class
    where T : ChildItem

    where C : class, ICollection<T>
{

    private P _parent;
    private C _collection;

    public ChildItemCollection(P parent, C collection)
    {
        this._parent = parent;
        this._collection = collection;
    }

...

}

public class ChildItemCollection
 : ChildItemCollection<P, T, List<T>>
        where P : class
        where T : ChildItem

    {
        #region Constructors
        public ChildItemCollection(P parent)
            : base(parent, new List<T>()) { }

        public ChildItemCollection(P parent, ICollection<T> collection)
            : this(parent)
        {
            foreach (T item in collection)
                this.Add(item);
        }
        #endregion Constructors
    }

I have tried many things without success.

I didn't understand how to use the "where" lines either.

Body:
In Kotlin, you can specify the type parameter upper bounds at their declaration:

class ChildItemCollection<P, T : ChildItem<P>, C : Collection<T>> : ...

If you have multiple upper bounds, they should be specified separately with where, see another Q&A.

Also, Kotlin does not have a class upper bound, because there's no distinction between value types and classes.


问:
Make ReSharper let me insert tab after 'else' by tab key
Currently, if I have

if(thing)
    dostuff;
else
```
<p>and then press <kbd>tab</kbd> after the <code>else</code>, ReSharper forces a newline</p>
<pre class="lang-cs prettyprint-override"><code>if(thing)
    dostuff;
else
{
}
</code>```

whereas what I want is to insert a tab character like what the tab key should do, as I often like having comments after if/else and prefer them to be tab-aligned

if(thing)     //etc
    dostuff;
else          //etc
{
}
```

I've turned off both Braces and Parentheses options in

Environment->Editor->Editor Behaviour

as well as unchecking "else" in the Templates Explorer.

Are there more options elsewhere I can access dealing with this? Is there some way to make ReSharper just plain never, ever, ever add braces, newlines or parenthesis without me telling it to? And generally allow me to use the tab key like I would were it not installed?

答:
The option should be located within the menu:

ReSharper -> Options... -> Code Editing -> C# -> Formatting Style -> Line Breaks and Wrapping.

Within this "Line Breaks and Wrapping" list of settings:

Place on New Line -> Place "else" on new line (with a check box)

Here, you should be able to find and uncheck other situations where you want to remove ReSharper's ability to add new lines and/or brackets when you do things.

ContentLicense: CC BY-SA 4.0

Body:
Currently, if I have

if(thing)
    dostuff;
else

and then press tab after the else, ReSharper forces a newline

if(thing)
    dostuff;
else
{
}

whereas what I want is to insert a tab character like what the tab key should do, as I often like having comments after if/else and prefer them to be tab-aligned

if(thing)     //etc
    dostuff;
else          //etc
{
}

I've turned off both Braces and Parentheses options in

Environment->Editor->Editor Behaviour

as well as unchecking "else" in the Templates Explorer.

Are there more options elsewhere I can access dealing with this? Is there some way to make ReSharper just plain never, ever, ever add braces, newlines or parenthesis without me telling it to? And generally allow me to use the tab key like I would were it not installed?


问:
Xcode The executable was signed with invalid entitlements
I would install an application in my mobile phone by using Xcode but it was not installed with following an error message.

Error Message

"The executable was signed with invalid entitlements.
The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile. (0xE8008016)"

Matters of Inquiry

Why does the error message occur while I install the application?

Would you mind if you can give me the solution of this problem?

答:
Had the same problem that suddenly popped up in my project from one day to the next.

What fixed it for me was turning "Automatically manage signing" off and on again for both targets and making sure the right development team was selected once it was on again (defaults to none in my project).