问:
Converting Curl command to PHP not working
I have curl command working through terminal and when I converts that command in PHP, it is giving me an error.

Here is Curl command from terminal:

```<code>[root@localhost ~]# curl -XPOST -v http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive
* About to connect() to localhost port 5636 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#0)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:5636
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Evebox-Git-Revision: 8ef8639
< X-Evebox-Session-Id: IUi21/bP7TkbJ11jpYcihe1w/S41vyAbP1L1qBIJKJiL8E3440J3imOSGxKYO9j5ffqAPyv2Q3tCXqUQxhIqnw
< Date: Wed, 05 Jul 2017 06:34:31 GMT
< Content-Length: 14
<
* Connection #0 to host localhost left intact
{"status":200}[root@localhost ~]#
</code>```

Here is the curl command in PHP:

```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
  echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
</code>```

This is response: 400 Bad Request

Here is the Verbose Output:

```<code>Verbose information:
</code>```

```* About to connect() to localhost port 5636 (#6)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#6)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
Host: localhost:5636
Accept: */*
Content-Length: -1
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

< HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
< Connection: close
<
* Closing connection 6
```

400 Bad Request

答:
Using the Requests library you could convert that cURL query as</p>

```<code>include('vendor/rmccue/requests/library/Requests.php');
Requests::register_autoloader();
$headers = array();
$response = Requests::post('http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive', $headers);
</code>```

Body:
I have curl command working through terminal and when I converts that command in PHP, it is giving me an error.

Here is Curl command from terminal:

[root@localhost ~]# curl -XPOST -v http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive
* About to connect() to localhost port 5636 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#0)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:5636
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Evebox-Git-Revision: 8ef8639
< X-Evebox-Session-Id: IUi21/bP7TkbJ11jpYcihe1w/S41vyAbP1L1qBIJKJiL8E3440J3imOSGxKYO9j5ffqAPyv2Q3tCXqUQxhIqnw
< Date: Wed, 05 Jul 2017 06:34:31 GMT
< Content-Length: 14
<
* Connection #0 to host localhost left intact
{"status":200}[root@localhost ~]#

Here is the curl command in PHP:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
  echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

This is response: 400 Bad Request

Here is the Verbose Output:

Verbose information:

