问:
Error display unable to delete the file chromedriver.exe while running a Selenium project in Visual studio
I am running a Selenium C# project through Visual studio and suddenly encountered an error

```<code>Access to the path 'c:\users\documents\visual studio 2017\Project\SeleniumTestProject\SeleniumTestProject\bin\Debug\chromedriver.exe' is denied.
</code>```

I removed the readonly attribute for the folder but still get this error. Can anyone please suggest me what could be wrong and solution for the same.

答:
I solved it by shutting down the ChromeDriver correctly.
I used:
IWebDriver.Dispose() for quitting the ChromeDriver process

In your case, after your test completes, there should be a chromedriver.exe in your Task Manager which does not quit until you manually "End Process" it. However, if you use IWebDriver.Dispose(), it kills the process. And now, since the chromedriver.exe is no longer in use, the "Access denied" problem also goes away.

Hope this solves your problem.
Reference: https://stackoverflow.com/a/44126143/1785144

Body:
I am running a Selenium C# project through Visual studio and suddenly encountered an error

Access to the path 'c:\users\documents\visual studio 2017\Project\SeleniumTestProject\SeleniumTestProject\bin\Debug\chromedriver.exe' is denied.

I removed the readonly attribute for the folder but still get this error. Can anyone please suggest me what could be wrong and solution for the same.


来源: stackexchange

问:
Can we send desktop/push notification using Google Sheet?
Is there any possibility to use some desktop/pop-up or push notification useing google sheet and =NOW() parametr? I would like to have some task remainder. In rows there are information like 1) current time [=NOW()] 2) schedule time 3) what to do. if 1st and 2nd row are the same i receive some notification/alert that scheduled task should be started</p>

答: This feature is not supported by Sheets API per se. Try playing around with Push API and see how you can implement it in your app. You also need a mechanism that constantly checks for the values every second which calls for a real-time app implementation. </p>

ContentLicense: CC BY-SA 3.0


问:
pandas merge multiple Dataframes and the do text analysis?

Problem statement:

I have this crummy file from a government department that lists the operation schedules of 500+ bus routes across multiple sheets in a single excel. There is really no structure here and the author seems to have a single objective - pack everything tight in a single file !

Now, what am I trying to do:

Do extensive text analysis to extract the starting time of each run on the route. Please note there are multiple routes on a single sheet and then there are around 12 sheets in all.

I am cutting my teeth with the pandas library and stuck at this point:

Have a dictionary where
Key:   sheet name (random str to identify the route sequence)
Value: DataFrame created with all cell data on that sheet.

What do I would like to know:

Create one gigantic DataFrame that has all the rows from across the 12 sheets. Start with my text analysis post this step.

Is that above the right way forward?

Thanks in advance.
AT

答:
Could try a multi-index dataframe:

```<code>df_3d=pd.concat(dfs, # List of dataframes
                keys=sheetnames,   # List of sheetnames
                axis=1)
</code>```

Where dfs would be something like

```<code>dfs=[read_excel(io,sheetname=i) for i in sheetnames]
</code>```

Body:
Could try a multi-index dataframe:

df_3d=pd.concat(dfs, # List of dataframes
                keys=sheetnames,   # List of sheetnames
                axis=1)

Where dfs would be something like

dfs=[read_excel(io,sheetname=i) for i in sheetnames]


问:
Get location updates after GPS enabled by user
I have a simple App which currently simply asks for necessary permissions and in case GPS is OFF, you get an AlertDialog asking you if you want to switch it ON. After accepting, being taken to GPS options, enabling it, and going back to my App, I'd like to update location and here I get lost.

In other words, I'm trying to do what's stated here: https://stackoverflow.com/a/43396965/7060082

Unfortunately I can't manage to get it done and the example is a bit complicated for me to understand. Here is a piece of my code showing the relevant bits:

    private void checkGPS() {
        manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.GPS_error)
                    .setCancelable(false)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                            Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(gps, 1);
                            getLatLon();
                        }
                    })
                    .setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                            dialog.cancel();
                        }
                    });
            final AlertDialog alert = builder.create();
            alert.show();
        } else {
            getLatLon();
        }

    }

    private void getLatLon() {
        //manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = manager.getBestProvider(criteria, false);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            manager.getLastKnownLocation(provider);

            if (location != null) {
                Toast.makeText(this, "This is my location: " + location.getLongitude() + ", " + location.getLatitude(), Toast.LENGTH_SHORT).show();

            } else {
               // manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

                //location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                /*
                double longitude = location.getLongitude();
                double latitude = location.getLatitude();
                Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
            */
            }
        }
    }

    @Override
    public void onLocationChanged(Location l) {
        location = l;
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();

    }
```

After asking for ACCESS_FINE_LOCATION permission (which is also stated on the manifest) I call checkGPS(). As said before, let's you enable or not the GPS. If enabled, I call getLatLon(). If there is a lastKnownLocation, good, if not...

Here I get lost. I call requestLocationUpdates and then do nothing waiting for onLocationChanged to recieve a location update and execute the rest of the code. Am I doing it right? The result is me clicking the button, switching GPS on. Click on the button again and nothing happens.

Any help with this will help.
Many thanks for your time.

答:
after some time busy with other projects, got back to this one and I removed the getLatLon(); function from the checkGPS(); function and that's it, code is fine. I was using the emulator to check if this was working, but I forgot that the emulator has a fixed value for the latitude and longitude, so you get no updates like a real mobile phone, and thus it looked as if it was not working properly.

Sort of a newby mistake. Regardless, thanks for your offers. Was interesting looking at different ways of doing the same thing.

Sartox

Body:
I have a simple App which currently simply asks for necessary permissions and in case GPS is OFF, you get an AlertDialog asking you if you want to switch it ON. After accepting, being taken to GPS options, enabling it, and going back to my App, I'd like to update location and here I get lost.

In other words, I'm trying to do what's stated here: https://stackoverflow.com/a/43396965/7060082

Unfortunately I can't manage to get it done and the example is a bit complicated for me to understand. Here is a piece of my code showing the relevant bits:

    private void checkGPS() {
        manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(R.string.GPS_error)
                    .setCancelable(false)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                            Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(gps, 1);
                            getLatLon();
                        }
                    })
                    .setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                            dialog.cancel();
                        }
                    });
            final AlertDialog alert = builder.create();
            alert.show();
        } else {
            getLatLon();
        }

    }

    private void getLatLon() {
        //manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = manager.getBestProvider(criteria, false);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            manager.getLastKnownLocation(provider);

            if (location != null) {
                Toast.makeText(this, "This is my location: " + location.getLongitude() + ", " + location.getLatitude(), Toast.LENGTH_SHORT).show();

            } else {
               // manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

                //location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                /*
                double longitude = location.getLongitude();
                double latitude = location.getLatitude();
                Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
            */
            }
        }
    }

    @Override
    public void onLocationChanged(Location l) {
        location = l;
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();

    }

After asking for ACCESS_FINE_LOCATION permission (which is also stated on the manifest) I call checkGPS(). As said before, let's you enable or not the GPS. If enabled, I call getLatLon(). If there is a lastKnownLocation, good, if not...

Here I get lost. I call requestLocationUpdates and then do nothing waiting for onLocationChanged to recieve a location update and execute the rest of the code. Am I doing it right? The result is me clicking the button, switching GPS on. Click on the button again and nothing happens.

Any help with this will help.
Many thanks for your time.


问:
Making Tumblr Landing Page
On Tumblr, I am trying to make a landing page with, for example, an "Enter" button that brings the user to the home page. I found the following code that redirects the site to a /welcome page, which I placed in the index page.

```<code><script type="text/javascript">
if(location.href == 'http://ihadcats.tumblr.com/') location.replace('http://ihadcats.tumblr.com/welcome');;
</script>
</code>```

Of course, on the 'welcome' page, when you press href="http://ihadcats.tumblr.com" it just loops back to the welcome page.

I created a custom page '/home', to use instead of the index page. I placed the normal index code into a separate '/home' page, but the code doesn't render. It displays, for example "{Title}" instead of the actual title.

When the Index page is loaded, Tumblr bakes in a lot of its own scripts. When the '/home' page is loaded, none of Tumblr's scripts are loaded. Though the code in both pages is exactly the same. Any ideas?

答:
Tumblr variables and blocks don't render on custom pages, only in the main theme code. Basically it doesn't see them as special key words or anything it just sees them as a normal webpage would see them.

As for making a landing page you can tag every post you make with some arbitrary tag like 'x' and then make your index page a landing page and then wrap all your code in {block:TagPage} {/block:TagPage} so that the theme code only displays on tag pages (and you would code permalink pages like normal).

Alternatively you could do as suggested above and make a welcome 'popup' of sorts.

Title: Making Tumblr Landing Page

Body:
On Tumblr, I am trying to make a landing page with, for example, an "Enter" button that brings the user to the home page. I found the following code that redirects the site to a /welcome page, which I placed in the index page.

Of course, on the 'welcome' page, when you press <a href="http://ihadcats.tumblr.com" it just loops back to the welcome page.

I created a custom page '/home', to use instead of the index page. I placed the normal index code into a separate '/home' page, but the code doesn't render. It displays, for example "{Title}" instead of the actual title.

When the Index page is loaded, Tumblr bakes in a lot of its own scripts. When the '/home' page is loaded, none of Tumblr's scripts are loaded. Though the code in both pages is exactly the same. Any ideas?


问:
Aligning Visio shape text to the top and to the left using Powershell
I'm having problems with the second line below. How can I use PowerShell to align the shape text?</p>

```<code>$squareshape.text = "abc";
$squareshape.align.top;
</code>```

答:
try this code

$squareshape.cells('VerticalAlign') = 0

$squareshape.cells('Para.HorzAlign') = 0

Body:
I'm having problems with the second line below. How can I use PowerShell to align the shape text?

$squareshape.text = "abc";
$squareshape.align.top;


问:
Passing ES_JAVA_OPTS variable with spaces when using docker compose
I'm trying to run Elasticsearch using docker compose but I'm not sure how to correctly pass the ES_JAVA_OPTS="-Xms512m -Xmx512m" environmental variable. I've tried lots of combinations of single and double quotes but they all result in: Error: Could not find or load main class "-Xms512m.

My docker-compose config is:

```<code>elasticsearch:
  image: "docker.elastic.co/elasticsearch/elasticsearch:5.4.3"
  ports:
   - "6379:6379"
  environment:
   - "http.host=0.0.0.0"
   - "transport.host=127.0.0.1"
   - "xpack.security.enabled=false"
   - 'ES_JAVA_OPTS="-Xms512m -Xmx512m"'
</code>```

This environmental variable works just fine when running the container directly with:

```<code>docker run --detach \
  --name elasticsearch \
  --publish 9200:9200 \
  --env "http.host=0.0.0.0" \
  --env "transport.host=127.0.0.1" \
  --env "xpack.security.enabled=false" \
  --env "ES_JAVA_OPTS=""-Xms512m -Xmx512m""" \
  docker.elastic.co/elasticsearch/elasticsearch:5.4.3
</code>```

What am I missing here?

答:
According to https://github.com/docker/compose/issues/2854, it's an issue with how docker compose will parse your env variables.

If you switch to yaml map instead of list, it should work:

elasticsearch:
  image: "docker.elastic.co/elasticsearch/elasticsearch:5.4.3"
  ports:
    - "6379:6379"
  environment:
    http.host: 0.0.0.0
    transport.host: 127.0.0.1
    xpack.security.enabled: "false"
    ES_JAVA_OPTS: -Xms512m -Xmx512m
```

Body:
I'm trying to run Elasticsearch using docker compose but I'm not sure how to correctly pass the ES_JAVA_OPTS="-Xms512m -Xmx512m" environmental variable. I've tried lots of combinations of single and double quotes but they all result in: Error: Could not find or load main class "-Xms512m.

My docker-compose config is:

elasticsearch:
  image: "docker.elastic.co/elasticsearch/elasticsearch:5.4.3"
  ports:
   - "6379:6379"
  environment:
   - "http.host=0.0.0.0"
   - "transport.host=127.0.0.1"
   - "xpack.security.enabled=false"
   - 'ES_JAVA_OPTS="-Xms512m -Xmx512m"'

This environmental variable works just fine when running the container directly with:

docker run --detach \
  --name elasticsearch \
  --publish 9200:9200 \
  --env "http.host=0.0.0.0" \
  --env "transport.host=127.0.0.1" \
  --env "xpack.security.enabled=false" \
  --env "ES_JAVA_OPTS=""-Xms512m -Xmx512m""" \
  docker.elastic.co/elasticsearch/elasticsearch:5.4.3

What am I missing here?

ContentLicense: CC BY-SA 4.0


问:
Storing Value in Arduino Sent From Python via Serial
I have been trying to send a value from a Python program via serial to an Arduino, but I have been unable to get the Arduino to store and echo back the value to Python. My code seems to match that I've found in examples online, but for whatever reason, it's not working.

I am using Python 3.5 on Windows 10 with an Arduino Uno. Any help would be appreciated.

Arduino code:

```<code>void readFromPython() {
  if (Serial.available() > 0) {
    incomingIntegrationTime = Serial.parseInt();
    // Collect the incoming integer from PySerial
    integration_time = incomingIntegrationTime;
    Serial.print("X");
    Serial.print("The integration time is now ");
    // read the incoming integer from Python:
    // Set the integration time to what you just collected IF it is not a zero
    Serial.println(integration_time);
    Serial.print("\n");
    integration_time=min(incomingIntegrationTime,2147483648);
    // Ensure the integration time isn't outside the range of integers
    integration_time=max(incomingIntegrationTime, 1);
    // Ensure the integration time isn't outside the range of integers
  }
}

void loop() {
  readFromPython();
  // Check for incoming data from PySerial
  delay(1);
  // Pause the program for 1 millisecond
}
</code>```

Python code:
(Note this is used with a PyQt button, but any value could be typed in instead of self.IntegrationTimeInputTextbox.text() and the value is still not receieved and echoed back by Arduino).

```<code>def SetIntegrationTime(self):
    def main():
        #    global startMarker, endMarker
        #This sets the com port in PySerial to the port with the Genuino as the variable arduino_ports
        arduino_ports = [
            p.device
        for p in serial.tools.list_ports.comports()
        if 'Genuino' in p.description
        ]
        #Set the proper baud rate for your spectrometer
        baud =  115200
        #This prints out the port that was found with the Genuino on it
        ports = list(serial.tools.list_ports.comports())
        for p in ports:
            print ('Device is connected to: ', p)
        # --------------------------- Error Handling ---------------------------
        #Tell the user if no Genuino was found
        if not arduino_ports:
            raise IOError("No Arduino found")
        #Tell the user if multiple Genuinos were found
        if len(arduino_ports) > 1:
            warnings.warn('Multiple Arduinos found - using the first')
        # ---------------------------- Error Handling ---------------------------
    #=====================================
        spectrometer = serial.Serial(arduino_ports[0], baud)
        integrationTimeSend = self.IntegrationTimeInputTextbox.text()
        print("test value is", integrationTimeSend.encode())
        spectrometer.write(integrationTimeSend.encode())
        for i in range(10): #Repeat the following 10 times
            startMarker = "X"
            xDecoded = "qq"
            xEncoded = "qq"
            while xDecoded != startMarker:    #Wait for the start marker (X))
                xEncoded = spectrometer.read() #Read the spectrometer until 'startMarker' is found so the right amound of data is read every time
                xDecoded = xEncoded.decode("UTF-8");
                print(xDecoded);
            line = spectrometer.readline()
            lineDecoded = line.decode("UTF-8")
            print(lineDecoded)
    #=====================================
        spectrometer.close()
    #===========================================

#WaitForArduinoData()
    main()
</code>```

答:
First, this is a problem:

```<code>incomingValue = Serial.read();
</code>```

Because read() returns the first byte of incoming serial data reference.  On the Arduino the int is a signed 16-bit integer, so reading only one byte of it with a Serial.read() is going to give you unintended results.

Also, don't put writes in between checking if data is available and actual reading:

```<code> if (Serial.available() > 0) {
    Serial.print("X");                  // Print your startmarker
    Serial.print("The value is now ");
    incomingValue = Serial.read(); // Collect the incoming value from
</code>```

That is bad.  Instead do your read immediately as this example shows:

```<code>    if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();
</code>```

That's two big issues there.   Take care of those and let's take a look at it after those fundamental issues are corrected.

PART 2

Once those are corrected, the next thing to do is determine which side of the serial communication is faulty.  Generally what I like to do is determine one side is sending properly by having its output show up in a terminal emulator.  I like TeraTerm for this.

Set your python code to send only and see if your sent values show up properly in a terminal emulator.  Once that is working and you have confidence in it, you can attend to the Arduino side.

Body:
I have been trying to send a value from a Python program via serial to an Arduino, but I have been unable to get the Arduino to store and echo back the value to Python. My code seems to match that I've found in examples online, but for whatever reason, it's not working.

I am using Python 3.5 on Windows 10 with an Arduino Uno. Any help would be appreciated.

Arduino code:

void readFromPython() {
  if (Serial.available() > 0) {
    incomingIntegrationTime = Serial.parseInt();
    // Collect the incoming integer from PySerial
    integration_time = incomingIntegrationTime;
    Serial.print("X");
    Serial.print("The integration time is now ");
    // read the incoming integer from Python:
    // Set the integration time to what you just collected IF it is not a zero
    Serial.println(integration_time);
    Serial.print("\n");
    integration_time=min(incomingIntegrationTime,2147483648);
    // Ensure the integration time isn't outside the range of integers
    integration_time=max(incomingIntegrationTime, 1);
    // Ensure the integration time isn't outside the range of integers
  }
}

void loop() {
  readFromPython();
  // Check for incoming data from PySerial
  delay(1);
  // Pause the program for 1 millisecond
}

Python code:
(Note this is used with a PyQt button, but any value could be typed in instead of self.IntegrationTimeInputTextbox.text() and the value is still not receieved and echoed back by Arduino).

def SetIntegrationTime(self):
    def main():
        #    global startMarker, endMarker
        #This sets the com port in PySerial to the port with the Genuino as the variable arduino_ports
        arduino_ports = [
            p.device
        for p in serial.tools.list_ports.comports()
        if 'Genuino' in p.description
        ]
        #Set the proper baud rate for your spectrometer
        baud =  115200
        #This prints out the port that was found with the Genuino on it
        ports = list(serial.tools.list_ports.comports())
        for p in ports:
            print ('Device is connected to: ', p)
        # --------------------------- Error Handling ---------------------------
        #Tell the user if no Genuino was found
        if not arduino_ports:
            raise IOError("No Arduino found")
        #Tell the user if multiple Genuinos were found
        if len(arduino_ports) > 1:
            warnings.warn('Multiple Arduinos found - using the first')
        # ---------------------------- Error Handling ---------------------------
    #=====================================
        spectrometer = serial.Serial(arduino_ports[0], baud)
        integrationTimeSend = self.IntegrationTimeInputTextbox.text()
        print("test value is", integrationTimeSend.encode())
        spectrometer.write(integrationTimeSend.encode())
        for i in range(10): #Repeat the following 10 times
            startMarker = "X"
            xDecoded = "qq"
            xEncoded = "qq"
            while xDecoded != startMarker:    #Wait for the start marker (X))
                xEncoded = spectrometer.read() #Read the spectrometer until 'startMarker' is found so the right amound of data is read every time
                xDecoded = xEncoded.decode("UTF-8");
                print(xDecoded);
            line = spectrometer.readline()
            lineDecoded = line.decode("UTF-8")
            print(lineDecoded)
    #=====================================
        spectrometer.close()
    #===========================================

#WaitForArduinoData()
    main()

Body:
First, this is a problem:

incomingValue = Serial.read();