* About to connect() to localhost port 5636 (#6)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#6)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
Host: localhost:5636
Accept: */*
Content-Length: -1
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

< HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
< Connection: close
<
* Closing connection 6

400 Bad Request

Body:
Using the Requests library you could convert that cURL query as

include('vendor/rmccue/requests/library/Requests.php');
Requests::register_autoloader();
$headers = array();
$response = Requests::post('http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive', $headers);


来源: stackexchange

问:
Python: Finding Longest/Shortest Words In a List and Calling Them in a Function
I have a list of words:
        words=["alpha","omega","up","down","over","under","purple","red","blue","green"]
I have two functions that are supposed to find the shortest and longest words in this list:

```<code>def bigWords(list=[], *args):
    largestWord=""
    largestLen=0
    for word in list:
        if largestWord<len(word):
            largestWord=len(word)
            largestWord=word
    print "The longest word(s) in the list is %s." % largestWord

def smallWords(list=[], *args):
    smallestWord=""
    smallestLen=0
    for word in list:
        if smallestLen>len(word):
            smallestLen>len(word)
            smallestWord=word
    print "The shortest word(s) in the list is: %s." % (smallestWord)
</code>```

I have these functions nested so I can call them all at once:

```<code>def callFunctions():
###Words###
    words=["alpha","omega","up","down","over","under","purple","red","blue","green"]

    wordLength=lenList(words)
    print "The amount of words[] is %d" % wordLength
    func_list2 = [bigWords, smallWords]
    for f in func_list2:
        map(f, words)

callFunctions()
</code>```

This is just returning this without inputing the words in the list:

```<code>The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
</code>```

Not sure why, any help is appreciated.

答:
Just use max and min functions having key as the length</p>
```<code>y = []
for names in range(4):
   name = raw_input('Enter:')
   y += name,
s = max(y, key=len)
r = min(y, key=len)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list of words:
        words=["alpha","omega","up","down","over","under","purple","red","blue","green"]
I have two functions that are supposed to find the shortest and longest words in this list:

def bigWords(list=[], *args):
    largestWord=""
    largestLen=0
    for word in list:
        if largestWord<len(word):
            largestWord=len(word)
            largestWord=word
    print "The longest word(s) in the list is %s." % largestWord

def smallWords(list=[], *args):
    smallestWord=""
    smallestLen=0
    for word in list:
        if smallestLen>len(word):
            smallestLen>len(word)
            smallestWord=word
    print "The shortest word(s) in the list is: %s." % (smallestWord)

I have these functions nested so I can call them all at once:

def callFunctions():
###Words###
    words=["alpha","omega","up","down","over","under","purple","red","blue","green"]

    wordLength=lenList(words)
    print "The amount of words[] is %d" % wordLength
    func_list2 = [bigWords, smallWords]
    for f in func_list2:
        map(f, words)

callFunctions()

This is just returning this without inputing the words in the list:

The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .

Not sure why, any help is appreciated.

Body:
Just use max and min functions having key as the length

y = []
for names in range(4):
   name = raw_input('Enter:')
   y += name,
s = max(y, key=len)
r = min(y, key=len)

ContentLicense: CC BY-SA 4.0


问:
Make a whole div clickable in order to launch a _blank document
How can I write the _blank statement in this location.href call?

```<code>  <div onclick="location.href='http://www.test.com';" style="display:block; height:40px; width:100px; cursor:pointer;"></div>
</code>```

Please note: I need to keep the div and treat it as a href container.

When someone clicks it should open a new browser window, not a popup box.

答:
use an  instead of a

```<code><a href="http://www.example.com" target="_blank" style="display:block; width:100px; height:40px;">CONTENT</a>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How can I write the _blank statement in this location.href call?

Please note: I need to keep the div and treat it as a href container.

When someone clicks it should open a new browser window, not a popup box.

Body:
use an <a> instead of a <div>

<a href="http://www.example.com" target="_blank" style="display:block; width:100px; height:40px;">CONTENT</a>


问:
iOS screenshot live camera preview
I have live camera in my app (in scrollView) and for transition I need to take screenshot of camera preview and get that image, but

```<code> drawHierarchy(in rect: CGRect,afterScreenUpdates afterUpdates: Bool)
</code>```

method doesn't help. Is there a way to achieve this without OpenGL. Please help, cause it's already several days I am searching the solution.

```<code> UIGraphicsBeginImageContextWithOptions((self.getRectOfSceneInScrollView(index: self.selectedSceneIndex!).size), false, 0);
self.scrollView.drawHierarchy(in: CGRect.init(--some rect--), afterScreenUpdates: true)

let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;

UIGraphicsEndImageContext()
</code>```

UPDATE:
self.scrollView.layer.render(in: UIGraphicsGetCurrentContext()!) doesn't help too

答:
Apple has some restrictions on capturing the AVCaptureVideoPreviewLayer from our custom camera view by using UIGraphicsGetImageFromCurrentImageContext. Even UIView Snapchat method will not work if we have camera view.

But we do have a workaround to get the effect. Get the image buffer for each camera frame and convert it to UIImage. Add the image to our screenshot manually. It's not that simple and AFAIK this is the best workaround. More info can be found in SO Answer from Is it possible to render AVCaptureVideoPreviewLayer in a graphics context?

Title: iOS screenshot live camera preview

Body:
I have live camera in my app (in scrollView) and for transition I need to take screenshot of camera preview and get that image, but

 drawHierarchy(in rect: CGRect,afterScreenUpdates afterUpdates: Bool)

method doesn't help. Is there a way to achieve this without OpenGL. Please help, cause it's already several days I am searching the solution.

 UIGraphicsBeginImageContextWithOptions((self.getRectOfSceneInScrollView(index: self.selectedSceneIndex!).size), false, 0);
self.scrollView.drawHierarchy(in: CGRect.init(--some rect--), afterScreenUpdates: true)

let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!;

UIGraphicsEndImageContext()

UPDATE:
self.scrollView.layer.render(in: UIGraphicsGetCurrentContext()!) doesn't help too


问:
Fetching all rows of dataframe using Python pandas
I ran a python code and got dataframe output like:

```<code>1    Department of Susta... (2)       Community Services (2)
2    Department of Commu... (2)       Community Services (2)
3    Sustainability Vict... (1)       Community Services (1)
4    Southern Grampians ... (1)       Community Services (1)
5    Productivity Commis... (1)       Community Services (1)
6         Parliament of NSW (1)       Community Services (1)
..                           ...                          ...
30      Noosa Shire Council (2)     Sport and Recreation (2)
31   State Library of Qu... (1)     Sport and Recreation (1)
32   Emergency Services ... (1)     Sport and Recreation (1)
33   Department of Susta... (1)     Sport and Recreation (1)
</code>```

now i don't have rows b/w 7 to 29. How to fetch all rows?

答:
It is only display problem, I prefer:

```<code>#temporaly display 999 rows
with pd.option_context('display.max_rows', 999):
    print (df)
</code>```

Option values are restored automatically when you exit the with block.

Body:
I ran a python code and got dataframe output like:

1    Department of Susta... (2)       Community Services (2)
2    Department of Commu... (2)       Community Services (2)
3    Sustainability Vict... (1)       Community Services (1)
4    Southern Grampians ... (1)       Community Services (1)
5    Productivity Commis... (1)       Community Services (1)
6         Parliament of NSW (1)       Community Services (1)
..                           ...                          ...
30      Noosa Shire Council (2)     Sport and Recreation (2)
31   State Library of Qu... (1)     Sport and Recreation (1)
32   Emergency Services ... (1)     Sport and Recreation (1)
33   Department of Susta... (1)     Sport and Recreation (1)

now i don't have rows b/w 7 to 29. How to fetch all rows?

Body:
It is only display problem, I prefer:

#temporaly display 999 rows
with pd.option_context('display.max_rows', 999):
    print (df)

Option values are restored automatically when you exit the with block.


问:
Form control not revalidating
I use 2 Buttons to get a list of popular places and hotels from a webservice and display in a multilist.

Button 1 for popular places

Button 2 for hotels

When I click on Button 1 it displayed all the requested list but when I go back to click Button 2 it return the list of hotels join with the list of popular places that was displayed earlier.

I want when I click on Button 1 it should return the list of popular places and when I go back to click Button 2 it should return ONLY the list of hotels.
I tried to revalidate the form but no luck.
Here is my code:

```<code>protected void beforeFormA(Form f) {
        Button bn = new Button("Exit");
        Container c = new Container(new BoxLayout(BoxLayout.Y_AXIS));
        switch (i) {
            case 1://for Button 1
                Style s = UIManager.getInstance().getComponentStyle("Button");
                FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
                EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 4), false);
                f.setTitle("Tourist Attractions");
                getattractive();
                ArrayList arr = (ArrayList) response.get("results");
                for (Object m : arr) {
                    Map ma = (Map) m;
                    address = (String) ma.get("formatted_address");
                    name = (String) ma.get("name");
                    icon = (String) ma.get("icon");
                    data.add(createListEntry(name, address, icon));
                }
                DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
                MultiList ml = new MultiList(model);
                ml.getUnselectedButton().setIconName("icon_URLImage");
                ml.getSelectedButton().setIconName("icon_URLImage");
                ml.getUnselectedButton().setIcon(placeholder);
                ml.getSelectedButton().setIcon(placeholder);
                findContainer(f).add(BorderLayout.CENTER, ml);
                c.addComponent(bn);
                bn.addActionListener((ActionEvent evt) -> {
                    System.exit(0);
                });
                findContainer(f).add(BorderLayout.SOUTH, c);
                f.getComponentForm().revalidate();
                break;

            case 2://for Button 2
                Style s1 = UIManager.getInstance().getComponentStyle("Button");
                FontImage p1 = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s1);
                EncodedImage placeholder1 = EncodedImage.createFromImage(p1.scaled(p1.getWidth() * 3, p1.getHeight() * 4), false);

                f.setTitle("Hotels");
                gethotels();
                ArrayList arr1 = (ArrayList) response.get("results");
                for (Object m : arr1) {
                    Map ma = (Map) m;
                    address = (String) ma.get("formatted_address");
                    name = (String) ma.get("name");
                    icon = (String) ma.get("icon");
                    data.add(createListEntry(name, address, icon));
                }
                DefaultListModel<Map<String, Object>> model1 = new DefaultListModel<>(data);
                MultiList ml1 = new MultiList(model1);
                ml1.getUnselectedButton().setIconName("icon_URLImage");
                ml1.getSelectedButton().setIconName("icon_URLImage");
                ml1.getUnselectedButton().setIcon(placeholder1);
                ml1.getSelectedButton().setIcon(placeholder1);
                findContainer1(f).add(BorderLayout.CENTER, ml1);
                c.addComponent(bn);
                bn.addActionListener((ActionEvent evt) -> {
                    System.exit(0);
                });
                findContainer1(f).add(BorderLayout.SOUTH, c);
                f.getComponentForm().revalidate();
                break;
        }
    }
</code>```

答:
It seems that you never clean your data list ... So previous items (added with   data.add(createListEntry(name, address, icon)); remain.

You should clear at the begining of each case with :

```<code>data.clear();
</code>```

Title: Form control not revalidating

Body:
I use 2 Buttons to get a list of popular places and hotels from a webservice and display in a multilist.

Button 1 for popular places

Button 2 for hotels

When I click on Button 1 it displayed all the requested list but when I go back to click Button 2 it return the list of hotels join with the list of popular places that was displayed earlier.

I want when I click on Button 1 it should return the list of popular places and when I go back to click Button 2 it should return ONLY the list of hotels.
I tried to revalidate the form but no luck.
Here is my code:

protected void beforeFormA(Form f) {
        Button bn = new Button("Exit");
        Container c = new Container(new BoxLayout(BoxLayout.Y_AXIS));
        switch (i) {
            case 1://for Button 1
                Style s = UIManager.getInstance().getComponentStyle("Button");
                FontImage p = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s);
                EncodedImage placeholder = EncodedImage.createFromImage(p.scaled(p.getWidth() * 3, p.getHeight() * 4), false);
                f.setTitle("Tourist Attractions");
                getattractive();
                ArrayList arr = (ArrayList) response.get("results");
                for (Object m : arr) {
                    Map ma = (Map) m;
                    address = (String) ma.get("formatted_address");
                    name = (String) ma.get("name");
                    icon = (String) ma.get("icon");
                    data.add(createListEntry(name, address, icon));
                }
                DefaultListModel<Map<String, Object>> model = new DefaultListModel<>(data);
                MultiList ml = new MultiList(model);
                ml.getUnselectedButton().setIconName("icon_URLImage");
                ml.getSelectedButton().setIconName("icon_URLImage");
                ml.getUnselectedButton().setIcon(placeholder);
                ml.getSelectedButton().setIcon(placeholder);
                findContainer(f).add(BorderLayout.CENTER, ml);
                c.addComponent(bn);
                bn.addActionListener((ActionEvent evt) -> {
                    System.exit(0);
                });
                findContainer(f).add(BorderLayout.SOUTH, c);
                f.getComponentForm().revalidate();
                break;

            case 2://for Button 2
                Style s1 = UIManager.getInstance().getComponentStyle("Button");
                FontImage p1 = FontImage.createMaterial(FontImage.MATERIAL_PORTRAIT, s1);
                EncodedImage placeholder1 = EncodedImage.createFromImage(p1.scaled(p1.getWidth() * 3, p1.getHeight() * 4), false);

                f.setTitle("Hotels");
                gethotels();
                ArrayList arr1 = (ArrayList) response.get("results");
                for (Object m : arr1) {
                    Map ma = (Map) m;
                    address = (String) ma.get("formatted_address");
                    name = (String) ma.get("name");
                    icon = (String) ma.get("icon");
                    data.add(createListEntry(name, address, icon));
                }
                DefaultListModel<Map<String, Object>> model1 = new DefaultListModel<>(data);
                MultiList ml1 = new MultiList(model1);
                ml1.getUnselectedButton().setIconName("icon_URLImage");
                ml1.getSelectedButton().setIconName("icon_URLImage");
                ml1.getUnselectedButton().setIcon(placeholder1);
                ml1.getSelectedButton().setIcon(placeholder1);
                findContainer1(f).add(BorderLayout.CENTER, ml1);
                c.addComponent(bn);
                bn.addActionListener((ActionEvent evt) -> {
                    System.exit(0);
                });
                findContainer1(f).add(BorderLayout.SOUTH, c);
                f.getComponentForm().revalidate();
                break;
        }
    }

Body:
It seems that you never clean your data list ... So previous items (added with   data.add(createListEntry(name, address, icon)); remain.

You should clear at the begining of each case with :

data.clear();


问:
Why do we use functionName: function in javascript return statement
I am completely new to javascript. I saw the below snippet in a tutorial. But i am not sure why do we use funtionName: function  in return statement.

For example, getID:function()  and setID: function() in the below code. Can anybody explain.

```<code>function celebrityID () {
    var celebrityID = 999;

    return {
        getID: function ()  {

          return celebrityID;
        },
        setID: function (theNewID)  {

            celebrityID = theNewID;
        }
    }

}
</code>```

答:
in your celebrityID () function you are returning an object, which has two properties those properties are function.

you can call

```<code>var myVar = new celebrityID();

myVar.getID(); // myVar = 999
</code>```

this like object creation from a class

Body:
I am completely new to javascript. I saw the below snippet in a tutorial. But i am not sure why do we use funtionName: function  in return statement.

For example, getID:function()  and setID: function() in the below code. Can anybody explain.

function celebrityID () {
    var celebrityID = 999;

    return {
        getID: function ()  {

          return celebrityID;
        },
        setID: function (theNewID)  {

            celebrityID = theNewID;
        }
    }

}

Body:
in your celebrityID () function you are returning an object, which has two properties those properties are function.

you can call

var myVar = new celebrityID();

myVar.getID(); // myVar = 999

this like object creation from a class


问:
preg_replace: wildcards do not match umlaut-characters
i want to filter a String by using the \w wildcard, but unfortunately it does not cover umlauts.

```<code>$i = "Die Höhe";
$x = preg_replace("/[^\w\s]/","",$i);
echo $x; // "Die Hhe";
</code>```

However, i can add all the characters to preg_replace, but this is not very elegant, since the list will become very long. ATM, i am preparing this only for German, but there are more languages to come.

```<code>$i = "Die Höhe";
$x = preg_replace("/[^\w\säöüÄÖÜß]/","",$i);
echo $x; // "Die Höhe";
</code>```

Is there a way to match all of them at once?

答:
this should remove all, in my opinion, non meaningful chars:</p>

```<code>$val = "Die Höhe";
$val = preg_replace('/[^\x20-\x7e\xa1-\xff]+/u', '', $val);
echo $val; // "Die Höhe"
</code>```

Body:
i want to filter a String by using the \w wildcard, but unfortunately it does not cover umlauts.

$i = "Die Höhe";
$x = preg_replace("/[^\w\s]/","",$i);
echo $x; // "Die Hhe";

However, i can add all the characters to preg_replace, but this is not very elegant, since the list will become very long. ATM, i am preparing this only for German, but there are more languages to come.

$i = "Die Höhe";
$x = preg_replace("/[^\w\säöüÄÖÜß]/","",$i);
echo $x; // "Die Höhe";

Is there a way to match all of them at once?

Body:
this should remove all, in my opinion, non meaningful chars:

$val = "Die Höhe";
$val = preg_replace('/[^\x20-\x7e\xa1-\xff]+/u', '', $val);
echo $val; // "Die Höhe"


问:
Update two ID's at once SQL - PHP
I have a table that's PK is an int field.
My problem is I need to swap two of the values round.

This is my current code:

```<code>$newId = (int)$id; $newId = $newId - 1;

$result = mysql_query("UPDATE homeScroller SET id = '$newId' WHERE id = '$id'") or die('error '.mysql_error());
$result2 = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'") or die('error '.mysql_error());
</code>```

The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.

答:
Do not use PK for this need.

If you can add timestamp field (shown_at) to this table, do it!
if cant, so update all PKs imultaneously. Just increment them.
For example: suppose we have such strings:

```<code>  1 photo1
  3 myphoto
  5 somephoto

  than use modulo 3.
  1%3 = 1
  3%3 = 0
  5%3 = 2

  increment all records

  2 photo1
  4 myphoto
  5 somephoto

  2%3 = 2
  4%3 = 1
  6%3 = 0
</code>```

So u can use modulo and increment ids

Title: Update two ID's at once SQL - PHP

Body:
I have a table that's PK is an int field.
My problem is I need to swap two of the values round.

This is my current code:

$newId = (int)$id; $newId = $newId - 1;

$result = mysql_query("UPDATE homeScroller SET id = '$newId' WHERE id = '$id'") or die('error '.mysql_error());
$result2 = mysql_query("UPDATE homeScroller SET id = '$id ' WHERE id = '$newId'") or die('error '.mysql_error());

The table contains at max 3 rows that contain info for an slideshow on the frontpage of the website. The frontpage orders them by their IDs. So to change the order I need to edit the ID's.

Body:
Do not use PK for this need.

If you can add timestamp field (shown_at) to this table, do it!
if cant, so update all PKs imultaneously. Just increment them.
For example: suppose we have such strings:

  1 photo1
  3 myphoto
  5 somephoto

  than use modulo 3.
  1%3 = 1
  3%3 = 0
  5%3 = 2

  increment all records

  2 photo1
  4 myphoto
  5 somephoto

  2%3 = 2
  4%3 = 1
  6%3 = 0

So u can use modulo and increment ids


问:
How to set different background color of every three html table rows in alternate
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr bgcolor="#dddddd">
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table></code>```

Any help is appreciated]1

答:
You want the alternative color for every three group of rows. Let explain the formula of css tr:nth-child(6n+1),
tr:nth-child(6n+2),
tr:nth-child(6n+3) where n=0,1,2,3......this tr selection will start from 1-3, 7-9....

Likewise tr:nth-child(6n+4),
tr:nth-child(6n+5),
tr:nth-child(6n+6) where n=0,1,2,3......this tr selection will start from 4-6, 10-12....

tr:nth-child(6n+1),
tr:nth-child(6n+2),
tr:nth-child(6n+3) {
  background: blue;
}

tr:nth-child(6n+4),
tr:nth-child(6n+5),
tr:nth-child(6n+6) {
  background: green;
}

table {
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table></code>```

 now you will get alternative color of blue and green as your requirement

Body:
Suppose I have two HTML tables named table1 and table2. If I want to have different background of every alternative three rows of table2, how can I achieve that using CSS? For example set background of first 3 rows as blue, then another 3 rows as green, again another 3 rows as blue, again another 3 rows as green and so on. Basically I want two different background colors for every three rows in alternate. I found CSS styling for even and odd rows, or every nth rows, but not for this case. I have attached the screenshot of sample table. Rather than hard coding in individual row like in this code, I want to do it in CSS styling.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 1px;
}

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    Island Trading
    Helen Bennett
    UK

    Laughing Bacchus Winecellars
    Yoshi Tannamuri
    Canada

    Magazzini Alimentari Riuniti
    Giovanni Rovelli
    Italy

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico

    Ernst Handel
    Roland Mendel
    Austria

    a
    b
    c

    a
    b
    c

    a
    b
    c

Any help is appreciated]1

Body:
You want the alternative color for every three group of rows. Let explain the formula of css tr:nth-child(6n+1),
tr:nth-child(6n+2),
tr:nth-child(6n+3) where n=0,1,2,3......this tr selection will start from 1-3, 7-9....

Likewise tr:nth-child(6n+4),
tr:nth-child(6n+5),
tr:nth-child(6n+6) where n=0,1,2,3......this tr selection will start from 4-6, 10-12....

tr:nth-child(6n+1),
tr:nth-child(6n+2),
tr:nth-child(6n+3) {
  background: blue;
}

tr:nth-child(6n+4),
tr:nth-child(6n+5),
tr:nth-child(6n+6) {
  background: green;
}

table {
  color: #fff;
}

<table id="table2">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
  </tr>
</table>

 now you will get alternative color of blue and green as your requirement


问:
How to share file for anyone Google Drive API using PHP
I have been trying over and over, but could not reach any result.
the code is generating permission id and I don't know what that means.

Please do help if anyone succeeded in this before, I just want to share file publicly using the google drive api v2.0

```<code>$fileId = '18mWN0UWX_z-4A1gag85ou0Im-wvKfMZU-tibdVd8nxY';
$userPermission = new Google_Service_Drive_Permission(array(
    'type' => 'anyone',
    'role' => 'reader',
    'emailAddress' => 'user@example.com'
  ));

  $request = $service->permissions->create(
    $fileId, $userPermission, array('fields' => 'id'));
  $batch->add($request, 'user');
  $domainPermission = new Google_Service_Drive_Permission(array(
    'type' => 'domain',
    'role' => 'reader',
    'domain' => 'example.com'
  ));

  $request = $service->permissions->create(
    $fileId, $domainPermission, array('fields' => 'id'));
  $batch->add($request, 'domain');
  $results = $batch->execute();

  foreach ($results as $result) {
    if ($result instanceof Google_Service_Exception) {
      // Handle error
      printf($result);
    } else {
      printf("Permission ID: %s\n", $result->id);
    }
  }
} finally {
  $service->getClient()->setUseBatch(false);
}
</code>```

答:
Here is my code snippet which was 2 years old.

```<code>$uplodedOriginalFile = new Google_Service_Drive_DriveFile();
$originallinkdata = file_get_contents($downloadlink['originallink']);
$uploadedfile = $service->files->insert($uplodedOriginalFile, array(
              'data' => $originallinkdata,
              'uploadType' => 'multipart',
            ));

$newPermission = new Google_Service_Drive_Permission();
//$newPermission->setValue($value);
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try
{
    $service->permissions->insert($uploadedfile['id'], $newPermission);
}
catch (Exception $e)
{
    print "An error occurred: " . $e->getMessage();
}

$publicOriginallink = "https://googledrive.com/host/".$uploadedfile['id'];
</code>```

So you just need the inserted file Id and keep the permssion for anyone as  reader and append the inserted file Id after "https://googledrive.com/host/ [newly inserted file id which is returned by google drive sdk]"

Body:
I have been trying over and over, but could not reach any result.
the code is generating permission id and I don't know what that means.

Please do help if anyone succeeded in this before, I just want to share file publicly using the google drive api v2.0

$fileId = '18mWN0UWX_z-4A1gag85ou0Im-wvKfMZU-tibdVd8nxY';
$userPermission = new Google_Service_Drive_Permission(array(
    'type' => 'anyone',
    'role' => 'reader',
    'emailAddress' => 'user@example.com'
  ));

  $request = $service->permissions->create(
    $fileId, $userPermission, array('fields' => 'id'));
  $batch->add($request, 'user');
  $domainPermission = new Google_Service_Drive_Permission(array(
    'type' => 'domain',
    'role' => 'reader',
    'domain' => 'example.com'
  ));

  $request = $service->permissions->create(
    $fileId, $domainPermission, array('fields' => 'id'));
  $batch->add($request, 'domain');
  $results = $batch->execute();

  foreach ($results as $result) {
    if ($result instanceof Google_Service_Exception) {
      // Handle error
      printf($result);
    } else {
      printf("Permission ID: %s\n", $result->id);
    }
  }
} finally {
  $service->getClient()->setUseBatch(false);
}

Body:
Here is my code snippet which was 2 years old.

$uplodedOriginalFile = new Google_Service_Drive_DriveFile();
$originallinkdata = file_get_contents($downloadlink['originallink']);
$uploadedfile = $service->files->insert($uplodedOriginalFile, array(
              'data' => $originallinkdata,
              'uploadType' => 'multipart',
            ));

$newPermission = new Google_Service_Drive_Permission();
//$newPermission->setValue($value);
$newPermission->setType('anyone');
$newPermission->setRole('reader');
try
{
    $service->permissions->insert($uploadedfile['id'], $newPermission);
}
catch (Exception $e)
{
    print "An error occurred: " . $e->getMessage();
}

$publicOriginallink = "https://googledrive.com/host/".$uploadedfile['id'];

So you just need the inserted file Id and keep the permssion for anyone as  reader and append the inserted file Id after "https://googledrive.com/host/ [newly inserted file id which is returned by google drive sdk]"


问:
Smooth expanding UIView animation in Swift
Aim:

How can I animate a UIView that I want to expand to fill the whole screen. The UIView needs to expand in smooth, even and balance way while it animates.

I have one red square positioned on screen, starts small then expands to fit the screen. (Image 1.)

```<code>let subview = UIView()
subview.backgroundColor = .red
subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
self.view.addSubview(subview)
</code>```

Question:

In Swift 2 and Swift 3, using an animateWithDuration, how do I
  animate the the red square UIView expanding in a balanced and even
  manner in all directions to fill the whole screen?

```<code>UIView.animateWithDuration(1.0, delay: 0, options: nil, animations: {

    ?????

}, completion: nil)
</code>```

Image 1:

答:
You can try this, I set the duration to 5 seconds but you got the idea.</p>

```<code>let viewWidth = view.frame.width
let viewHeight = view.frame.height
UIView.animate(withDuration: 5) {
    subview.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
}
</code>```

Body:
Aim:

How can I animate a UIView that I want to expand to fill the whole screen. The UIView needs to expand in smooth, even and balance way while it animates.

I have one red square positioned on screen, starts small then expands to fit the screen. (Image 1.)

let subview = UIView()
subview.backgroundColor = .red
subview.frame = CGRect(x: 60, y: 200, width: 50, height: 50)
self.view.addSubview(subview)

Question:

In Swift 2 and Swift 3, using an animateWithDuration, how do I
  animate the the red square UIView expanding in a balanced and even
  manner in all directions to fill the whole screen?

UIView.animateWithDuration(1.0, delay: 0, options: nil, animations: {

    ?????

}, completion: nil)

Image 1:

Body:
You can try this, I set the duration to 5 seconds but you got the idea.

let viewWidth = view.frame.width
let viewHeight = view.frame.height
UIView.animate(withDuration: 5) {
    subview.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
}


问:
PHP script not working as expected
My php script is woking outside function but not inside function.

```<code>$uid = $_SESSION['user_id'];
function getUserName($conn) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}
</code>```

Unable to get it where I am wrong.

答:
try this</p>

```<code>function getUserName($uid, $conn) {
 // code here
}
</code>```

Title: PHP script not working as expected

Body:
My php script is woking outside function but not inside function.

$uid = $_SESSION['user_id'];
function getUserName($conn) {
$sql = "SELECT * FROM `tbl_user` WHERE `user_id` ='".$uid."' ";
$row = $conn->query($sql)->fetch_array();
return $row["user_name"];
}

Unable to get it where I am wrong.

Body:
try this

function getUserName($uid, $conn) {
 // code here
}


问:
How to interrupt java.util.Scanner nextLine call
I am using a multi threaded environment were one Thread is constantly listening for user input by repeatedly calling scanner.nextLine().
To end the application, this runloop is stopped by another thread, but the listening thread won't stop until a last user input was made (due to the blocking nature of nextLine()).

Closing the stream seems not to be an option since I am reading from System.in, which returns an InputStream that is not closable.

Is there a way to interrupt the blocking of scanner, so that it will return?

thanks

答:
Sure. Use a nuke. Call System.exit(0) at the end of your main thread. This will murder everything. Even the active thread waiting in System.in.

The problem is that System.in is a traditional input stream with blocking, and when it's blocking the thread is marked as running. You cannot interrupt it. So whatever thread you are using to read the System.in is calling read and the read will block the thread. You can coax some of this stuff with a bunch of tricks avoid calling read except in those cases when we can be sure there will be no block and then constantly poll. But, there's no real way around the problem that any attempt to read that will lock your thread and no amount of closing underlying streams or interrupting or stopping the thread will save you. But, if you murder the entire vm... the thread will die.

Obviously you need to make sure the rest of the threads have properly exited and it's just that one stupid I want to be able to respond to typed input thread that is the last hanger-on. But, if that's totally the case the correct answer is to exit, or at least, basically the only answer that'll work without burning clock-cycles for no reason and let the program terminate.


问:
Java 8 method reference does not start thread?
Why does a method reference not start a thread in this example?

```<code>package example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ESMethodReference {
    int i1, i2, result = 0;

    ESMethodReference(int i1, int i2){
        this.i1 =i1;
        this.i2 = i2;
    }

    public Runnable calculate(){
        System.out.print("In calculate()");
        return new Runnable() {
            @Override
            public void run() {
                result += i1 + i2;
                System.out.print(" creating result");
            }
        };
    }

    public static void main(String[] args) throws InterruptedException{
        ESMethodReference es = new ESMethodReference(1, 1);

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 2; i++){
            executorService.submit(es.calculate());
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes.calculate() result incremented " + es.result );

            executorService.submit(es::calculate);
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes::calculate result NOT incremented " + es.result );
        }

        executorService.shutdown();
    }
}
</code>```

Output:

In calculate() creating result  es.calculate() result incremented 2

In calculate()  es::calculate result NOT incremented 2

In calculate() creating result  es.calculate() result incremented 4

In calculate()  es::calculate result NOT incremented 4

答:
```<code>executorService.submit(es::calculate);
</code>```

is equivalent to

```<code>executorService.submit(() -> es.calculate());
</code>```

which is not the same as

```<code>executorService.submit(es.calculate());
</code>```

The former asynchronously creates the Runnable (without executing it) while the latter asynchronously executes (a distinct instance of) the same Runnable.

As a side note, you should probably avoid naming your method “calculate” if it only creates the task without calculating anything. If it was named createTask() for example, it would make it more obvious that the following does not calculate anything:

```<code>executorService.submit(es::createTask)
</code>```

Or, if you made the method actually calculate the result:

```<code>public void calculate(){
    System.out.print("In calculate()");
    result += i1 + i2;
    System.out.print(" creating result");
}
</code>```

then the call with the method reference would work as you expected it.

Body:
Why does a method reference not start a thread in this example?

package example;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ESMethodReference {
    int i1, i2, result = 0;

    ESMethodReference(int i1, int i2){
        this.i1 =i1;
        this.i2 = i2;
    }

    public Runnable calculate(){
        System.out.print("In calculate()");
        return new Runnable() {
            @Override
            public void run() {
                result += i1 + i2;
                System.out.print(" creating result");
            }
        };
    }

    public static void main(String[] args) throws InterruptedException{
        ESMethodReference es = new ESMethodReference(1, 1);

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 2; i++){
            executorService.submit(es.calculate());
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes.calculate() result incremented " + es.result );

            executorService.submit(es::calculate);
            Thread.sleep(100);  // Allow new thread to run
            System.out.println("\tes::calculate result NOT incremented " + es.result );
        }

        executorService.shutdown();
    }
}

Output:

In calculate() creating result  es.calculate() result incremented 2

In calculate()  es::calculate result NOT incremented 2

In calculate() creating result  es.calculate() result incremented 4

In calculate()  es::calculate result NOT incremented 4

Body:
executorService.submit(es::calculate);

is equivalent to

executorService.submit(() -> es.calculate());

which is not the same as

executorService.submit(es.calculate());

The former asynchronously creates the Runnable (without executing it) while the latter asynchronously executes (a distinct instance of) the same Runnable.

As a side note, you should probably avoid naming your method “calculate” if it only creates the task without calculating anything. If it was named createTask() for example, it would make it more obvious that the following does not calculate anything:

executorService.submit(es::createTask)

Or, if you made the method actually calculate the result:

public void calculate(){
    System.out.print("In calculate()");
    result += i1 + i2;
    System.out.print(" creating result");
}

then the call with the method reference would work as you expected it.


问:
The controller with the name x is not registered
I can't figure out why i've this "controller is not registered" error in angular 1.6.4.

Controller:

```<code>var app = angular.module('app', ['ngRoute']);
app.controller("formCtrl", function($scope, $rootScope, $stateParams) {
  $scope.id = $stateParams.id;
});
</code>```

Index:

```<code><html>
  <head>
    <script src="js/angular.js"></script>
    <script src="js/angular-route.js"></script>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <script src="js/formCtrl.js" type="text/javascript"></script>
    <script src="js/app.js" type="text/javascript"></script>
  </head>
  <body ng-app="app">
    <div ng-view>
    </div>
  </body>
</html>
</code>```

App:

```<code>app = angular.module('app', ['ngRoute']);

app.config(function($routeProvider) {
  $routeProvider
  .when("/:id", {
    templateUrl: './partials/main.html',
    controller: 'formCtrl'
  });
})
</code>```

答:
try this :</p>

```<code>var app = angular.module('app', ['ngRoute']);
 app.controller("formCtrl",["$scope", "$rootScope", "$stateParams", function($scope, $rootScope, $stateParams) {
   $scope.id = $stateParams.id;
}]);
</code>```

Body:
I can't figure out why i've this "controller is not registered" error in angular 1.6.4.

Controller:

var app = angular.module('app', ['ngRoute']);
app.controller("formCtrl", function($scope, $rootScope, $stateParams) {
  $scope.id = $stateParams.id;
});

Index:

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

App:

app = angular.module('app', ['ngRoute']);

app.config(function($routeProvider) {
  $routeProvider
  .when("/:id", {
    templateUrl: './partials/main.html',
    controller: 'formCtrl'
  });
})

Body:
try this :

var app = angular.module('app', ['ngRoute']);
 app.controller("formCtrl",["$scope", "$rootScope", "$stateParams", function($scope, $rootScope, $stateParams) {
   $scope.id = $stateParams.id;
}]);


问:
How to ensure sequential primary key in oracle database using sequence table when doing inserts from multiple threads in a spring batch application
I have a data aggregation and loading application that loads data files to an oracle database. We are using spring integration for file poling and spring batch for loading data to the database. When more than one file is being processed (read and loaded to database ) primary key tends to skip some values.
Oracle sequence created is.

```<code>CREATE SEQUENCE  "SCHEMA"."SEQUENCE_TABLE_NAME"  MINVALUE 1 MAXVALUE
    9999999999999999999999999999 INCREMENT BY 1 START WITH 241488161 CACHE
    20 NOORDER  NOCYCLE ;
</code>```

An inbound-channel-adapter has a poller which has as task executor. the inbound channel adapter sends the file to a transformer which creates a JobLaunchRequest object that is launched by the job-launching-gateway.
The job has a reader and a jdbcwriter that executes the following statement.

```<code><bean id="itemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
    <property name="dataSource" ref="dataSource"/>
    <property name="sql">
        <value>
            <![CDATA[
            insert  into data_table (id,dataA,dataB)
            values(SEQUENCE_TABLE_NAME.nextval,:dataA,:dataB)
            ]]>
        </value>
    </property>
    <property name="itemSqlParameterSourceProvider">
        <bean
             class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
    </property>
</bean>
</code>```

The key reason for loading to database is that an api is exposed which depends on the primary key being ordered and sequential. but once two many files are present in the folder. due to multiple threads reading and writing to the db. the primary key provided by the sequence table is missing some values in between.

A similar case is explained here (oracle perspective alone).

答:
First exposing a primary key via an API is generally a bad practice.

But here is another aproach to it:

Let all threads create those rows in the original table and don't care about the primary key at all. Create a new table that has a foreign key reference on the original table and a second column for storing the sequential value. A single thread will continously pick rows from the original table and create the rows in the new table using a sequence. Then expose the sequential value of the new table as the key in your API.

Since only that thread is accessing the sequence there should be no gaps. If you are not expecting the highest loads imaginable that single thread should be able to handle the load of multiple other threads.

There will be a latency introduced until an item becomes visible to your API because there is now a second transaction involved.

Body:
I have a data aggregation and loading application that loads data files to an oracle database. We are using spring integration for file poling and spring batch for loading data to the database. When more than one file is being processed (read and loaded to database ) primary key tends to skip some values.
Oracle sequence created is.

CREATE SEQUENCE  "SCHEMA"."SEQUENCE_TABLE_NAME"  MINVALUE 1 MAXVALUE
    9999999999999999999999999999 INCREMENT BY 1 START WITH 241488161 CACHE
    20 NOORDER  NOCYCLE ;

An inbound-channel-adapter has a poller which has as task executor. the inbound channel adapter sends the file to a transformer which creates a JobLaunchRequest object that is launched by the job-launching-gateway.
The job has a reader and a jdbcwriter that executes the following statement.

<bean id="itemWriter" class="org.springframework.batch.item.database.JdbcBatchItemWriter">
    <property name="dataSource" ref="dataSource"/>
    <property name="sql">
        <value>
            <![CDATA[
            insert  into data_table (id,dataA,dataB)
            values(SEQUENCE_TABLE_NAME.nextval,:dataA,:dataB)
            ]]>
        </value>
    </property>
    <property name="itemSqlParameterSourceProvider">
        <bean
             class="org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
    </property>
</bean>

The key reason for loading to database is that an api is exposed which depends on the primary key being ordered and sequential. but once two many files are present in the folder. due to multiple threads reading and writing to the db. the primary key provided by the sequence table is missing some values in between.

A similar case is explained here (oracle perspective alone).


问:
Focus on First asp:textbox in each bootstrap tab when clicking tab link
i am new to development and started developing a simple asp.net application. I am using bootstrap tabs having some asp labels and textboxes in each. I want focus on first textbox in the tab content when click on that tab. I searched various answers but all are for input  fields(exp: input type="text"). can't find any for asp textbox. Any help will be appreciated.
Thanks</p>

答:
ASP.NET TextBoxes are HTML textboxes. By default, the ClientIDMode of controls are Predictable. This means the rendered HTML's id is auto-generated.

```<code>// ASP.NET TextBox
<asp:TextBox ID="TextBox1"/>

// Rendered HTML
<input type="text" id="ContentPlaceHolder1_TextBox1_1"/>
</code>```

What you can do is add ClientIDMode="Static" to the TextBox. This will make the rendered (HTML) id of the input the same as the ID you passed to the TextBox.

```<code>// ASP.NET TextBox
<asp:TextBox ID="TextBox1" ClientIDMode="Static"/>

// Rendered HTML
<input type="text" id="TextBox1"/>
</code>```

You can then target that via JavaScript using the answers you've searched for.

EDIT:

If you don't want to target the TextBoxes via id, you can probably just use CSS classes to tag them like:

```<code><asp:TextBox ID="TextBox1" CssClass="default-focus" />
</code>```

Then with jQuery:

```<code>$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  var target = event.target.attributes.href.value;
  var $textbox = $(target + ' .default-focus');

  $textbox.focus();
});
</code>```

Body:
ASP.NET TextBoxes are HTML textboxes. By default, the ClientIDMode of controls are Predictable. This means the rendered HTML's id is auto-generated.

// ASP.NET TextBox
<asp:TextBox ID="TextBox1"/>

// Rendered HTML
<input type="text" id="ContentPlaceHolder1_TextBox1_1"/>

What you can do is add ClientIDMode="Static" to the TextBox. This will make the rendered (HTML) id of the input the same as the ID you passed to the TextBox.

// ASP.NET TextBox
<asp:TextBox ID="TextBox1" ClientIDMode="Static"/>

// Rendered HTML
<input type="text" id="TextBox1"/>

You can then target that via JavaScript using the answers you've searched for.

EDIT:

If you don't want to target the TextBoxes via id, you can probably just use CSS classes to tag them like:

<asp:TextBox ID="TextBox1" CssClass="default-focus" />

Then with jQuery:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  var target = event.target.attributes.href.value;
  var $textbox = $(target + ' .default-focus');

  $textbox.focus();
});


问:
How does the getChar function work?
```<code>private static char[] getChars(int i) {
    char buf[] = new char[32];
    int q;
    for (int j = 31; j >= 0; j--) {
         q = (i * 52429) >>> (19);
         int r = i - ((q << 3) + (q << 1));
         buf[j] = (char) (r + '0');
         i = q;
         if (i == 0)
             break;
    }

 return buf;
}
</code>```

The above code is based on a part of java.lang.Integer.getChars(int). How did the developers come up with this "magic" number 52429. What is the math behind it? After 81920 as input this function doesn't work. does this magic number only work for a certain range of inputs, if so why?

答:
If you search the source code, you'll find a second instance of that number:

// I use the "invariant division by multiplication" trick to
// accelerate Integer.toString.  In particular we want to
// avoid division by 10.
//
// The "trick" has roughly the same performance characteristics
// as the "classic" Integer.toString code on a non-JIT VM.
// The trick avoids .rem and .div calls but has a longer code
// path and is thus dominated by dispatch overhead.  In the
// JIT case the dispatch overhead doesn't exist and the
// "trick" is considerably faster than the classic code.
//
// TODO-FIXME: convert (x * 52429) into the equiv shift-add
// sequence.
//
// RE:  Division by Invariant Integers using Multiplication
//      T Gralund, P Montgomery
//      ACM PLDI 1994
//
```

So, the answer to your question can be found in the book Division by Invariant Integers using Multiplication by T Gralund, P Montgomery.

Title: How does the getChar function work?

Body:
private static char[] getChars(int i) {
    char buf[] = new char[32];
    int q;
    for (int j = 31; j >= 0; j--) {
         q = (i * 52429) >>> (19);
         int r = i - ((q << 3) + (q << 1));
         buf[j] = (char) (r + '0');
         i = q;
         if (i == 0)
             break;
    }

 return buf;
}

The above code is based on a part of java.lang.Integer.getChars(int). How did the developers come up with this "magic" number 52429. What is the math behind it? After 81920 as input this function doesn't work. does this magic number only work for a certain range of inputs, if so why?

Body:
If you search the source code, you'll find a second instance of that number:

// I use the "invariant division by multiplication" trick to
// accelerate Integer.toString.  In particular we want to
// avoid division by 10.
//
// The "trick" has roughly the same performance characteristics
// as the "classic" Integer.toString code on a non-JIT VM.
// The trick avoids .rem and .div calls but has a longer code
// path and is thus dominated by dispatch overhead.  In the
// JIT case the dispatch overhead doesn't exist and the
// "trick" is considerably faster than the classic code.
//
// TODO-FIXME: convert (x * 52429) into the equiv shift-add
// sequence.
//
// RE:  Division by Invariant Integers using Multiplication
//      T Gralund, P Montgomery
//      ACM PLDI 1994
//

So, the answer to your question can be found in the book Division by Invariant Integers using Multiplication by T Gralund, P Montgomery.


问:
Why can't my code access this variable?
I'm trying to build an extension for another program using an SDK. The code is written in JavaScript.

I am loading in an external library (Highcharts) using the SDK's built-in requireJS functionality.

However when I try to access Highcharts, via the Highcharts variable, the browser tells me it is undefined.

I tried console.log(this) to my code, after it should have been loaded, and you can see the output below, in the image. Highcharts seems to have been loaded. When I try console.log(EPCMPROXY) I get that object, but when I try console.log(Highcharts), I get undefined. If I open the console of the browser window, and manually type in Highcharts, it returns the object. Am I doing something wrong, or referencing Highcharts incorrectly? How is it possible that I can access the one object (EPCMPROXY) but not the other (Highcharts) when they are in the same scope?

Code:

```<code>console.log(this);
console.log(Highcharts);
console.log(EPCMPROXY);  //some var generated by the page, used as example here
</code>```

Output of console.log(this):

```<code>j {owner: f, init: function, componentDeleted: function, beforeUpdate: function, afterUpdate: function…}
    $:function ()
        arguments : null
        caller : null
        length : 0
        name : ""
        prototype : Object
        __proto__ : function ()
        [[FunctionLocation]] : combined_static_includes_1.jsversion=20170105152024:25
        [[Scopes]]:Scopes[2]
            0 : Closure (a)
            1 : Global
                $ : function (e,i)
                AsyncHandleJavascriptError : function AsyncHandleJavascriptError(a)
                EPCMPROXY : Object
                ES6Promise : Object
                Highcharts : Object
</code>```

Output of console.log(Highcharts):

```<code>undefined
</code>```

Output of console.log(EPCMPROXY):

```<code>Object
  ...
</code>```

答: The problem is that when the line "console.log(Highcharts)" is executed, it wasn't actually loaded yet (due to problems with my requireJS set-up). The reason I could see it when I executed "console.log(this)" is, as dsfq pointed out, that it shows objects that might have been loaded later, since it is run asynchronously. The little blue "i" icon, which can be seen in the screenshot, is actually a tooltip from Chrome which states: "Value below was evaluated just now".</p>

Title: Why can't my code access this variable?

Body:
I'm trying to build an extension for another program using an SDK. The code is written in JavaScript.

I am loading in an external library (Highcharts) using the SDK's built-in requireJS functionality.

However when I try to access Highcharts, via the Highcharts variable, the browser tells me it is undefined.

I tried console.log(this) to my code, after it should have been loaded, and you can see the output below, in the image. Highcharts seems to have been loaded. When I try console.log(EPCMPROXY) I get that object, but when I try console.log(Highcharts), I get undefined. If I open the console of the browser window, and manually type in Highcharts, it returns the object. Am I doing something wrong, or referencing Highcharts incorrectly? How is it possible that I can access the one object (EPCMPROXY) but not the other (Highcharts) when they are in the same scope?

Code:

console.log(this);
console.log(Highcharts);
console.log(EPCMPROXY);  //some var generated by the page, used as example here

Output of console.log(this):

j {owner: f, init: function, componentDeleted: function, beforeUpdate: function, afterUpdate: function…}
    $:function ()
        arguments : null
        caller : null
        length : 0
        name : ""
        prototype : Object
        __proto__ : function ()
        [[FunctionLocation]] : combined_static_includes_1.jsversion=20170105152024:25
        [[Scopes]]:Scopes[2]
            0 : Closure (a)
            1 : Global
                $ : function (e,i)
                AsyncHandleJavascriptError : function AsyncHandleJavascriptError(a)
                EPCMPROXY : Object
                ES6Promise : Object
                Highcharts : Object

Output of console.log(Highcharts):

undefined

Output of console.log(EPCMPROXY):

Object
  ...


问:
VBA Outlook Run-time error '438': Object doesn't support this property or method
I am trying to run this to macro to move an email attachment from a folder in my inbox (called toolkit downloads) into a folder on my desktop and rename the attachment.

I get

Run-time error '438': Object doesn't support this property or method

```<code>Sub OSP()

Dim oOutlook As Outlook.Application
Dim oNs As Outlook.NameSpace 'Main Outlook Today
Dim oFldrSb As Outlook.MAPIFolder 'Sub Folder in Outlook Today
Dim oFldrSbSb As Outlook.MAPIFolder 'Sub in Sub Folder
Dim oFldrSbSbsb As Outlook.MAPIFolder 'Sub in Sub in Sub Folder

Dim oMessage As Object
Dim sPathName As String
Dim oAttachment As Outlook.Attachment
Dim Ictr As Integer
Dim iAttachCnt As Integer

sPathName = "H:\Desktop\Toolkit Downloads\" 'My Folder Path where to save attachments

Set oOutlook = New Outlook.Application
Set oNs = oOutlook.GetNamespace("MAPI")
Set oFldrSb = oNs.Folders("Joe.Bloggs@test.co.uk")
Set oFldrSbSb = oFldrSb.Folders("Inbox")
Set oFldrSbSbsb = oFldrSbSb.Folders("Toolkit Downloads")

For Each oMessage In oFldrSbSbsb.Items

    With oMessage.Attachments
        iAttachCnt = .Count

        If iAttachCnt > 0 Then
            For Ictr = 1 To iAttachCnt
                .Item(Ictr).SaveAsFile sPathName _
                & .Item(Ictr).Parent
            Next Ictr
        End If
    End With

DoEvents

Next oMessage

SaveAttachments = True

MsgBox "All Indepol Download files have been moved !!" & vbCrLf & vbCrLf & "It worked... Yahoo"

End Sub
</code>```

答:
You are trying to use the MailItem object as a string in the method SaveAsFile, ergo the error.

I'm guessing that you want to include the mail's subject into the new file name :

```<code>.Item(Ictr).SaveAsFile sPathName _
    & .Item(Ictr).Parent.Subject
</code>```

And if you have multiples attachments, I'd add the initial file name in there :

```<code>.Item(Ictr).SaveAsFile sPathName _
    & .Item(Ictr).Parent.Subject
    & .Item(Ictr).FileName
</code>```

Full code :

```<code>Sub OSP()

Dim oOutlook As Outlook.Application
Dim oNs As Outlook.NameSpace 'Main Outlook Today
Dim oFldrSb As Outlook.MAPIFolder 'Sub Folder in Outlook Today
Dim oFldrSbSb As Outlook.MAPIFolder 'Sub in Sub Folder
Dim oFldrSbSbsb As Outlook.MAPIFolder 'Sub in Sub in Sub Folder

Dim oMessage As Object
Dim sPathName As String
Dim oAttachment As Outlook.Attachment
Dim Ictr As Integer
Dim iAttachCnt As Integer

sPathName = "H:\Desktop\Toolkit Downloads\" 'My Folder Path where to save attachments

Set oOutlook = Application
Set oNs = oOutlook.GetNamespace("MAPI")
Set oFldrSb = oNs.Folders("Joe.Bloggs@test.co.uk")
Set oFldrSbSb = oFldrSb.Folders("Inbox")
Set oFldrSbSbsb = oFldrSbSb.Folders("Toolkit Downloads")

For Each oMessage In oFldrSbSbsb.items

    With oMessage.Attachments
        iAttachCnt = .Count

        If iAttachCnt > 0 Then
            For Ictr = 1 To iAttachCnt
                .Item(Ictr).SaveAsFile sPathName _
                & .Item(Ictr).Parent.Subject
                & .Item(Ictr).FileName
            Next Ictr
        End If
    End With

DoEvents

Next oMessage

SaveAttachments = True

MsgBox "All Indepol Download files have been moved !!" & vbCrLf & vbCrLf & "It worked... Yahoo"

End Sub
</code>```

Body:
I am trying to run this to macro to move an email attachment from a folder in my inbox (called toolkit downloads) into a folder on my desktop and rename the attachment.

I get

Run-time error '438': Object doesn't support this property or method

Sub OSP()

Dim oOutlook As Outlook.Application
Dim oNs As Outlook.NameSpace 'Main Outlook Today
Dim oFldrSb As Outlook.MAPIFolder 'Sub Folder in Outlook Today
Dim oFldrSbSb As Outlook.MAPIFolder 'Sub in Sub Folder
Dim oFldrSbSbsb As Outlook.MAPIFolder 'Sub in Sub in Sub Folder

Dim oMessage As Object
Dim sPathName As String
Dim oAttachment As Outlook.Attachment
Dim Ictr As Integer
Dim iAttachCnt As Integer

sPathName = "H:\Desktop\Toolkit Downloads\" 'My Folder Path where to save attachments

Set oOutlook = New Outlook.Application
Set oNs = oOutlook.GetNamespace("MAPI")
Set oFldrSb = oNs.Folders("Joe.Bloggs@test.co.uk")
Set oFldrSbSb = oFldrSb.Folders("Inbox")
Set oFldrSbSbsb = oFldrSbSb.Folders("Toolkit Downloads")

For Each oMessage In oFldrSbSbsb.Items

    With oMessage.Attachments
        iAttachCnt = .Count

        If iAttachCnt > 0 Then
            For Ictr = 1 To iAttachCnt
                .Item(Ictr).SaveAsFile sPathName _
                & .Item(Ictr).Parent
            Next Ictr
        End If
    End With

DoEvents

Next oMessage

SaveAttachments = True

MsgBox "All Indepol Download files have been moved !!" & vbCrLf & vbCrLf & "It worked... Yahoo"

End Sub

Body:
You are trying to use the MailItem object as a string in the method SaveAsFile, ergo the error.

I'm guessing that you want to include the mail's subject into the new file name :

.Item(Ictr).SaveAsFile sPathName _
    & .Item(Ictr).Parent.Subject

And if you have multiples attachments, I'd add the initial file name in there :

.Item(Ictr).SaveAsFile sPathName _
    & .Item(Ictr).Parent.Subject
    & .Item(Ictr).FileName

Full code :

Sub OSP()

Dim oOutlook As Outlook.Application
Dim oNs As Outlook.NameSpace 'Main Outlook Today
Dim oFldrSb As Outlook.MAPIFolder 'Sub Folder in Outlook Today
Dim oFldrSbSb As Outlook.MAPIFolder 'Sub in Sub Folder
Dim oFldrSbSbsb As Outlook.MAPIFolder 'Sub in Sub in Sub Folder

Dim oMessage As Object
Dim sPathName As String
Dim oAttachment As Outlook.Attachment
Dim Ictr As Integer
Dim iAttachCnt As Integer

sPathName = "H:\Desktop\Toolkit Downloads\" 'My Folder Path where to save attachments

Set oOutlook = Application
Set oNs = oOutlook.GetNamespace("MAPI")
Set oFldrSb = oNs.Folders("Joe.Bloggs@test.co.uk")
Set oFldrSbSb = oFldrSb.Folders("Inbox")
Set oFldrSbSbsb = oFldrSbSb.Folders("Toolkit Downloads")

For Each oMessage In oFldrSbSbsb.items

    With oMessage.Attachments
        iAttachCnt = .Count

        If iAttachCnt > 0 Then
            For Ictr = 1 To iAttachCnt
                .Item(Ictr).SaveAsFile sPathName _
                & .Item(Ictr).Parent.Subject
                & .Item(Ictr).FileName
            Next Ictr
        End If
    End With

DoEvents

Next oMessage

SaveAttachments = True

MsgBox "All Indepol Download files have been moved !!" & vbCrLf & vbCrLf & "It worked... Yahoo"

End Sub


问:
Number of valid sub-string algorithm
I came across a question for which I couldn't find the algorithm. Can you help me?
Question- A valid substring is one which contains the letter a or z. You will get a string and you have to calculate the number of valid sub-strings of that string.For example- the string 'abcd' contains 4 valid substrings. The string 'azazaz' contains 21 valid substrings and similarly 'abbzbba' contains 22 valid substrings.
I just want to know the algorithm.

答:
Define D[i] - number of valid substrings ending at index i.

Assuming you have this D[i], the solution is simply D[0]+D[1]+...+D[n-1].

Calculating D is fairly simple, by iterating the string and for each charater:

if it is "valid", all substrings ending with this characters are valid.

Otherwise, only by extending a valid substring that ended at last character - makes it valid.

C code:

```<code>int NumValidSubstrings(char* s) {
  int n = strlen(s);
  int D[n] = {0};  // VLA, if that's an issue, just use dynamic allocation
  for (int i = 0; i < n; i++) {
    if (s[i] == 'z' || s[i] == 'a') {
      // if character is valid, each substring ending with it is also valid.
      D[i] += i + 1;
    } else if (i > 0) {
      // Else, only valid substrings from last character, that are extended by 1
      D[i] = D[i-1];
    }
  }
  int count = 0;
  for (int i = 0; i < n; i++) count += D[i];
  return count;
}
</code>```

Notes:

This technique is called Dynamic Programming.

This solution is O(n) time + space.

You can save some space by not storing the entire D array - but only the last value and calculate count on the fly, making this solution O(1) space  and O(n) time.

Title: Number of valid sub-string algorithm

Body:
Define D[i] - number of valid substrings ending at index i.

Assuming you have this D[i], the solution is simply D[0]+D[1]+...+D[n-1].

Calculating D is fairly simple, by iterating the string and for each charater:

if it is "valid", all substrings ending with this characters are valid.

Otherwise, only by extending a valid substring that ended at last character - makes it valid.

C code:

int NumValidSubstrings(char* s) {
  int n = strlen(s);
  int D[n] = {0};  // VLA, if that's an issue, just use dynamic allocation
  for (int i = 0; i < n; i++) {
    if (s[i] == 'z' || s[i] == 'a') {
      // if character is valid, each substring ending with it is also valid.
      D[i] += i + 1;
    } else if (i > 0) {
      // Else, only valid substrings from last character, that are extended by 1
      D[i] = D[i-1];
    }
  }
  int count = 0;
  for (int i = 0; i < n; i++) count += D[i];
  return count;
}

Notes:

This technique is called Dynamic Programming.

This solution is O(n) time + space.

You can save some space by not storing the entire D array - but only the last value and calculate count on the fly, making this solution O(1) space  and O(n) time.


问:
OrientDB Delete network BigData
I m using orientdb  community version 2.2.20 .
I have import a large dataset of for about 15M edges and 30K vertices
What is the best way to delete a graph is it to delete edges , and then the vertices ? or is there a way to delete the whole graph at once?

Reading the documentation I only  find the DELETE VERTEX, and EDGE commands

答:
If you're deleting everything, you can use also the TRUNCATE CLASS command specifying also UNSAFE. That is much faster. Example to delete any vertices and edges in your database:

```<code>TRUNCATE CLASS V POLYMORPHIC UNSAFE
TRUNCATE CLASS E POLYMORPHIC UNSAFE
</code>```

Title: OrientDB Delete network BigData

Body:
If you're deleting everything, you can use also the TRUNCATE CLASS command specifying also UNSAFE. That is much faster. Example to delete any vertices and edges in your database:

TRUNCATE CLASS V POLYMORPHIC UNSAFE
TRUNCATE CLASS E POLYMORPHIC UNSAFE


问:
Swift SWRevealController without storyboard
I implemented SWRevealController with storyboard and everything works great, but now I would like to program the app without storyboard.

Can someone help me with the implementation? I have a FrontViewController and a MenuViewController. Do I need an extra SWRevealViewController for this and if yes, what do I have to code?

I know there is some information on SWRevealController but it is in Objective-C and I have some problems to write this in Swift 2.0.

答:
This worked for me (in swift 3.1)

In the StoryBoard create MasterViewController, HomeViewController (embedded in UINavigationController) with storyboardId "HomeViewController", and MenuViewController (embedded in UINavigationController) with storyboardId "MenuViewController".

Create MasterViewController class and associate to UIViewController  (MasterViewController) in Storyboard and implements SWRevealViewControllerDelegate protocol (see code)

```<code>import UIKit

class MasterViewController: UIViewController, SWRevealViewControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    let frontNavigationController:UINavigationController
    let rearNavigationController:UINavigationController
    let revealController = SWRevealViewController()
    var mainRevealController = SWRevealViewController()

    let menuTable = self.storyboard?.instantiateViewController(withIdentifier:  "MenuViewController")as! MenuViewController
    let homepage = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

    frontNavigationController =  UINavigationController(rootViewController: homepage)
    rearNavigationController =  UINavigationController(rootViewController: menuTable)
    rearNavigationController.setNavigationBarHidden(true, animated: false)

    revealController.frontViewController = frontNavigationController
    revealController.rearViewController = rearNavigationController
    revealController.delegate = self
    mainRevealController  = revealController

    UIApplication.shared.delegate!.window?.rootViewController = mainRevealController
}
</code>```

}

As alternative you could omit MasterViewController and:

implement SWRevealViewControllerDelegate in AppDelegate and

copy the code of viewDidLoad body wrote above in   application:didFinishLaunchingWithOptions:

Body:
This worked for me (in swift 3.1)

In the StoryBoard create MasterViewController, HomeViewController (embedded in UINavigationController) with storyboardId "HomeViewController", and MenuViewController (embedded in UINavigationController) with storyboardId "MenuViewController".

Create MasterViewController class and associate to UIViewController  (MasterViewController) in Storyboard and implements SWRevealViewControllerDelegate protocol (see code)

import UIKit

class MasterViewController: UIViewController, SWRevealViewControllerDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    let frontNavigationController:UINavigationController
    let rearNavigationController:UINavigationController
    let revealController = SWRevealViewController()
    var mainRevealController = SWRevealViewController()

    let menuTable = self.storyboard?.instantiateViewController(withIdentifier:  "MenuViewController")as! MenuViewController
    let homepage = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

    frontNavigationController =  UINavigationController(rootViewController: homepage)
    rearNavigationController =  UINavigationController(rootViewController: menuTable)
    rearNavigationController.setNavigationBarHidden(true, animated: false)

    revealController.frontViewController = frontNavigationController
    revealController.rearViewController = rearNavigationController
    revealController.delegate = self
    mainRevealController  = revealController

    UIApplication.shared.delegate!.window?.rootViewController = mainRevealController
}

}

As alternative you could omit MasterViewController and:

implement SWRevealViewControllerDelegate in AppDelegate and

copy the code of viewDidLoad body wrote above in   application:didFinishLaunchingWithOptions:


问:
Is there a way to get the VMs and its flavor size from all openstack projects using cli tools?
Objective : My objective is to generate a report with all the VMs running on the openstack instance (from all projects) with its flavor size. My Environment is running Red hat openstack OSP 8 (Liberty).

Question/Issue: Is there a way to get the server and its flavor size from all projects? We can get the server list from all projects using OpenStack server "openstack server list --all-projects" but this does not give the flavor size of each VM.
I thought of writing a simple for loop taking the server list output and passing it to openstack server show command but the server show command does not show details from other projects,it only shows for admin.

Basically, I need the report similar to the table in "Horizon -> System -> Instances" (dashboard/admin/instances/) which shows the instances from all projects. I would prefer to stick with cli tools to generate the info.

Appreciate any pointers.

答: I got it working using nova cli "nova list --fields name,flavor --all-tenants". I could not find any options to list flavor using openstack unified cli.


问:
Unable to plot graph on matplotlib
I am new to Python and I am having some problems with plotting graphs on matplotlib which I hope you all can assist me.

So I have a DataFrame that shows the temperature in a given year.

```<code>    01-01    334
    01-02    320
    01-03    330
    01-04    331
    01-05    328
          .
          .
          .
    12-27    318
    12-28    320
    12-29    320
    12-30    325
    12-31    334
</code>```

and when I try to plot it by using the following codes:

```<code> dates = pd.date_range('1/1/2015','31/12/2015', freq = 'D')
 yvals = list(df.values)
 plt.figure()
 plt.plot(dates,'-', yvals, '-')
</code>```

It just returns a white figure with no points or lines on it.

How do I go about resolving this?? Thank you so much!

答:
If you use matplotlib, you can try to use plt.show():

```<code>plt.figure()
sample_image = plt.plot(x,y)
plt.imshow(sample_image)
plt.show()  # display it
</code>```

Note: Be aware that you don't have to show the image in order to save it.

```<code>plt.savefig('image.png')
</code>```

Title: Unable to plot graph on matplotlib

Body:
I am new to Python and I am having some problems with plotting graphs on matplotlib which I hope you all can assist me.

So I have a DataFrame that shows the temperature in a given year.

    01-01    334
    01-02    320
    01-03    330
    01-04    331
    01-05    328
          .
          .
          .
    12-27    318
    12-28    320
    12-29    320
    12-30    325
    12-31    334

and when I try to plot it by using the following codes:

 dates = pd.date_range('1/1/2015','31/12/2015', freq = 'D')
 yvals = list(df.values)
 plt.figure()
 plt.plot(dates,'-', yvals, '-')

It just returns a white figure with no points or lines on it.

How do I go about resolving this?? Thank you so much!

Body:
If you use matplotlib, you can try to use plt.show():

plt.figure()
sample_image = plt.plot(x,y)
plt.imshow(sample_image)
plt.show()  # display it

Note: Be aware that you don't have to show the image in order to save it.

plt.savefig('image.png')


问:
Converting Curl command to PHP not working
I have curl command working through terminal and when I converts that command in PHP, it is giving me an error.

Here is Curl command from terminal:

```<code>[root@localhost ~]# curl -XPOST -v http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive
* About to connect() to localhost port 5636 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#0)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:5636
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Evebox-Git-Revision: 8ef8639
< X-Evebox-Session-Id: IUi21/bP7TkbJ11jpYcihe1w/S41vyAbP1L1qBIJKJiL8E3440J3imOSGxKYO9j5ffqAPyv2Q3tCXqUQxhIqnw
< Date: Wed, 05 Jul 2017 06:34:31 GMT
< Content-Length: 14
<
* Connection #0 to host localhost left intact
{"status":200}[root@localhost ~]#
</code>```

Here is the curl command in PHP:

```<code>$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
  echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
</code>```

This is response: 400 Bad Request

Here is the Verbose Output:

```<code>Verbose information:
</code>```

```* About to connect() to localhost port 5636 (#6)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#6)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
Host: localhost:5636
Accept: */*
Content-Length: -1
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

< HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
< Connection: close
<
* Closing connection 6
```

400 Bad Request

答:
Use

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');

or using urlencode($url);

Body:
I have curl command working through terminal and when I converts that command in PHP, it is giving me an error.

Here is Curl command from terminal:

[root@localhost ~]# curl -XPOST -v http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive
* About to connect() to localhost port 5636 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#0)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:5636
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Evebox-Git-Revision: 8ef8639
< X-Evebox-Session-Id: IUi21/bP7TkbJ11jpYcihe1w/S41vyAbP1L1qBIJKJiL8E3440J3imOSGxKYO9j5ffqAPyv2Q3tCXqUQxhIqnw
< Date: Wed, 05 Jul 2017 06:34:31 GMT
< Content-Length: 14
<
* Connection #0 to host localhost left intact
{"status":200}[root@localhost ~]#

Here is the curl command in PHP:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
  echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

This is response: 400 Bad Request

Here is the Verbose Output:

Verbose information:

* About to connect() to localhost port 5636 (#6)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#6)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
Host: localhost:5636
Accept: */*
Content-Length: -1
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

< HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
< Connection: close
<
* Closing connection 6

400 Bad Request


答:
you should either convert the dates to numbers, or use plt.plot_dates:

```<code>dates = pd.date_range('1/1/2015' ,'31/12/2015', freq = 'D')
yvals = np.linspace(1,366,365)
plt.plot_date(dates ,yvals)
plt.show()
</code>```

(I didn't know what your yvals were so I made them up. should work with yours too)
Read the plot_date documentation for more details

Title: Unable to plot graph on matplotlib

Body:
you should either convert the dates to numbers, or use plt.plot_dates:

dates = pd.date_range('1/1/2015' ,'31/12/2015', freq = 'D')
yvals = np.linspace(1,366,365)
plt.plot_date(dates ,yvals)
plt.show()

(I didn't know what your yvals were so I made them up. should work with yours too)
Read the plot_date documentation for more details


问:
ANDROID: MediaPlayer shows error (1, -19)
I'm working on a Service that plays a song picked from an ArrayList.
The problem comes when I use prepare() and prepareAsync()methods, so here's the code:

```<code>public class MusicService extends Service implements MediaPlayer.OnPreparedListener{
    private final static int DEF_VALUE = -1;
    private Context mContext;
    private ArrayList<Song> mSongsList;
    private MediaPlayer mPlayer;
    private boolean isPlaying = false;
    private int mPosition;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate(){
        super.onCreate();
        mContext = getApplicationContext();
        mSongsList = new ArrayList<Song>();
        mPlayer = new MediaPlayer();
        setMusicPlayer();
    }

    public void setMusicPlayer(){
        //Setting player properties
        mPlayer.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setAudioSessionId(AudioManager.STREAM_MUSIC);
        mPlayer.setOnPreparedListener(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int mCommand = intent.getIntExtra("CMD", DEF_VALUE);
        int mTrackSelected = intent.getIntExtra("TRACK_CLICKED", DEF_VALUE);

        /** SERVICE COMMANDS
         *  0 = SERVICE PERMISSIONS
         *  1 = PLAY_PAUSE
         *  2 = NEXT TRACK
         *  3 = PREV TRACK
         *  4 = SONG IN LIST
         */

        switch (mCommand){
            case 0:
                GetTracks mGetSongs = new GetTracks();
                mSongsList = mGetSongs.listAllSongs(mContext);
                Log.d("test size arrayList", ""+mSongsList.size());
                break;
            case 1:
                setPlayPause();
                break;
            case 2:
                skipNextTrack();
                break;
            case 3:
                skipPrevTrack();
                break;
            case 4:
                if(mTrackSelected != DEF_VALUE){
                    mPosition = mTrackSelected;
                    setSongToPlay(mPosition);
                }
                break;
            default:
                Log.d("error cmd", "You shouldn't be here!");
                break;
        }

        return START_STICKY;
    }

    private void skipPrevTrack() {
        Log.d("method called:", "skipPrevTrack()");
        if(mPosition == 0){
            setSongToPlay(mPosition = mSongsList.size()-1);
        } else setSongToPlay(--mPosition);
        Log.d("test mPosition service", ""+mPosition);
    }

    private void skipNextTrack() {
        Log.d("method called:", "skipNextTrack()");
        if(mPosition == mSongsList.size()-1){
            setSongToPlay(mPosition = 0);
        } else setSongToPlay(++mPosition);
        Log.d("test mPosition service", ""+mPosition);
    }

    private void setSongToPlay(int pos) {
        Log.d("method called:", "setSongToPlay("+pos+")");
        startSong(mSongsList.get(pos).getSongUri());
    }
    private void startSong(Uri uri){

        try{
            mPlayer.reset();
            mPlayer.setDataSource(mContext, uri);
            mPlayer.prepareAsync();

            /** +++WORKS FINE WITH THIS CODE+++
             mPlayer = MediaPlayer.create(mContext, uri);
             mPlayer.start();
             */

        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private void setPlayPause() {
        Log.d("method called:", "setPlayPause()");
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }
}
</code>```

LOG:

```<code> 12-19 16:12:18.325 4013-4013/sebbsoft.myApp D/method called:: setSongToPlay(3)
12-19 16:12:18.341 4013-4013/sebbsoft.myApp D/test song playing: Fiori del male ft. Sfera Ebbasta
12-19 16:12:18.363 4013-4013/sebbsoft.myApp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
12-19 16:12:18.428 4013-4028/sebbsoft.myApp E/MediaPlayer: error (1, -19)
</code>```

How can I solve it?

答:
Finally solved it! After a lot of trial & error!!
This is the line that causes it for me:

```<code>mMediaPlayer.setAudioSessionId(AudioManager.STREAM_MUSIC);
</code>```

The API doc for setAudioSessionId doesn't indicate any alternative or any issue on still using it which made it hard to debug. But I saw setAudioStreamType just below it, which is deprecated and suggests setAudioAttributes instead, w/c is added in API 21.

So I changed the above code to this:

```<code>if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mMediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build());
} else {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
</code>```

And now it works!

By the way, as you can see, I checked only against version N (API 24) and above instead of from LOLLIPOP even though setAudioAttributes was added in API 21, because I only encounter this issue on Nougat devices, setAudioSessionId works up to Marshmallow devices for me so... don't wanna break anything that's already working.

I do hope someone would stop by and explain why this happens and what the error really means.

Hope this saves anyone days of headache :)

EDIT:
For anyone Googling around, I also changed the original mMediaPlayer.setAudioSessionId to mMediaPlayer.setAudioStreamType, as pointed out by Eugen Pechanec. See his comment and answer for details.
You would also want to change from checking against Build.VERSION_CODES.N to Build.VERSION_CODES.LOLLIPOP with that.

Body:
I'm working on a Service that plays a song picked from an ArrayList.
The problem comes when I use prepare() and prepareAsync()methods, so here's the code:

public class MusicService extends Service implements MediaPlayer.OnPreparedListener{
    private final static int DEF_VALUE = -1;
    private Context mContext;
    private ArrayList<Song> mSongsList;
    private MediaPlayer mPlayer;
    private boolean isPlaying = false;
    private int mPosition;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate(){
        super.onCreate();
        mContext = getApplicationContext();
        mSongsList = new ArrayList<Song>();
        mPlayer = new MediaPlayer();
        setMusicPlayer();
    }

    public void setMusicPlayer(){
        //Setting player properties
        mPlayer.setWakeMode(mContext, PowerManager.PARTIAL_WAKE_LOCK);
        mPlayer.setAudioSessionId(AudioManager.STREAM_MUSIC);
        mPlayer.setOnPreparedListener(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int mCommand = intent.getIntExtra("CMD", DEF_VALUE);
        int mTrackSelected = intent.getIntExtra("TRACK_CLICKED", DEF_VALUE);

        /** SERVICE COMMANDS
         *  0 = SERVICE PERMISSIONS
         *  1 = PLAY_PAUSE
         *  2 = NEXT TRACK
         *  3 = PREV TRACK
         *  4 = SONG IN LIST
         */

        switch (mCommand){
            case 0:
                GetTracks mGetSongs = new GetTracks();
                mSongsList = mGetSongs.listAllSongs(mContext);
                Log.d("test size arrayList", ""+mSongsList.size());
                break;
            case 1:
                setPlayPause();
                break;
            case 2:
                skipNextTrack();
                break;
            case 3:
                skipPrevTrack();
                break;
            case 4:
                if(mTrackSelected != DEF_VALUE){
                    mPosition = mTrackSelected;
                    setSongToPlay(mPosition);
                }
                break;
            default:
                Log.d("error cmd", "You shouldn't be here!");
                break;
        }

        return START_STICKY;
    }

    private void skipPrevTrack() {
        Log.d("method called:", "skipPrevTrack()");
        if(mPosition == 0){
            setSongToPlay(mPosition = mSongsList.size()-1);
        } else setSongToPlay(--mPosition);
        Log.d("test mPosition service", ""+mPosition);
    }

    private void skipNextTrack() {
        Log.d("method called:", "skipNextTrack()");
        if(mPosition == mSongsList.size()-1){
            setSongToPlay(mPosition = 0);
        } else setSongToPlay(++mPosition);
        Log.d("test mPosition service", ""+mPosition);
    }

    private void setSongToPlay(int pos) {
        Log.d("method called:", "setSongToPlay("+pos+")");
        startSong(mSongsList.get(pos).getSongUri());
    }
    private void startSong(Uri uri){

        try{
            mPlayer.reset();
            mPlayer.setDataSource(mContext, uri);
            mPlayer.prepareAsync();

            /** +++WORKS FINE WITH THIS CODE+++
             mPlayer = MediaPlayer.create(mContext, uri);
             mPlayer.start();
             */

        } catch (Exception e){
            e.printStackTrace();
        }
    }

    private void setPlayPause() {
        Log.d("method called:", "setPlayPause()");
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }
}

LOG:

 12-19 16:12:18.325 4013-4013/sebbsoft.myApp D/method called:: setSongToPlay(3)
12-19 16:12:18.341 4013-4013/sebbsoft.myApp D/test song playing: Fiori del male ft. Sfera Ebbasta
12-19 16:12:18.363 4013-4013/sebbsoft.myApp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
12-19 16:12:18.428 4013-4028/sebbsoft.myApp E/MediaPlayer: error (1, -19)

How can I solve it?

Body:
Finally solved it! After a lot of trial & error!!
This is the line that causes it for me:

mMediaPlayer.setAudioSessionId(AudioManager.STREAM_MUSIC);

The API doc for setAudioSessionId doesn't indicate any alternative or any issue on still using it which made it hard to debug. But I saw setAudioStreamType just below it, which is deprecated and suggests setAudioAttributes instead, w/c is added in API 21.

So I changed the above code to this:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mMediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build());
} else {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}

And now it works!

By the way, as you can see, I checked only against version N (API 24) and above instead of from LOLLIPOP even though setAudioAttributes was added in API 21, because I only encounter this issue on Nougat devices, setAudioSessionId works up to Marshmallow devices for me so... don't wanna break anything that's already working.

I do hope someone would stop by and explain why this happens and what the error really means.

Hope this saves anyone days of headache :)

EDIT:
For anyone Googling around, I also changed the original mMediaPlayer.setAudioSessionId to mMediaPlayer.setAudioStreamType, as pointed out by Eugen Pechanec. See his comment and answer for details.
You would also want to change from checking against Build.VERSION_CODES.N to Build.VERSION_CODES.LOLLIPOP with that.