Because read() returns the first byte of incoming serial data reference.  On the Arduino the int is a signed 16-bit integer, so reading only one byte of it with a Serial.read() is going to give you unintended results.

Also, don't put writes in between checking if data is available and actual reading:

 if (Serial.available() > 0) {
    Serial.print("X");                  // Print your startmarker
    Serial.print("The value is now ");
    incomingValue = Serial.read(); // Collect the incoming value from

That is bad.  Instead do your read immediately as this example shows:

    if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();

That's two big issues there.   Take care of those and let's take a look at it after those fundamental issues are corrected.

PART 2

Once those are corrected, the next thing to do is determine which side of the serial communication is faulty.  Generally what I like to do is determine one side is sending properly by having its output show up in a terminal emulator.  I like TeraTerm for this.

Set your python code to send only and see if your sent values show up properly in a terminal emulator.  Once that is working and you have confidence in it, you can attend to the Arduino side.


问:
Connect to MongoDB from Spring Boot Application over SSL
I use the following adjustments for local development in the application.properties:

```<code>myproject.mongodb.databaseName=databaseName
myproject.mongodb.databaseAddress=serverName.mycompany.at
myproject.mongodb.databasePort=27017
myproject.mongodb.username=myProjectName
myproject.mongodb.password=asdfasdf
myproject.mongodb.mappingBasePackage=domain
</code>```

Now I will use the app in a productiv way and therefore need SSL like I can adjust with RoboMongo:

Does anyone know what I have to set in my application.properties file?

答:
As far as I know the only way to connect with options (without extra code) is to use the connection string/uri. It would look something like this:</p>

```<code>spring.data.mongodb.uri=mongodb://myProjectName:asdfasdf@serverName.mycompany.at:27017/databaseName?ssl=true
</code>```

Body:
I use the following adjustments for local development in the application.properties:

myproject.mongodb.databaseName=databaseName
myproject.mongodb.databaseAddress=serverName.mycompany.at
myproject.mongodb.databasePort=27017
myproject.mongodb.username=myProjectName
myproject.mongodb.password=asdfasdf
myproject.mongodb.mappingBasePackage=domain

Now I will use the app in a productiv way and therefore need SSL like I can adjust with RoboMongo:

Does anyone know what I have to set in my application.properties file?

Body:
As far as I know the only way to connect with options (without extra code) is to use the connection string/uri. It would look something like this:

spring.data.mongodb.uri=mongodb://myProjectName:asdfasdf@serverName.mycompany.at:27017/databaseName?ssl=true


问:
my application bug and stop I don't know why
I made a navigation drawer in my project, then I wanted to make a button for sliding left and right but my app stops and blocks.

I get this error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{radiofm.arabelradio/radiofm.arabelradio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
</code>```

Program:

```<code>package radiofm.arabelradio;

import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import java.io.IOException;

import static android.media.AudioManager.STREAM_MUSIC;

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";
    //main_page contain arabel_photo player for radio

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////////////////////////////////////////////////////////////
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.pause();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");
                }
            }
        });
        //main_page contain arabel_photo player for radio//////////////////////////:

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    class PlayerTask extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... strings) {

            try {
                mediaPlayer.setDataSource(strings[0] );
                mediaPlayer.prepare();
                prepared=true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            id_play.setEnabled(true);
            id_play.setImageResource(R.drawable.play);

            // id_play.setText("PLAY");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(started){
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(started){
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(prepared){
            mediaPlayer.release();
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
    //main_page contain arabel_photo player for radio//////////////////////////:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

答: Your activity theme probably without action bar, and the function getActionBar() return null instance.</p>

Body:
I made a navigation drawer in my project, then I wanted to make a button for sliding left and right but my app stops and blocks.

I get this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{radiofm.arabelradio/radiofm.arabelradio.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

Program:

package radiofm.arabelradio;

import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

import java.io.IOException;

import static android.media.AudioManager.STREAM_MUSIC;

public class MainActivity extends AppCompatActivity {

    ImageButton id_play;
    MediaPlayer mediaPlayer;
    boolean prepared = false;
    boolean started =false;
    String stream ="http://arabelfm.ice.infomaniak.ch/arabelprodcastfm.mp3";
    //main_page contain arabel_photo player for radio

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /////////////////////////////////////////////////////////////////////////////
        id_play = (ImageButton) findViewById(R.id.id_play);
        id_play.setEnabled(false);
        //id_play.setText("LOADING");
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        new PlayerTask().execute(stream);
        id_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (started){
                    started=false;
                    mediaPlayer.pause();
                    id_play.setImageResource(R.drawable.play);
                   // id_play.setText("PLAY");
                }
                else {
                    started=true;
                    mediaPlayer.start();
                    id_play.setImageResource(R.drawable.pause);

                    //id_play.setText("PAUSE");
                }
            }
        });
        //main_page contain arabel_photo player for radio//////////////////////////:

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mToggle=new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////
    class PlayerTask extends AsyncTask<String,Void,Boolean>{

        @Override
        protected Boolean doInBackground(String... strings) {

            try {
                mediaPlayer.setDataSource(strings[0] );
                mediaPlayer.prepare();
                prepared=true;
            } catch (IOException e) {
                e.printStackTrace();
            }

            return prepared;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            id_play.setEnabled(true);
            id_play.setImageResource(R.drawable.play);

            // id_play.setText("PLAY");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(started){
            mediaPlayer.pause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(started){
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(prepared){
            mediaPlayer.release();
        }
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////
    //main_page contain arabel_photo player for radio//////////////////////////:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mToggle.onOptionsItemSelected(item))
        {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


问:
What's the benefit of Scala (singleton) object vs. typical class level artifacts
I understand one of the main benefits from using object is, they are real objects instead of system wide functionality.  But finally those objects are also system wide accessible.

Beside of being more "pure"  what additional benefit does scala "objects" offer.

I bet there are a number but I can't really figure out which.

答:
One advantage I can see is that the object will always be lazily initialized. Static on Java will be initialized when a class is accessed even if the static itself is not used.

See this Java code:

```<code>class StaticJava {

  static String AA = "Static String";

  StaticJava() {
  }

}
</code>```

When I call StaticJava constructor, AA will always initialized, even if it is not used.

On Scala:

```<code>object StaticScala {
  val AA = "Static String"
}

class StaticScala
</code>```

Since the object StaticScala will be translated to something like StaticScala$, calling the constructor of StaticScala class will not initialize the singleton object.

Body:
One advantage I can see is that the object will always be lazily initialized. Static on Java will be initialized when a class is accessed even if the static itself is not used.

See this Java code:

class StaticJava {

  static String AA = "Static String";

  StaticJava() {
  }

}

When I call StaticJava constructor, AA will always initialized, even if it is not used.

On Scala:

object StaticScala {
  val AA = "Static String"
}

class StaticScala

Since the object StaticScala will be translated to something like StaticScala$, calling the constructor of StaticScala class will not initialize the singleton object.

ContentLicense: CC BY-SA 2.5


问:
Extending array in HDF5 using PyTables
I normally use h5py to do the HDF5 stuff in Python and if I want to create a dataset which I want to extend later or, I do:

```<code>f = h5py.File('foo.h5', 'w')
d = f.create_dataset('whatever', (5, 5), maxshape=(None, 5), dtype='i8', chunks=True)
...
d.resize((23, 5))
...
</code>```

The maxshape(None, ...) sets the first dimension to "infinity", so it's extensible.

Now I have a project where I need to stick with PyTables and wanted to build up large arrays step by step. Is there a way to extend arrays in PyTables?

This is roughly the idea:

```<code>import tables as tb
import numpy as np

filename = "foo.h5"
h5file = tb.File(filename, "a")

gbar = h5file.create_group(h5file.root, "bar", "Pressure")
h5file.create_array(gbar, 'left', np.array((1, 2, 3, 4)), "...")

# now extend the shape of (4,) and append more arrays iteratively???

h5file.close()
</code>```

答:
I found the solution in the docs: tables.EArray

http://www.pytables.org/usersguide/libref/homogenous_storage.html#earrayclassdescr

Here is a descriptive example code which adds two "columns" with two different ways of dtype definition. The with block can be called multiple times and it will extend the columns:

```<code>import tables as tb
import numpy as np

filename = 'foo.h5'

with tb.File(filename, "a") as f:
    if "/foo" not in f:
        group = f.create_group("/", 'foo', 'Foo Information')
    else:
        group = f.root.foo

    if "col1" not in group:
        a = tb.Atom.from_dtype(np.dtype('<f8'), dflt=0.0)
        arr = f.create_earray(group, 'col1', a, (0,), "Bar")
    else:
        arr = getattr(group, "col1")

    arr.append(np.arange(10))
    arr.append(np.arange(40, 45))

    if "col2" not in group:
        b = tb.Int64Atom()
        arr = f.create_earray(group, 'col2', b, (0,), "Baz")
    else:
        arr = getattr(group, "col")

    arr.append(np.arange(7))
    arr.append(np.arange(30, 38))
</code>```

Title: Extending array in HDF5 using PyTables

Body:
I normally use h5py to do the HDF5 stuff in Python and if I want to create a dataset which I want to extend later or, I do:

f = h5py.File('foo.h5', 'w')
d = f.create_dataset('whatever', (5, 5), maxshape=(None, 5), dtype='i8', chunks=True)
...
d.resize((23, 5))
...

The maxshape(None, ...) sets the first dimension to "infinity", so it's extensible.

Now I have a project where I need to stick with PyTables and wanted to build up large arrays step by step. Is there a way to extend arrays in PyTables?

This is roughly the idea:

import tables as tb
import numpy as np

filename = "foo.h5"
h5file = tb.File(filename, "a")

gbar = h5file.create_group(h5file.root, "bar", "Pressure")
h5file.create_array(gbar, 'left', np.array((1, 2, 3, 4)), "...")

# now extend the shape of (4,) and append more arrays iteratively???

h5file.close()

Body:
I found the solution in the docs: tables.EArray

http://www.pytables.org/usersguide/libref/homogenous_storage.html#earrayclassdescr

Here is a descriptive example code which adds two "columns" with two different ways of dtype definition. The with block can be called multiple times and it will extend the columns:

import tables as tb
import numpy as np

filename = 'foo.h5'

with tb.File(filename, "a") as f:
    if "/foo" not in f:
        group = f.create_group("/", 'foo', 'Foo Information')
    else:
        group = f.root.foo

    if "col1" not in group:
        a = tb.Atom.from_dtype(np.dtype('<f8'), dflt=0.0)
        arr = f.create_earray(group, 'col1', a, (0,), "Bar")
    else:
        arr = getattr(group, "col1")

    arr.append(np.arange(10))
    arr.append(np.arange(40, 45))

    if "col2" not in group:
        b = tb.Int64Atom()
        arr = f.create_earray(group, 'col2', b, (0,), "Baz")
    else:
        arr = getattr(group, "col")

    arr.append(np.arange(7))
    arr.append(np.arange(30, 38))


问:
how to add a stamp (cachet)to a quotation using HTML CSS
I'm new in odoo and HTML&css, all I want is to add a stamp to my qutation so theu user won't need to put a stamp in every single quotation...can anyone help me and guide me to a road to fix that problem

thanks for your help.

```<code>    <table class="table3">
        <tr>
            <td style="width:45%;border-style:none;">

                <table style="width:60%;">
                    <tr>
                        <td style="font-size:14px;margin-left:4px; margin-right:auto;border: 2px"><br/>Bon pour accord le <br/><br/><br/> <br/><br/><br/>Nom, Qualité et signature ou cachet du client<br/><br/></td>
                    </tr>

                </table>

            </td>
            <td>
                <table id="t01">
                    <tr>
                        <td style="width:30%;font-size:12px"><b>Total DA HT</b></td>
                        <td>225,00</td>

                    </tr>
                    <tr>
                        <td style="width:30%; font-size:12px"><b>Total TVA</b></td>
                        <td>55.10</td>
                    </tr>
                    <tr>
                        <td style="width:30%;font-size:12px"><b>Droit de timbre</b></td>
                        <td>0.0</td>
                    </tr>
                    <tr>
                        <td style="width:30%;font-size:12px"><b>Total DA TTC</b></td>
                        <td>350</td>
                    </tr>
                </table>

            </td>
        </tr>
    </table>

    <div class="footer">
            <br/><br/>
                  <div style="text-align:center">
<hr style="border: 1px solid #73ad20">

                            <p style="font-family:KacstFarsi; color:green; font-size:9px">N° R.C.: 1003703 -10 B /00/16//N.I.F.: 001016100370377</p>
                            <p style="font-family:KacstFarsi; color:green; font-size:9px">AGB BANQUE RIB: 03200001500720120844Dely-Brahim /N° Article 16500743415</p>

                    <small>
                        <span>Page</span>
                        <span class="page" />
                        /
                        <span class="topage" />
                    </small>
                  </div>
</div>
</code>```

答:
You could extend res.users with a field for the signature image (fields.binary) and extend the settings view (right corner "login" settings). So every user can set his own signature image. Little hint: res.users is a bit special. You need to implement that field as user-writeable field (Odoo example). In my example the field is called sign_image.

After this you can use this new field in your QWeb report, like:

<t t-if="o.user_id.sign_image">

</t>
```

Where o is the actual record (quotation) which is printed and o.user_id is the salesman on that. If you want to use the user who is printing instead of the salesman use o.env.user.sign_image.

Body:
I'm new in odoo and HTML&css, all I want is to add a stamp to my qutation so theu user won't need to put a stamp in every single quotation...can anyone help me and guide me to a road to fix that problem

thanks for your help.

Bon pour accord le

Nom, Qualité et signature ou cachet du client

                        Total DA HT
                        225,00

                        Total TVA
                        55.10

                        Droit de timbre
                        0.0

                        Total DA TTC
                        350

N° R.C.: 1003703 -10 B /00/16//N.I.F.: 001016100370377

AGB BANQUE RIB: 03200001500720120844Dely-Brahim /N° Article 16500743415

                        Page

                        /

Body:
You could extend res.users with a field for the signature image (fields.binary) and extend the settings view (right corner "login" settings). So every user can set his own signature image. Little hint: res.users is a bit special. You need to implement that field as user-writeable field (Odoo example). In my example the field is called sign_image.

After this you can use this new field in your QWeb report, like:

<t t-if="o.user_id.sign_image">
    <div t-field="o.user_id.sign_image" t-field-options='{"widget": "image"}'/>
</t>

Where o is the actual record (quotation) which is printed and o.user_id is the salesman on that. If you want to use the user who is printing instead of the salesman use o.env.user.sign_image.


问:
Exporting to Excel with JasperReports: How to add AutoFilter for columns
I am using this code for create report in MS Excel format:

```<code>JRXlsExporter exporter = new JRXlsExporter();
</code>```

From there I don't know if it's possible to tell JasperReports to apply an auto filter on each column.

答:
Go to the 'Exporter Parameters' pane and make sure none of the 'Start' or 'Stop' options are set for Auto Filter. Choose the empty space in the related list box (see the attached image). Then run the report again. This time you should see the filters in the right places.

http://community.jaspersoft.com/jaspersoft-studio/issues/6876

Body:
I am using this code for create report in MS Excel format:

JRXlsExporter exporter = new JRXlsExporter();

From there I don't know if it's possible to tell JasperReports to apply an auto filter on each column.


问:
Center/middle align element larger than container
EDIT: Trying to reword the question so that the problem is understood correctly

I have a div element within which there is a video element. The div element is resizable. The video element needs to be resizable too but it also needs to keep its original aspect ratio.

.container {
  background: #ff9;
  height: 150px;
  width: 100px;
}

.subcontainer {
  background: #9ff;
  min-width: 100%;
  min-height: 100%;
  margin: 5px;
}

.fixedsize{
  background: #9f9;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="subcontainer">
    <video class="fixedsize" src="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy-hd.mp4" poster="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy_s.gif" autoplay="" loop="" playsinline=""></video>
  </div>
</div></code>```

So I need, the video element here to be centered both horizontally and vertically without losing the aspect ratio of it.

.container {
  background: #ff9;
  height: 400px;
  width: 1000px;
}

.subcontainer {
  background: #9ff;
  min-width: 100%;
  min-height: 100%;
  margin: 5px;
}

.fixedsize {
  background: #9f9;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="subcontainer">
    <video class="fixedsize" src="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy-hd.mp4" poster="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy_s.gif" autoplay="" loop="" playsinline=""></video>
  </div>
</div></code>```

In this case, I want the video to stretch vertically and then centered horizontally.

Similar case for where the width of container is greater than the video width; I'd want the video to stretch horizontally and centered vertically.

Is this possible with only css?

答:
max-width and max-height both set to 100% will force the element to stay smaller than its parent. The aligment is the same as one would usually do to center a block element.

.container {
  background: #ff9;
  height: 150px;
  width: 100px;
  //overflow: hidden;
}

.subcontainer {
  background: #9ff;
  min-width: 100%;
  min-height: 100%;
  margin: 5px;
  //overflow: hidden;
  position: relative;
}

.fixedsize{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 100%;
  max-height: 100%;
  background: #9f9;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="subcontainer">
    <video class="fixedsize" src="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy-hd.mp4" poster="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy_s.gif" autoplay="" loop="" playsinline=""></video>
  </div>
</div></code>```

Body:
EDIT: Trying to reword the question so that the problem is understood correctly

I have a div element within which there is a video element. The div element is resizable. The video element needs to be resizable too but it also needs to keep its original aspect ratio.

.container {
  background: #ff9;
  height: 150px;
  width: 100px;
}

.subcontainer {
  background: #9ff;
  min-width: 100%;
  min-height: 100%;
  margin: 5px;
}

.fixedsize{
  background: #9f9;
}

    <video class="fixedsize" src="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy-hd.mp4" poster="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy_s.gif" autoplay="" loop="" playsinline=""></video>

So I need, the video element here to be centered both horizontally and vertically without losing the aspect ratio of it.

.container {
  background: #ff9;
  height: 400px;
  width: 1000px;
}

.subcontainer {
  background: #9ff;
  min-width: 100%;
  min-height: 100%;
  margin: 5px;
}

.fixedsize {
  background: #9f9;
}

    <video class="fixedsize" src="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy-hd.mp4" poster="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy_s.gif" autoplay="" loop="" playsinline=""></video>

In this case, I want the video to stretch vertically and then centered horizontally.

Similar case for where the width of container is greater than the video width; I'd want the video to stretch horizontally and centered vertically.

Is this possible with only css?

Body:
max-width and max-height both set to 100% will force the element to stay smaller than its parent. The aligment is the same as one would usually do to center a block element.

.container {
  background: #ff9;
  height: 150px;
  width: 100px;
  //overflow: hidden;
}

.subcontainer {
  background: #9ff;
  min-width: 100%;
  min-height: 100%;
  margin: 5px;
  //overflow: hidden;
  position: relative;
}

.fixedsize{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 100%;
  max-height: 100%;
  background: #9f9;
}

<div class="container">
  <div class="subcontainer">
    <video class="fixedsize" src="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy-hd.mp4" poster="https://media.giphy.com/media/3ohryjnGyiSRrGWKn6/giphy_s.gif" autoplay="" loop="" playsinline=""></video>
  </div>
</div>


问:
How to open and gather all the results from a list into threads with CompletableFuture?
I have a list of Strings, and for each of them, I need to open a new thread and to gather all the information into a CompletableFuture.

This is my iteration:

```<code>for (String result: results) {
    candidateInfos.add(getCandidatesInfo(result));
}
</code>```

I am trying for the first time the implementation of threads and I would appreciate some help.

答:
You can build Stream for each method call and can then collect the result into a list as follows.

```<code>Stream.Builder<Supplier<CanditateInfo>> streamBuilder = Stream.builder();

results.forEach(string-> streamBuilder.accept(() -> this.getCandidatesInfo(string)));

List<CanditateInfo> candidateInfos = streamBuilder.build().map(supplier -> CompletableFuture.supplyAsync(supplier, Executors.newFixedThreadPool(
  results.size()))).collect(Collectors.toList()).stream().map(
     CompletableFuture::join).collect(Collectors.toList());
</code>```

Here I have used the separate Executor because by default, java use the common Fork and Join Pool which will block all other threads if the pool would have got filled. For more Info see http://fahdshariff.blogspot.in/2016/06/java-8-completablefuture-vs-parallel.html

Edit: Less syntax.

You can directly create a stream using a list or if you an array then using Arrays.stream instead of using Stream.Builder

```<code>           List<CanditateInfo> candidateInfos = results.stream().map(s ->
 CompletableFuture.supplyAsync(this.getCandidatesInfo(s), Executors.newFixedThreadPool(
           results.size()))).map(CompletableFuture::join).collect(Collectors.toList());
</code>```

Body:
I have a list of Strings, and for each of them, I need to open a new thread and to gather all the information into a CompletableFuture.

This is my iteration:

for (String result: results) {
    candidateInfos.add(getCandidatesInfo(result));
}

I am trying for the first time the implementation of threads and I would appreciate some help.

Body:
You can build Stream for each method call and can then collect the result into a list as follows.

Stream.Builder<Supplier<CanditateInfo>> streamBuilder = Stream.builder();

results.forEach(string-> streamBuilder.accept(() -> this.getCandidatesInfo(string)));

List<CanditateInfo> candidateInfos = streamBuilder.build().map(supplier -> CompletableFuture.supplyAsync(supplier, Executors.newFixedThreadPool(
  results.size()))).collect(Collectors.toList()).stream().map(
     CompletableFuture::join).collect(Collectors.toList());

Here I have used the separate Executor because by default, java use the common Fork and Join Pool which will block all other threads if the pool would have got filled. For more Info see http://fahdshariff.blogspot.in/2016/06/java-8-completablefuture-vs-parallel.html

Edit: Less syntax.

You can directly create a stream using a list or if you an array then using Arrays.stream instead of using Stream.Builder

           List<CanditateInfo> candidateInfos = results.stream().map(s ->
 CompletableFuture.supplyAsync(this.getCandidatesInfo(s), Executors.newFixedThreadPool(
           results.size()))).map(CompletableFuture::join).collect(Collectors.toList());


问:
Guzzle async POST requests not being sent
I'm trying to make 4 async search calls (POST HTTP request) to search 4 database tables at the same time, then wait for all of them to finish (asynchronously), combine the results and return them to the user.

Here is my code:

```<code>public static function async_search($search_words)
{
    $curl = new CurlMultiHandler();
    $client = new Client([
        'base_uri' => 'https://mytestapi.com/',
        'timeout' => 0,
    ]);

    $finished_promisesArr = array(
        'search1' => 0,
        'search2' => 0,
        'search3' => 0,
        'search4' => 0,
    );

    $bodyArr = array(
        'search_words' => $search_words,
    );

    $search1_promise = $client->requestAsync('POST', 'search1', array(
        'form_params' => $bodyArr,
    ))->then(
        function(ResponseInterface $response) {
            echo 'got response';
            $finished_promisesArr['search1'] = 1;
        },
        function (RequestException $e) {
            $finished_promisesArr['search1'] = 1;
        }
    );

    $search2_promise = $client->requestAsync('POST', 'search2', array(
        'form_params' => $bodyArr,
    ))->then(
        function(ResponseInterface $response) {
            $finished_promisesArr['search2'] = 1;
        },
        function (RequestException $e) {
            $finished_promisesArr['search2'] = 1;
        }
    );

    $search3_promise = $client->requestAsync('POST', 'searchCompanies', array(
        'form_params' => $bodyArr,
    ))->then(
        function(ResponseInterface $response) {
            $finished_promisesArr['search3'] = 1;
        },
        function (RequestException $e) {
            $finished_promisesArr['search3'] = 1;
        }
    );

    $search4_promise = $client->requestAsync('POST', 'searchCompaniesByIndustries', array(
        'form_params' => $bodyArr,
    ))->then(
        function(ResponseInterface $response) {
            $finished_promisesArr['search4'] = 1;
        },
        function (RequestException $e) {
            $finished_promisesArr['search4'] = 1;
        }
    );

    $promisesAggregate = GuzzleHttp\Promise\all([$search1_promise, $search2_promise, $search3_promise, $search4_promise]);
    foreach ($promisesAggregate as $agg) {
        $curl->tick();
    }

    $keep_running = true;
    while ($keep_running) {
        $all_processes_finished = true;
        foreach ($finished_promisesArr as $promise => $status) {
            if (!$status) {
                $all_processes_finished = false;
            }
        }

        if ($all_processes_finished) {
            $keep_running = false;
        }
    }

    return array();
}
</code>```

Please ignore the empty array in the result and the fact that I'm not doing anything with the response.
I've got logs on the server methods and they're not even being called, and the loop continues to run infinitely.

Note that when I use the request method instead of requestAsync I do get the correct result.

Any ideas here?

Thank's!

答:
Just call $promisesAggregate->wait() after you get it from GuzzleHttp\Promise\all function.

It means the same as your code, but does it right (your wait code calls ->tick() only once and this is the mistake).

Body:
I'm trying to make 4 async search calls (POST HTTP request) to search 4 database tables at the same time, then wait for all of them to finish (asynchronously), combine the results and return them to the user.

Here is my code:

public static function async_search($search_words)
{
    $curl = new CurlMultiHandler();
    $client = new Client([
        'base_uri' => 'https://mytestapi.com/',
        'timeout' => 0,
    ]);

    $finished_promisesArr = array(
        'search1' => 0,
        'search2' => 0,
        'search3' => 0,
        'search4' => 0,
    );

    $bodyArr = array(
        'search_words' => $search_words,
    );

    $search1_promise = $client->requestAsync('POST', 'search1', array(
        'form_params' => $bodyArr,
    ))->then(
        function(ResponseInterface $response) {
            echo 'got response';
            $finished_promisesArr['search1'] = 1;
        },
        function (RequestException $e) {
            $finished_promisesArr['search1'] = 1;
        }
    );

    $search2_promise = $client->requestAsync('POST', 'search2', array(
        'form_params' => $bodyArr,
    ))->then(
        function(ResponseInterface $response) {
            $finished_promisesArr['search2'] = 1;
        },
        function (RequestException $e) {
            $finished_promisesArr['search2'] = 1;
        }
    );

    $search3_promise = $client->requestAsync('POST', 'searchCompanies', array(
        'form_params' => $bodyArr,
    ))->then(
        function(ResponseInterface $response) {
            $finished_promisesArr['search3'] = 1;
        },
        function (RequestException $e) {
            $finished_promisesArr['search3'] = 1;
        }
    );

    $search4_promise = $client->requestAsync('POST', 'searchCompaniesByIndustries', array(
        'form_params' => $bodyArr,
    ))->then(
        function(ResponseInterface $response) {
            $finished_promisesArr['search4'] = 1;
        },
        function (RequestException $e) {
            $finished_promisesArr['search4'] = 1;
        }
    );

    $promisesAggregate = GuzzleHttp\Promise\all([$search1_promise, $search2_promise, $search3_promise, $search4_promise]);
    foreach ($promisesAggregate as $agg) {
        $curl->tick();
    }

    $keep_running = true;
    while ($keep_running) {
        $all_processes_finished = true;
        foreach ($finished_promisesArr as $promise => $status) {
            if (!$status) {
                $all_processes_finished = false;
            }
        }

        if ($all_processes_finished) {
            $keep_running = false;
        }
    }

    return array();
}

Please ignore the empty array in the result and the fact that I'm not doing anything with the response.
I've got logs on the server methods and they're not even being called, and the loop continues to run infinitely.

Note that when I use the request method instead of requestAsync I do get the correct result.

Any ideas here?

Thank's!


问:
Reading text from image in Python Selenium
Is it possible to scrap text from image element, as in the picture:

Picture

I did everything else, but

```<code>Salzufer 16
10587 Berlin
</code>```

Is in the shape of an image?

I use Selenium webdriver and need to scrape data like Address,Contact,Branch of economic activity..

答:
If you inspect the html (search for the address) you'll see, that the address actually appears in a javascript code, that generates a google map.

You could exploit this using a regular expression.

Assuming that you've already coded the part where you perform the search and now just need to extract the address. Your selenium object is named driver. Then it would be something like this:

```<code>import re
page_source = driver.page_source
add_pattern = '{address: \"(.*?)\"}'
address = re.search(page_source, add_pattern).group(1)
print(address)
</code>```

Body:
Is it possible to scrap text from image element, as in the picture:

Picture

I did everything else, but

Salzufer 16
10587 Berlin

Is in the shape of an image?

I use Selenium webdriver and need to scrape data like Address,Contact,Branch of economic activity..

Body:
If you inspect the html (search for the address) you'll see, that the address actually appears in a javascript code, that generates a google map.

You could exploit this using a regular expression.

Assuming that you've already coded the part where you perform the search and now just need to extract the address. Your selenium object is named driver. Then it would be something like this:

import re
page_source = driver.page_source
add_pattern = '{address: \"(.*?)\"}'
address = re.search(page_source, add_pattern).group(1)
print(address)


问:
Qt stylesheet and QString::arg()
To keep a Stylesheet dynamic regarding DPI settings, I want to set certain parts of it from code.

This works:

```<code>my_label->setStyleSheet( QString( "font-size: 30px;" ) );
</code>```

Yet, this doesn't:

```<code>my_label->setStyleSheet( QString( "font-size: %1px;" ).arg( 30 ) );
</code>```

Can anyone enlighten me, why this is? Running Qt 5.7.

答:
The issue was a combination of two things:

I needed to convert the value to a string first

The actual value passed to the arg() during runtime had a decimal place, the "30" was just for testing

While I did try different combinations (integer values (30), converting to QString first), I did not try using an integer value AND converting it to QString together.
So everyone was kinda right. Thanks for the patience.

Title: Qt stylesheet and QString::arg()

Body:
To keep a Stylesheet dynamic regarding DPI settings, I want to set certain parts of it from code.

This works:

my_label->setStyleSheet( QString( "font-size: 30px;" ) );

Yet, this doesn't:

my_label->setStyleSheet( QString( "font-size: %1px;" ).arg( 30 ) );

Can anyone enlighten me, why this is? Running Qt 5.7.


问:
How to get unit tests to run in Maven Tycho build?
I've done a lot of work in the past writing unit tests that run in "conventional" Maven builds,
using JUnit and Mockito (and PowerMock).  I'm now working on an Eclipse plugin codebase, which builds with Maven Tycho.

Overall, it's a multiproject build, but I'm only adding unit tests to one of the plugin projects (for now).

I've heard of tycho-surefire, but that seems pretty complicated, and it really sounds more like it supports integration tests instead of unit tests.  I'm guessing I'll probably have no choice but to use this, but so far I haven't tried to integrate it.

I tried getting the JUnit and Mockito artifacts from Maven, and then using the maven-dependency-plugin to get the artifacts available to be referenced in the Bundle-Classpath property of the manifest.

When I run the build, the tycho-compiler-plugin I see it compiling 105 source files, which includes all of the classes in src/main/java and src/test/java.
 It fails to compile the test class because it can't find the Mockito classes, even though when I run the build with -X, it shows the mockito-all artifact in the dependency tree.

What can I do here?

答:
After a lot of painful Maven trial & error I struggled across this website, which provides a surprisingly easy way to use unit-tests in a Maven-Tycho setup.

Here, the important parts of the pom.xml when using JUnit (probably looks similar for Mockito):

```<code><testSourceDirectory>src/test/java</testSourceDirectory>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12.4</version>
    <executions>
      <execution>
        <id>test</id>
        <phase>test</phase>
        <configuration>
          <includes>
            <include>**/*Test.java</include>
          </includes>
        </configuration>
        <goals>
          <goal>test</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.5.1</version>
    <executions>
      <execution>
        <id>compiletests</id>
        <phase>test-compile</phase>
        <goals>
          <goal>testCompile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>
</code>```

Name all your tests in a way so that they end with *Test.java. Run mvn test in order to execute all available unit-tests.

Body:
After a lot of painful Maven trial & error I struggled across this website, which provides a surprisingly easy way to use unit-tests in a Maven-Tycho setup.

Here, the important parts of the pom.xml when using JUnit (probably looks similar for Mockito):

<testSourceDirectory>src/test/java</testSourceDirectory>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12.4</version>
    <executions>
      <execution>
        <id>test</id>
        <phase>test</phase>
        <configuration>
          <includes>
            <include>**/*Test.java</include>
          </includes>
        </configuration>
        <goals>
          <goal>test</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.5.1</version>
    <executions>
      <execution>
        <id>compiletests</id>
        <phase>test-compile</phase>
        <goals>
          <goal>testCompile</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>

Name all your tests in a way so that they end with *Test.java. Run mvn test in order to execute all available unit-tests.


问:
Redirect Specific non-existing URL to an existing
I have a simple need to redirect:

mypage.com/myurl (which doesn't not exist; meening that returns a 404 error)

To

mypage.com/newurl/myurl (which is an exitsing page with content).

I saw a tons of forum post about this, but didn't find an awnser. I tried lot of thinks but with internal server error, infinitive loops etc.

Please note that I have a www to non www permanent redirect, like this:

```<code>RewriteCond %{HTTP_HOST} ^www\.mypage\.si [NC]
RewriteRule ^(.*)$ http://mypage.si/$1 [L,R=301]
</code>```

UPDATE:

I will be specific:

This URL doesn't exist:  http://domodom.si/sl/nepremicnine

and needs to be redirected here: http://domodom.si/sl/nepremicnine/nepremicnine-ponudba

Hope this will offer more insights about the problem.

Thanks

答:
assuming mod_rewrite

RedirectPermanent /myurl/ mypage.com/newurl/myurl

Body:
I have a simple need to redirect:

mypage.com/myurl (which doesn't not exist; meening that returns a 404 error)

To

mypage.com/newurl/myurl (which is an exitsing page with content).

I saw a tons of forum post about this, but didn't find an awnser. I tried lot of thinks but with internal server error, infinitive loops etc.

Please note that I have a www to non www permanent redirect, like this:

RewriteCond %{HTTP_HOST} ^www\.mypage\.si [NC]
RewriteRule ^(.*)$ http://mypage.si/$1 [L,R=301]

UPDATE:

I will be specific:

This URL doesn't exist:  http://domodom.si/sl/nepremicnine

and needs to be redirected here: http://domodom.si/sl/nepremicnine/nepremicnine-ponudba

Hope this will offer more insights about the problem.

Thanks


问:
Plot the data in real time in Matlab
I have a few files which I am planning to plot in Matlab. I have loaded the files and I wanted to plot it in real time. As in I want to see it as it is being plotted. </p>

```<code>%clear
[filename, pathname] = uigetfile('*.raw;*.prc', 'Pick raw or processed data file');
N=str2double(filename(5:6));
Fs = 145.3*10^3;
T = 1/Fs; % Sampling period
if isequal(filename(end-2:end),'raw')
    % load raw data file
    fid = fopen([pathname filename],'r','l');
    A=fread(fid,inf,'*uint16')'; %s=ftell(fid);
    B=bitand(A, hex2dec('0FFF')); C=bitshift(A,-12);
    channels=sort(C(1:N));
    rawdata(int16(numel(A)/N)+2,N)=uint16(0); % Need to add +2 due to data loss
    for ii=1:N
        %rawdata(:,ii)=B(C==channels(ii)); can't use due to data loss
        temp=B(C==channels(ii));
        rawdata(1:numel(temp),ii)=temp;
    end
    plot(3.3/4095*single(rawdata))
    legend(int2str(channels'))
else
    %load processed file
    fid = fopen([pathname filename],'r','b');
    A= fread(fid,inf,'*single')';
    prcdata=reshape(A,N,[])';

    %Find time
    N = size(prcdata(:,1),1);
    t=T*(0:N-1)';

for u = 1:N;
        x=0:(T*(0:u-1)');
        plot(x,prcdata(:,4));
   drawnow;
   end
end
</code>```

答:
I know one heuristic way but it certainly works:</p>

```<code>for u = 1:N;
    x(u)=0:(T*(0:u-1)');
    plot(x(1:u),prcdata(:,4));
    pause(0.01);
end
</code>```

Title: Plot the data in real time in Matlab

Body:
I have a few files which I am planning to plot in Matlab. I have loaded the files and I wanted to plot it in real time. As in I want to see it as it is being plotted.

%clear
[filename, pathname] = uigetfile('*.raw;*.prc', 'Pick raw or processed data file');
N=str2double(filename(5:6));
Fs = 145.3*10^3;
T = 1/Fs; % Sampling period
if isequal(filename(end-2:end),'raw')
    % load raw data file
    fid = fopen([pathname filename],'r','l');
    A=fread(fid,inf,'*uint16')'; %s=ftell(fid);
    B=bitand(A, hex2dec('0FFF')); C=bitshift(A,-12);
    channels=sort(C(1:N));
    rawdata(int16(numel(A)/N)+2,N)=uint16(0); % Need to add +2 due to data loss
    for ii=1:N
        %rawdata(:,ii)=B(C==channels(ii)); can't use due to data loss
        temp=B(C==channels(ii));
        rawdata(1:numel(temp),ii)=temp;
    end
    plot(3.3/4095*single(rawdata))
    legend(int2str(channels'))
else
    %load processed file
    fid = fopen([pathname filename],'r','b');
    A= fread(fid,inf,'*single')';
    prcdata=reshape(A,N,[])';

    %Find time
    N = size(prcdata(:,1),1);
    t=T*(0:N-1)';

for u = 1:N;
        x=0:(T*(0:u-1)');
        plot(x,prcdata(:,4));
   drawnow;
   end
end

Body:
I know one heuristic way but it certainly works:

for u = 1:N;
    x(u)=0:(T*(0:u-1)');
    plot(x(1:u),prcdata(:,4));
    pause(0.01);
end


问:
Plotting columns as series
I have a dataframe which has 12 columns (one for each month of the year) and an id. Each record in this dataframe corresponds to the transaction amount(in dollars) a customer has made over the course of last twelve months. I want to plot these columns as series. And I also want to plot all the customers in the dataframe. The x-axis will be the month index and y-axis will be dollar value. So basically for each customer I need a line or series chart on the same graph.

Code for generating random data

```<code>a <- data.frame(id = seq(1,1000,1))
b <- data.frame(replicate(12,sample(1000:100000,1000,rep=TRUE)))
df <- cbind(a,b)
</code>```

This is what I tried but its not what I want

```<code>library(reshape2)
library(ggplot2)
df_lg <- melt(df, id = 'id') # convert from wide to tall
ggplot(data=df_lg,
       aes(x=variable, y=value, colour=variable)) +
  geom_line()
</code>```

Any ideas how to do this?

答:
Just add group to your aesthetics, so the colour and group should be the id variable you want in the legend.

```<code>ggplot(data=df_lg,
       aes(x=variable, y=value, colour=id, group = id)) +
  geom_line()
</code>```

Title: Plotting columns as series

Body:
I have a dataframe which has 12 columns (one for each month of the year) and an id. Each record in this dataframe corresponds to the transaction amount(in dollars) a customer has made over the course of last twelve months. I want to plot these columns as series. And I also want to plot all the customers in the dataframe. The x-axis will be the month index and y-axis will be dollar value. So basically for each customer I need a line or series chart on the same graph.

Code for generating random data

a <- data.frame(id = seq(1,1000,1))
b <- data.frame(replicate(12,sample(1000:100000,1000,rep=TRUE)))
df <- cbind(a,b)

This is what I tried but its not what I want

library(reshape2)
library(ggplot2)
df_lg <- melt(df, id = 'id') # convert from wide to tall
ggplot(data=df_lg,
       aes(x=variable, y=value, colour=variable)) +
  geom_line()

Any ideas how to do this?

Body:
Just add group to your aesthetics, so the colour and group should be the id variable you want in the legend.

ggplot(data=df_lg,
       aes(x=variable, y=value, colour=id, group = id)) +
  geom_line()


问:
Add buttons to google sheets that links me to another sheet
Im in need for a script that when I make a button in google sheets. I can click on it and will take me to another work sheet. Something like below but I cant get this to work

```<code>function GoToSheet1() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';
</code>```

Thanks in advance Jarrad

答:
Could you just insert a hyperlink into a cell and format it (colours, borders etc) so it "looks" like a button?  Then protect that cell so other users can't alter it.  A formula you could enter into a cell would be simply:

```<code>=HYPERLINK("http://link.to.spreadsheet", "Button Text")
</code>```

If you need something more complex, and hence a script, we'll need more information.  I'm not sure why you'd use a script for the purpose you have explained.

For example - is the sheet (link) different for each row of the spreadsheet, or different for each worksheet within the spreadsheet.  Perhaps share a redacted screenshot of the spreadsheet to give us more of an idea of what you are trying to achive.

Body:
Im in need for a script that when I make a button in google sheets. I can click on it and will take me to another work sheet. Something like below but I cant get this to work

function GoToSheet1() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';

Thanks in advance Jarrad

Body:
Could you just insert a hyperlink into a cell and format it (colours, borders etc) so it "looks" like a button?  Then protect that cell so other users can't alter it.  A formula you could enter into a cell would be simply:

=HYPERLINK("http://link.to.spreadsheet", "Button Text")

If you need something more complex, and hence a script, we'll need more information.  I'm not sure why you'd use a script for the purpose you have explained.

For example - is the sheet (link) different for each row of the spreadsheet, or different for each worksheet within the spreadsheet.  Perhaps share a redacted screenshot of the spreadsheet to give us more of an idea of what you are trying to achive.


问:
WPF Add more interaction to listview items
I am binding my listview to a viewmodel using Caliburn. My view's code is the following:

```<code><ListView  x:Name="ListView" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding ProjectsPMod}" Margin="110,0,110,131" HorizontalContentAlignment="Stretch" BorderThickness="0" Height="111" VerticalAlignment="Bottom">
        <interactivity:Interaction.Triggers>
            <interactivity:EventTrigger EventName="SelectionChanged">
                <cal:ActionMessage MethodName="OpenProjectShell">
                    <cal:Parameter Value="{Binding ElementName=ListView, Path=SelectedItem}" />
                </cal:ActionMessage>
            </interactivity:EventTrigger>
        </interactivity:Interaction.Triggers>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <ContentControl  Content="{StaticResource  Appbar_Suitcase}" />
                        <Label Content="{Binding Name}"/>
                    </StackPanel>

                    <Separator HorizontalAlignment="Stretch" Margin="0, 10, 0, 0"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

Right now each item in every row just displays its name and a briefcase icon. If I wanted to add an "Edit"further down that row, where if you clicked on it something happened (perhaps a popup appears), how would I do it?

答:
If you mean "How to add an edit button for each row?" then you simply need to add a button in the ItemTemplate:</p>

```<code> <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <ContentControl  Content="{StaticResource  Appbar_Suitcase}" />
                    <Label Content="{Binding Name}"/>
                    <!-- Edit button -->
                    <Button Command="{Binding EditCommandOnViewModel}" Content="Edit" />
                </StackPanel>

                <Separator HorizontalAlignment="Stretch" Margin="0, 10, 0, 0"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</code>```

Body:
I am binding my listview to a viewmodel using Caliburn. My view's code is the following:

<ListView  x:Name="ListView" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding ProjectsPMod}" Margin="110,0,110,131" HorizontalContentAlignment="Stretch" BorderThickness="0" Height="111" VerticalAlignment="Bottom">
        <interactivity:Interaction.Triggers>
            <interactivity:EventTrigger EventName="SelectionChanged">
                <cal:ActionMessage MethodName="OpenProjectShell">
                    <cal:Parameter Value="{Binding ElementName=ListView, Path=SelectedItem}" />
                </cal:ActionMessage>
            </interactivity:EventTrigger>
        </interactivity:Interaction.Triggers>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <StackPanel Orientation="Horizontal">
                        <ContentControl  Content="{StaticResource  Appbar_Suitcase}" />

                    </StackPanel>

                    <Separator HorizontalAlignment="Stretch" Margin="0, 10, 0, 0"/>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Right now each item in every row just displays its name and a briefcase icon. If I wanted to add an "Edit"further down that row, where if you clicked on it something happened (perhaps a popup appears), how would I do it?

Body:
If you mean "How to add an edit button for each row?" then you simply need to add a button in the ItemTemplate:

 <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <StackPanel Orientation="Horizontal">
                    <ContentControl  Content="{StaticResource  Appbar_Suitcase}" />
                    <Label Content="{Binding Name}"/>
                    <!-- Edit button -->
                    <Button Command="{Binding EditCommandOnViewModel}" Content="Edit" />
                </StackPanel>

                <Separator HorizontalAlignment="Stretch" Margin="0, 10, 0, 0"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>


问:
Adding value to column depending on LIKE
I have SSMS 2008 R2. This is my table

```<code>PK | DateOf           | Other Columns | Items
01 | 05/30/2017 15:30 | Blah          | truck, elephant, apple, . . .
02 | 04/15/2012 07:07 | Bluh          | foot, orange, horse, . . .
03 | 11/01/2016 10:30 | Wham          | apple, screen, penny, . . .
</code>```

I am trying to search the Items column for each record and count how many times the fruits occur. Conveniently enough, there will only be a single fruit for each record, but it would be cool if the solution would be able to handle several fruits (maybe even duplicates). The result table would look like this for the above

```<code>Count | Fruit
2     | Apple
1     | Orange
</code>```

I have a complete list of the "fruits". I was trying to figure out how to make it work with LIKE's.

```<code>SELECT
count(PK) AS [Count]
??? AS [Fruit]
WHERE DateOf >= '2011-01-01 00:00' AND DateOf < '2012-01-01 00:00'
AND Items LIKE '%Apple%' --??(some kind of code that looks for the fruit values??)
</code>```

答:
Try this it may helps you

```<code>IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp

DECLARE @SearchWords nvarchar(max)='Apple,Orange'

DECLARE @Table TABLE (SearchWords nvarchar(max))
INSERT INTO @Table
SELECT @SearchWords

;With cte_Search
AS
(
SELECT  ROW_NUMBER()OVER(ORDER BY (SELECT 1) )AS Seq,
        Split.a.value('.', 'VARCHAR(1000)') AS SearchWords
            FROM (
                SELECT
                     CAST('<S>' + REPLACE(SearchWords, ',', '</S><S>') + '</S>' AS XML) AS SearchWords
                FROM @Table
                ) AS A
            CROSS APPLY SearchWords.nodes('/S') AS Split(a)

)
SELECT * INTO #Temp  FROM cte_Search

;With CTE (PK , DateOf , OtherColumns , Items)
AS
(
SELECT 01 , '05/30/2017 15:30' ,'Blah', 'truck, elephant, apple'UNION ALL
SELECT 02 , '04/15/2012 07:07' ,'Bluh', 'foot, orange, horse'   UNION ALL
SELECT 03 , '11/01/2016 10:30' ,'Wham', 'apple, screen, penny'
)
SELECT SearchWords AS Fruit,
        MAX(Seq) AS CountOFFruits FROM
(
SELECT C.OtherColumns,
        t.SearchWords,
        C.Items,
        COUNT(C.Items) CntItems,
        ROW_NUMBER()OVER(Partition by t.SearchWords order by  C.OtherColumns ) AS Seq
         FROM CTE c ,#Temp t
WHERE CHARINDEX(t.SearchWords,c.Items) >0
Group by C.OtherColumns,t.SearchWords,C.Items
)dt
Group by SearchWords
</code>```

Result

```<code>Fruit   CountOFFruits
----------------------
Apple   2
Orange  1
</code>```

Body:
I have SSMS 2008 R2. This is my table

PK | DateOf           | Other Columns | Items
01 | 05/30/2017 15:30 | Blah          | truck, elephant, apple, . . .
02 | 04/15/2012 07:07 | Bluh          | foot, orange, horse, . . .
03 | 11/01/2016 10:30 | Wham          | apple, screen, penny, . . .

I am trying to search the Items column for each record and count how many times the fruits occur. Conveniently enough, there will only be a single fruit for each record, but it would be cool if the solution would be able to handle several fruits (maybe even duplicates). The result table would look like this for the above

Count | Fruit
2     | Apple
1     | Orange

I have a complete list of the "fruits". I was trying to figure out how to make it work with LIKE's.

SELECT
count(PK) AS [Count]
??? AS [Fruit]
WHERE DateOf >= '2011-01-01 00:00' AND DateOf < '2012-01-01 00:00'
AND Items LIKE '%Apple%' --??(some kind of code that looks for the fruit values??)

Body:
Try this it may helps you

IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp

DECLARE @SearchWords nvarchar(max)='Apple,Orange'

DECLARE @Table TABLE (SearchWords nvarchar(max))
INSERT INTO @Table
SELECT @SearchWords

;With cte_Search
AS
(
SELECT  ROW_NUMBER()OVER(ORDER BY (SELECT 1) )AS Seq,
        Split.a.value('.', 'VARCHAR(1000)') AS SearchWords
            FROM (
                SELECT
                     CAST('<S>' + REPLACE(SearchWords, ',', '</S><S>') + '</S>' AS XML) AS SearchWords
                FROM @Table
                ) AS A
            CROSS APPLY SearchWords.nodes('/S') AS Split(a)

)
SELECT * INTO #Temp  FROM cte_Search

;With CTE (PK , DateOf , OtherColumns , Items)
AS
(
SELECT 01 , '05/30/2017 15:30' ,'Blah', 'truck, elephant, apple'UNION ALL
SELECT 02 , '04/15/2012 07:07' ,'Bluh', 'foot, orange, horse'   UNION ALL
SELECT 03 , '11/01/2016 10:30' ,'Wham', 'apple, screen, penny'
)
SELECT SearchWords AS Fruit,
        MAX(Seq) AS CountOFFruits FROM
(
SELECT C.OtherColumns,
        t.SearchWords,
        C.Items,
        COUNT(C.Items) CntItems,
        ROW_NUMBER()OVER(Partition by t.SearchWords order by  C.OtherColumns ) AS Seq
         FROM CTE c ,#Temp t
WHERE CHARINDEX(t.SearchWords,c.Items) >0
Group by C.OtherColumns,t.SearchWords,C.Items
)dt
Group by SearchWords

Result

Fruit   CountOFFruits
----------------------
Apple   2
Orange  1


问:
openxlsx - changing of header not wanted
I write a list of data.frames into an xlsx file with openxlsx. I do not like that the package changes the column names so that they contain the sheet name. Is there a way how to switch it off? I cannot find it.</p>

```<code>library(openxlsx)

write.list <- function(data.list, filepath, digits=3, row.names=TRUE)
{
  wb = createWorkbook()

  for (i in 1:length(names(data.list))) {
    idx = names(data.list)[i]
    addWorksheet(wb, idx)
    rounded = data.frame(lapply(data.list[idx], function(x)
                                  {if(is.numeric(x)) round(x, digits) else x}))
    writeData(wb, sheet=i, rounded, rowNames=row.names)
  }

  saveWorkbook(wb, filepath)
}
</code>```

答:
The problem is coming from where you are creating the rounded object. You need to use a [[ instead of [ to get the list current list element. Changing the the rounded = line to the following should correct this.

```<code>rounded = data.frame(lapply(data.list[[idx]], function(x)
</code>```

Body:
I write a list of data.frames into an xlsx file with openxlsx. I do not like that the package changes the column names so that they contain the sheet name. Is there a way how to switch it off? I cannot find it.

library(openxlsx)

write.list <- function(data.list, filepath, digits=3, row.names=TRUE)
{
  wb = createWorkbook()

  for (i in 1:length(names(data.list))) {
    idx = names(data.list)[i]
    addWorksheet(wb, idx)
    rounded = data.frame(lapply(data.list[idx], function(x)
                                  {if(is.numeric(x)) round(x, digits) else x}))
    writeData(wb, sheet=i, rounded, rowNames=row.names)
  }

  saveWorkbook(wb, filepath)
}

Body:
The problem is coming from where you are creating the rounded object. You need to use a [[ instead of [ to get the list current list element. Changing the the rounded = line to the following should correct this.

rounded = data.frame(lapply(data.list[[idx]], function(x)


问:
chart.js-plugin-annotations multiple horizontal lines in one chart
I am using chart.js 2.6 and chart.js-plugin-annotations 0.5.5 to create a graph.

I need to add 3 horizontal lines using annotations on the same graph but only the last one in the list is drawn. If I switch the placement of the annotations the last one is still drawn so the code for each annotation seems to works, but only the last one shows.

```<code> annotation: {
   drawTime: 'afterDatasetsDraw',
     annotations: [{
                        id: 'hline1',
                        type: 'line',
                        mode: 'horizontal',
                        scaleID: 'y-axis-0',
                        value: speedAverage,
                        borderColor: 'green',
                        borderWidth: 1
                    }],
                    annotations: [{
                        id: 'hline3',
                        type: 'line',
                        mode: 'horizontal',
                        scaleID: 'y-axis-0',
                        value: speedToleranceMin,
                        borderColor: 'red',
                        borderWidth: 1,
                        label: {
                            backgroundColor: "red",
                            content: "Min Value",
                            enabled: true
                        }
                    }],
                    annotations: [{
                        id: 'hline2',
                        type: 'line',
                        mode: 'horizontal',
                        scaleID: 'y-axis-0',
                        value: speedToleranceMax,
                        borderColor: 'red',
                        borderWidth: 1,
                        label: {
                            backgroundColor: "red",
                            content: "Max Value",
                            enabled: true
                        }
            }]
   }
</code>```

whats wrong here?
Expected result is to see all 3 lines not just 1 of them.

答:
You are using the plugin incorrectly. Correct way should be ...</p>

```<code>annotation: {
   drawTime: 'afterDatasetsDraw',
   annotations: [{
      id: 'hline1',
      type: 'line',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: speedAverage,
      borderColor: 'green',
      borderWidth: 1
   }, {
      id: 'hline3',
      type: 'line',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: speedToleranceMin,
      borderColor: 'red',
      borderWidth: 1,
      label: {
         backgroundColor: "red",
         content: "Min Value",
         enabled: true
      }
   }, {
      id: 'hline2',
      type: 'line',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: speedToleranceMax,
      borderColor: 'red',
      borderWidth: 1,
      label: {
         backgroundColor: "red",
         content: "Max Value",
         enabled: true
      }
   }]
}
</code>```

Body:
I am using chart.js 2.6 and chart.js-plugin-annotations 0.5.5 to create a graph.

I need to add 3 horizontal lines using annotations on the same graph but only the last one in the list is drawn. If I switch the placement of the annotations the last one is still drawn so the code for each annotation seems to works, but only the last one shows.

 annotation: {
   drawTime: 'afterDatasetsDraw',
     annotations: [{
                        id: 'hline1',
                        type: 'line',
                        mode: 'horizontal',
                        scaleID: 'y-axis-0',
                        value: speedAverage,
                        borderColor: 'green',
                        borderWidth: 1
                    }],
                    annotations: [{
                        id: 'hline3',
                        type: 'line',
                        mode: 'horizontal',
                        scaleID: 'y-axis-0',
                        value: speedToleranceMin,
                        borderColor: 'red',
                        borderWidth: 1,
                        label: {
                            backgroundColor: "red",
                            content: "Min Value",
                            enabled: true
                        }
                    }],
                    annotations: [{
                        id: 'hline2',
                        type: 'line',
                        mode: 'horizontal',
                        scaleID: 'y-axis-0',
                        value: speedToleranceMax,
                        borderColor: 'red',
                        borderWidth: 1,
                        label: {
                            backgroundColor: "red",
                            content: "Max Value",
                            enabled: true
                        }
            }]
   }

whats wrong here?
Expected result is to see all 3 lines not just 1 of them.

Body:
You are using the plugin incorrectly. Correct way should be ...

annotation: {
   drawTime: 'afterDatasetsDraw',
   annotations: [{
      id: 'hline1',
      type: 'line',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: speedAverage,
      borderColor: 'green',
      borderWidth: 1
   }, {
      id: 'hline3',
      type: 'line',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: speedToleranceMin,
      borderColor: 'red',
      borderWidth: 1,
      label: {
         backgroundColor: "red",
         content: "Min Value",
         enabled: true
      }
   }, {
      id: 'hline2',
      type: 'line',
      mode: 'horizontal',
      scaleID: 'y-axis-0',
      value: speedToleranceMax,
      borderColor: 'red',
      borderWidth: 1,
      label: {
         backgroundColor: "red",
         content: "Max Value",
         enabled: true
      }
   }]
}


问:
Swap using a pointer without referring the array C++
so i need to swap row 2 and row 3 of my array. There is a catch our professor had us use a one dimensional array and use a pointer instead of a 2d array. We cannot reference the array only the pointer. I have no idea how to do this.

```<code>int numbers[25] = { 1,3,5,7,9 , -2,-4,-6, -8, -10 , 3,3,3,3,3 , 55, 77, 99, 22, 33, -15, -250, -350, -450, -550 };
</code>```

this array is supposed to look like this:

```<code> 1     3     5     7     9
   -2    -4    -6    -8   -10   // i need to swap this row
    3     3     3     3     3   // for this row
   55    77    99    22    33
  -15  -250  -350  -450  -550

This is how i need to print it
  1     3     5     7     9
  3     3     3     3     3
 -2    -4    -6    -8   -10
   55    77    99    22    33
  -15  -250  -350  -450  -550
</code>```

Note: this is not my whole HW assignment is just where i am stuck.

答:
Just define a temporary array:

```<code>int tmp_row[5];
</code>```

Save the third row:

```<code>int bytes = sizeof(tmp_row);

memcpy(tmp_row, &numbers[10], bytes);
</code>```

Then fill in the second and third rows appropriately:

```<code>memcpy(&numbers[10], &numbers[5], bytes);
memcpy(&numbers[5], tmp_row, bytes);
</code>```

Body:
so i need to swap row 2 and row 3 of my array. There is a catch our professor had us use a one dimensional array and use a pointer instead of a 2d array. We cannot reference the array only the pointer. I have no idea how to do this.

int numbers[25] = { 1,3,5,7,9 , -2,-4,-6, -8, -10 , 3,3,3,3,3 , 55, 77, 99, 22, 33, -15, -250, -350, -450, -550 };

this array is supposed to look like this:

 1     3     5     7     9
   -2    -4    -6    -8   -10   // i need to swap this row
    3     3     3     3     3   // for this row
   55    77    99    22    33
  -15  -250  -350  -450  -550

This is how i need to print it
  1     3     5     7     9
  3     3     3     3     3
 -2    -4    -6    -8   -10
   55    77    99    22    33
  -15  -250  -350  -450  -550

Note: this is not my whole HW assignment is just where i am stuck.

Body:
Just define a temporary array:

int tmp_row[5];

Save the third row:

int bytes = sizeof(tmp_row);

memcpy(tmp_row, &numbers[10], bytes);

Then fill in the second and third rows appropriately:

memcpy(&numbers[10], &numbers[5], bytes);
memcpy(&numbers[5], tmp_row, bytes);