问:
How do I get a custom field out of the payload using JJWT
OK, I am adding a couple of custom claims to the payload when I generate the JWT, and I can pull those out just fine in my front-end (javascript). I then have my javascript send an ajax call to a micro-service and it passes the JWT along with it. I want to get my custom claims out of the JWT in the micro-service. I'm doing the following:

```<code>Claims claims = Jwts.parser().setSigningKey(Vars.SECRET_KEY).parseClaimsJws(token).getBody();
 User user = claims.get("customuser", User.class);
</code>```

and it throws an exception.

```<code>io.jsonwebtoken.RequiredTypeException: Expected value to be of type: class net.netdatacorp.netdauth.model.User, but was class java.util.LinkedHashMap
    at io.jsonwebtoken.impl.DefaultClaims.get(DefaultClaims.java:128)
</code>```

Here is how the data looks in the JWT inspector on the front-end for my custom claim.

```<code>{
  jti: "83bffbad-7d36-4370-9332-21a84f2a3dce",
  iat: 1498241526,
  sub: "test",
  iss: "www.test.net",
  customuser: {
    userId: 1,
    userCd: "TMM",
    firstNm: "Testy",
    lastNm: "McTesty",
    userNm: "test",
    emailAddress: "jacob@test.net",
    active: true,
    createdDt: 1491355712000,
    createdByUserId: 0,
    lastUpdateDt: 1498199278000,
    lastUpdateByUserId: 0,
    lastLoginDt: 1484928016000
  }
}
</code>```

What am I missing to be able to pull my custom claim out?

答:
OK, so I switched to using Jose4J instead of JJWT and after working to get every thing working I realized I probably could have done something similar with JJWT. So what I ended up doing was to use Gson to perform a JSON encoding of the Object and the attaching the resulting JSON string as a claim. And so when I wanted to get a custom claim back out, I would extract the claim as a string and the use the Gson library to convert it back to a POJO.</p>

```<code>GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();

JwtConsumer jwtConsumer = getConsumer();

JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
String userStr = jwtClaims.getClaimValue("user", String.class);
User user = gson.fromJson(userStr, User.class);
</code>```

Body:
OK, I am adding a couple of custom claims to the payload when I generate the JWT, and I can pull those out just fine in my front-end (javascript). I then have my javascript send an ajax call to a micro-service and it passes the JWT along with it. I want to get my custom claims out of the JWT in the micro-service. I'm doing the following:

Claims claims = Jwts.parser().setSigningKey(Vars.SECRET_KEY).parseClaimsJws(token).getBody();
 User user = claims.get("customuser", User.class);

and it throws an exception.

io.jsonwebtoken.RequiredTypeException: Expected value to be of type: class net.netdatacorp.netdauth.model.User, but was class java.util.LinkedHashMap
    at io.jsonwebtoken.impl.DefaultClaims.get(DefaultClaims.java:128)

Here is how the data looks in the JWT inspector on the front-end for my custom claim.

{
  jti: "83bffbad-7d36-4370-9332-21a84f2a3dce",
  iat: 1498241526,
  sub: "test",
  iss: "www.test.net",
  customuser: {
    userId: 1,
    userCd: "TMM",
    firstNm: "Testy",
    lastNm: "McTesty",
    userNm: "test",
    emailAddress: "jacob@test.net",
    active: true,
    createdDt: 1491355712000,
    createdByUserId: 0,
    lastUpdateDt: 1498199278000,
    lastUpdateByUserId: 0,
    lastLoginDt: 1484928016000
  }
}

What am I missing to be able to pull my custom claim out?

Body:
OK, so I switched to using Jose4J instead of JJWT and after working to get every thing working I realized I probably could have done something similar with JJWT. So what I ended up doing was to use Gson to perform a JSON encoding of the Object and the attaching the resulting JSON string as a claim. And so when I wanted to get a custom claim back out, I would extract the claim as a string and the use the Gson library to convert it back to a POJO.

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();

JwtConsumer jwtConsumer = getConsumer();

JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
String userStr = jwtClaims.getClaimValue("user", String.class);
User user = gson.fromJson(userStr, User.class);


来源: stackexchange

问:
How to add google map on navigation drawer activity?
Problem with this, This code is also not working..</p>

```<code>public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener

mapView = (MapView)findViewById(R.id.map);

    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            googleMap.addMarker(new MarkerOptions()
                    .position(new LatLng(37.7750, 122.4183))
                    .title("San Francisco")
                    .snippet("Population: 776733"));
        }
    });
</code>```

答:
I found a solution today.

Implement OnMapReadyCallback to MainActivity.

```<code>public class MainActivity extends AppCompatActivity implements
     NavigationView.OnNavigationItemSelectedListener,
     OnMapReadyCallback
{
    // ...
}
</code>```

Implement onMapReady(). Keep it empty.

```<code>@Override
public void onMapReady(GoogleMap googleMap)
{
}
</code>```

In onCreate() method:

```<code>SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Problem with this, This code is also not working..

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener

mapView = (MapView)findViewById(R.id.map);

    mapView.onCreate(savedInstanceState);
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            googleMap.addMarker(new MarkerOptions()
                    .position(new LatLng(37.7750, 122.4183))
                    .title("San Francisco")
                    .snippet("Population: 776733"));
        }
    });

Body:
I found a solution today.

Implement OnMapReadyCallback to MainActivity.

public class MainActivity extends AppCompatActivity implements
     NavigationView.OnNavigationItemSelectedListener,
     OnMapReadyCallback
{
    // ...
}

Implement onMapReady(). Keep it empty.

@Override
public void onMapReady(GoogleMap googleMap)
{
}

In onCreate() method:

SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);


问:
jquery fancybox, ie8, Message: 'loading' is null or not an object
My website has an error in IE 8.0.6001.18702, which is something to do with jquery fancybox 1.3.1.

Webpage error details

```<code>User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/
4.0; .NET CLR 2.0.50727; MS-RTC LM 8; .NET CLR 3.0.4506.2152; .NET CLR
3.5.30729)

Message: 'loading' is null or not an object
Line: 36
Char: 4
Code: 0
URI: ....../jquery.fancybox-1.3.1.js
</code>```

Any ideas? It happens when i try to activate the iframe fancybox. I'm clicking a link in the form of:

```<code><a href="" class="iframe fancybox">blah</a>
</code>```

I have a link, but you'd have to sign up to the site to see the error. let me know if you want it

答: The answer was to upgrade to the latest version of jquery, 1.4.4 and this sorted out the issue.</p>

ContentLicense: CC BY-SA 2.5

Body:
My website has an error in IE 8.0.6001.18702, which is something to do with jquery fancybox 1.3.1.

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/
4.0; .NET CLR 2.0.50727; MS-RTC LM 8; .NET CLR 3.0.4506.2152; .NET CLR
3.5.30729)

Message: 'loading' is null or not an object
Line: 36
Char: 4
Code: 0
URI: ....../jquery.fancybox-1.3.1.js

Any ideas? It happens when i try to activate the iframe fancybox. I'm clicking a link in the form of:

blah

I have a link, but you'd have to sign up to the site to see the error. let me know if you want it


问:
Grey Bar at bottom of Website Only On Mobile View
I have set a background on my website (www.brentleas.com) and it fills the screen on desktop but on mobile it doesn't. When I use the development tools on chrome it shows the image filling the screen. However when I load up the website on my phone it has a grey bar at the bottom of the page.

Image showing what I'm talking about: 1

Here's my css code:

```<code>html {

background-image: url("../images/cooper.png");

background-repeat: no-repeat;

background-position: center center;

background-attachment: fixed;

background-size: cover;

background-color: #464646;

color: white; }
</code>```

Any help would be greatly appreciated. Thanks in advance.

答: min-height: 100%; should do the trick I guess

Body:
I have set a background on my website (www.brentleas.com) and it fills the screen on desktop but on mobile it doesn't. When I use the development tools on chrome it shows the image filling the screen. However when I load up the website on my phone it has a grey bar at the bottom of the page.

Image showing what I'm talking about: 1

Here's my css code:

html {

background-image: url("../images/cooper.png");

background-repeat: no-repeat;

background-position: center center;

background-attachment: fixed;

background-size: cover;

background-color: #464646;

color: white; }

Any help would be greatly appreciated. Thanks in advance.


问:
Spacing between checkboxes and values
JSFiddle

How would I go about editing the HTML/CSS  to create spacing between each checkbox/value pairing? Right now each checkbox and each value are spaced evenly. I'd like value1 to be close to checkbox1, but checkbox2 to have some distance from the value1.

Code here:

```<code>.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 20px 0;
}

<div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four
  </span>
</div>
</code>```

答:
Just wrap each input and its text in its own element and give them spacing of some kind:

```<code><div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One">
    One
  </span>
  <span>
    <input type="checkbox" name="Two" value="Two">
    Two
  </span>
  <span>
    <input type="checkbox" name="Three" value="Three">
    Three
  </span>
  <span>
    <input type="checkbox" name="Four" value="Four">
    Four
  </span>
</div>
</code>```

```<code>.checkboxes {
  padding: 10px;
}

span {
  margin-left: 10px;
  margin-right: 10px;
}
</code>```

https://jsfiddle.net/8to42fz8/5/

Also, what you want to use for text describing inputs is label, but plain text is just as well here.

Title: Spacing between checkboxes and values

Body:
JSFiddle

How would I go about editing the HTML/CSS  to create spacing between each checkbox/value pairing? Right now each checkbox and each value are spaced evenly. I'd like value1 to be close to checkbox1, but checkbox2 to have some distance from the value1.

Code here:

.checkboxes {
  text-align:center;
}

.checkboxes input{
  margin: 0 20px 0;
}

    <input type="checkbox" name="One" value="One"> One
    <input type="checkbox" name="Two" value="Two"> Two
    <input type="checkbox" name="Three" value="Three"> Three
    <input type="checkbox" name="Four" value="Four"> Four

Body:
Just wrap each input and its text in its own element and give them spacing of some kind:

<div class="checkboxes">
  <span>
    <input type="checkbox" name="One" value="One">
    One
  </span>
  <span>
    <input type="checkbox" name="Two" value="Two">
    Two
  </span>
  <span>
    <input type="checkbox" name="Three" value="Three">
    Three
  </span>
  <span>
    <input type="checkbox" name="Four" value="Four">
    Four
  </span>
</div>

.checkboxes {
  padding: 10px;
}

span {
  margin-left: 10px;
  margin-right: 10px;
}

https://jsfiddle.net/8to42fz8/5/

Also, what you want to use for text describing inputs is label, but plain text is just as well here.


问:
Upgrading Python in Django cartridge in Openshift to install Quantlib-Python
I am using the Django cartridge in Openshift. This cartridge has Python version 3.3.2. Is there a way to upgrade the python to 3.6?

I am trying pip install QuantLib-Python in ssh console.
It gives me the following error:
Collecting QuantLib-Python
  Could not find a version that satisfies the requirement QuantLib-Python (from versions: )
No matching distribution found for QuantLib-Python.
I did the same install in my Windows machine which has a Python version 3.6.
Hence I feel that I will be able to my pip install if I upgrade the python.
I would appreciate any suggestion. Thanks.

答: There will be no further updates to OpenShift Online V2. You should start looking at migrating to OpenShift Online V3. The latter has newer versions of Python, although no Python 3.6 as yet, latest is Python 3.5. Python 3.6 support in V3 is on its way though and will be coming at some point.</p>


问:
How to display javascript alert without reset form
I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.

I tried this way:

```<code>if($pwd != $pwd2) {
    echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
</code>```

I also tried the one below but still the same thing happened:

```<code>if($pwd != $pwd2) {
    ?>
    <script type="text/javascript">
        alert("Password does not match!");
    </script>
    <?php
}
</code>```

答:
Try this code to solve your problem. </p>

```<code>$username = $_POST['username'];
$password = $_POST['password'];

<input type="text" name="username"  value="<?php echo htmlentities($username);
?>">
<input type="password" name="password">
</code>```

Body:
I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.

I tried this way:

if($pwd != $pwd2) {
    echo("");
}

I also tried the one below but still the same thing happened:

if($pwd != $pwd2) {
    ?>

    <?php
}

Body:
Try this code to solve your problem.

$username = $_POST['username'];
$password = $_POST['password'];

<input type="text" name="username"  value="<?php echo htmlentities($username);
?>">
<input type="password" name="password">


问:
Sphinx Error: Can not import normalize while using command "make html"
I was generating documents using sphinx python library, and I encounter the
can not import normalize error.

I found a similar question from 2014 but it does not solve my problem.

Test Code

```<code># hello.py
def myadd(a,b):
    """

        Parameters
    ----------
    a: first parameter
    b: second paramter

    Returns
    -------
    Return: Sum of two arguments

    """
    return a+b

if __name__=="__main__":
     a = myadd(5,6)
     print('\n')
     print(a)
</code>```

Sphinx and Locale Installation

```<code>import sphinx
from locale import normalize # I got no error here
print(sphinx.__version__) # 1.6.2
</code>```

Sphinx commands

```<code>sphinx-quickstart
> Project name: a
> Author name(s): a
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]: n
this creates THREE files and THREE folders.
Then,

make html # this gives the error.
</code>```

This procedure works in this youtube video.

However, If I repeat the same procedure, I got following error:

```<code>File "/usr/lib/python2.7/gettext.py", line 440, in find
    for nelang in _expand_lang(lang):
  File "/usr/lib/python2.7/gettext.py", line 133, in _expand_lang
    from locale import normalize
ImportError: cannot import name normalize
Makefile:20: recipe for target 'html' failed
make: *** [html] Error 1
</code>```

Funny thing is when I import normalize from locale I get no error, and
only sphinx gives this error.

Question

How can we generate documentation using sphinx by avoiding import error?

Help will be appreciated!!

Related Links

http://www.sphinx-doc.org/en/stable/tutorial.html
http://www.sphinx-doc.org/en/stable/ext/example_google.html

https://thomas-cokelaer.info/tutorials/sphinx/docstring_python.html

http://gisellezeno.com/tutorials/sphinx-for-python-documentation.html

答:
I had two different installations of Python, namely, python2 and python3.
Both have modules sphinx and somehow they got mixed and gave the problem. For now what I did was following:

```<code>ls /Library/Frameworks/Python.framework/Versions/3.6
sudo rm -rf /Library/Frameworks/Python.framework/Versions/3.6
ls "/Applications/Python/3.6
sudo rm -rf "/Applications/Python/3.6
</code>```

Download and install graphical python3 installer from anaconda.

Then it worked without any problems.

Body:
I was generating documents using sphinx python library, and I encounter the
can not import normalize error.

I found a similar question from 2014 but it does not solve my problem.

Test Code

# hello.py
def myadd(a,b):
    """

        Parameters
    ----------
    a: first parameter
    b: second paramter

    Returns
    -------
    Return: Sum of two arguments

    """
    return a+b

if __name__=="__main__":
     a = myadd(5,6)
     print('\n')
     print(a)

Sphinx and Locale Installation

import sphinx
from locale import normalize # I got no error here
print(sphinx.__version__) # 1.6.2

Sphinx commands

sphinx-quickstart
> Project name: a
> Author name(s): a
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]: n
this creates THREE files and THREE folders.
Then,

make html # this gives the error.

This procedure works in this youtube video.

However, If I repeat the same procedure, I got following error:

File "/usr/lib/python2.7/gettext.py", line 440, in find
    for nelang in _expand_lang(lang):
  File "/usr/lib/python2.7/gettext.py", line 133, in _expand_lang
    from locale import normalize
ImportError: cannot import name normalize
Makefile:20: recipe for target 'html' failed
make: *** [html] Error 1

Funny thing is when I import normalize from locale I get no error, and
only sphinx gives this error.

Question

How can we generate documentation using sphinx by avoiding import error?

Help will be appreciated!!

Related Links

http://www.sphinx-doc.org/en/stable/tutorial.html
http://www.sphinx-doc.org/en/stable/ext/example_google.html

https://thomas-cokelaer.info/tutorials/sphinx/docstring_python.html

http://gisellezeno.com/tutorials/sphinx-for-python-documentation.html

Body:
I had two different installations of Python, namely, python2 and python3.
Both have modules sphinx and somehow they got mixed and gave the problem. For now what I did was following:

ls /Library/Frameworks/Python.framework/Versions/3.6
sudo rm -rf /Library/Frameworks/Python.framework/Versions/3.6
ls "/Applications/Python/3.6
sudo rm -rf "/Applications/Python/3.6

Download and install graphical python3 installer from anaconda.

Then it worked without any problems.


问:
Convert a list of dictionaries with similar/duplicate keys into a single dictionary (values would be list) using reduce method
This question is similar to the post "Python - Convert list of single key dictionaries into a single dictionary", where the assumption is that we guarantee different keys in the list of dictionaries. My question here is, what if we have similar keys and how we can utilize the reduce function.

For example, we have:

lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

And we want to be:

```<code>dict = {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']}
</code>```

In addition, the post How to merge multiple dicts with same key? is similar, except that here we would like to utilize the reduce method.

答:
I just came up with a solution using a function with the reduce method.

First we define a function that checks if the key was inserted in dict before or not. If it's a new key we add it to the dict with the value in a list, if it's already there we append the value to the existing list.

```<code>def dict_list(each_dict):
    d_key = each_dict.keys()[0]
    d_value = each_dict.values()[0]
    if d_key in return_dict:
        return_dict[d_key].append(d_value)
    else:
        return_dict[d_key] = [d_value]
    return return_dict
</code>```

Then use this function with reduce in a single line as following:

```<code>lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]
return_dict = {}
print reduce(lambda return_dict, each_dict: dict_list(each_dict), lst, {})
</code>```

Body:
This question is similar to the post "Python - Convert list of single key dictionaries into a single dictionary", where the assumption is that we guarantee different keys in the list of dictionaries. My question here is, what if we have similar keys and how we can utilize the reduce function.

For example, we have:

lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]

And we want to be:

dict = {'1': ['A', 'B'], '2': ['C', 'D'], '3': ['E']}

In addition, the post How to merge multiple dicts with same key? is similar, except that here we would like to utilize the reduce method.

Body:
I just came up with a solution using a function with the reduce method.

First we define a function that checks if the key was inserted in dict before or not. If it's a new key we add it to the dict with the value in a list, if it's already there we append the value to the existing list.

def dict_list(each_dict):
    d_key = each_dict.keys()[0]
    d_value = each_dict.values()[0]
    if d_key in return_dict:
        return_dict[d_key].append(d_value)
    else:
        return_dict[d_key] = [d_value]
    return return_dict

Then use this function with reduce in a single line as following:

lst = [{'1': 'A'}, {'1': 'B'}, {'2': 'C'}, {'2': 'D'}, {'3': 'E'}]
return_dict = {}
print reduce(lambda return_dict, each_dict: dict_list(each_dict), lst, {})


问:
How to revert to old Swift's AnyObject & Any auto-convert behavior?
I understand that Swift wants to enforce strong typing by removing the auto-converting behavior of any type into AnyObject and Any. But sometimes, for some kind of parameter, I just want to actually declare that the parameter accepts anything without the need to add as AnyObject or as Any because for my situation it made the code ugly as hell and very unnecessary because I do check for various types of data from that parameter inside the function. How can I evoke that behavior (locally or globally) in the new Swift 3.x or 4.x?

答:
As of this SE-0072 evolution proposal of swift, you might not be able to do that in Swift 3. There are some conversion issues of which are described in short here.

For this the Proposed solution states that "Implicit bridging conversions in Swift 3 should be eliminated".

And from Impact on existing code it is stated:

Code that previously relied on implicit conversions between Swift value types and their associated bridged Objective-C type will now require a manual coercion via an as cast.


问:
Tables and how to manage data
I have a table:

    1
    2
    3
    4

```
</div>
</div>
</p>

<p>I want the cells to break at a certain width so that it displays:</p>

```1 2
3 4
```

I tried using td:nth-child(), but couldn't get past changing the color of the td or having them all vertical.

Thanks for any help

Title: Tables and how to manage data

Body:
I have a table:

    1
    2
    3
    4

I want the cells to break at a certain width so that it displays:

1 2
3 4

I tried using td:nth-child(), but couldn't get past changing the color of the td or having them all vertical.

Thanks for any help

Body:
<table>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
  </tr>
</table>


问:
Check CPU utilization of rsync and kill if it crosses a threshold
I have a shell script running four rsync commands sequentially. This script is scheduled to run every 20 min using a CRON job.
Sometimes the rsync process takes upto 30% CPU utilization, slowing the server down. This is causing problems.

This is my script:

```<code>### rsync_script.sh

#!/bin/bash

rsync -avz --delete --bwlimit=5000 /path1/to/file/filename_* root@1.1.1.1:/destination/path1/

rsync -avz --delete --bwlimit=5000 /path2/to/file/filename_* root@1.1.1.1:/destination/path2/

rsync -avz --delete --bwlimit=5000 /path3/to/file/filename_* root@1.1.1.1:/destination/path3/

rsync -avz --delete --bwlimit=5000 /path4/to/file/filename_* root@1.1.1.1:/destination/path4/
</code>```

I run the cron job:

```<code>*/20 * * * * /bin/sh  /path/to/script/rsync_script.sh
</code>```

I need to put a check such that if the CPU utilization of rsync exceeeds say 5%, then I need to stop the script.

Any help is appreciated.

Thanks

答:
If using too much CPU is your issue, then rather than killing the process, you might schedule it at a lower priority.

See man 1 nice for instructions on a tool to do that.

The -z option you are using is a compression option - if you are CPU constrained that might be something to tweak and test.

The --stats option gives you a sense for rsync's internal statistics on efficiency, also something good to look at while tuning things.

Good luck - fortunately there are some things you can tune.

Body:
I have a shell script running four rsync commands sequentially. This script is scheduled to run every 20 min using a CRON job.
Sometimes the rsync process takes upto 30% CPU utilization, slowing the server down. This is causing problems.

This is my script:

### rsync_script.sh

#!/bin/bash

rsync -avz --delete --bwlimit=5000 /path1/to/file/filename_* root@1.1.1.1:/destination/path1/

rsync -avz --delete --bwlimit=5000 /path2/to/file/filename_* root@1.1.1.1:/destination/path2/

rsync -avz --delete --bwlimit=5000 /path3/to/file/filename_* root@1.1.1.1:/destination/path3/

rsync -avz --delete --bwlimit=5000 /path4/to/file/filename_* root@1.1.1.1:/destination/path4/

I run the cron job:

*/20 * * * * /bin/sh  /path/to/script/rsync_script.sh

I need to put a check such that if the CPU utilization of rsync exceeeds say 5%, then I need to stop the script.

Any help is appreciated.

Thanks


问:
Error getting part of url separated by blackslash
I want to get last part of url separated by blackslash
Here is my code

```<code><?php

$str = "C:\xampp\htdocs\sanimailer\storage\mail-attachments\10819_21098672691424384960_C
opy_of_tristan_data_cleanup_version_FBL_3.2.xlsx";

echo basename($str);
?>
</code>```

I want output as this

```<code>10819_21098672691424384960_Copy_of_tristan_data_cleanup_version_FBL_3.2.xlsx
</code>```

But I am getting output as this

Not sure why I am getting such output .

答:
You need to convert " to ' and then it will work:-

```<code><?php

   $str = 'C:\xampp\htdocs\sanimailer\storage\mail-attachments\10819_21098672691424384960_C
opy_of_tristan_data_cleanup_version_FBL_3.2.xlsx';

   echo basename($str);
?>
</code>```

Output:- https://eval.in/829073

The problem you are facing because "\10" converted to that symbol

check here:- https://eval.in/829077

Body:
I want to get last part of url separated by blackslash
Here is my code

<?php

$str = "C:\xampp\htdocs\sanimailer\storage\mail-attachments\10819_21098672691424384960_C
opy_of_tristan_data_cleanup_version_FBL_3.2.xlsx";

echo basename($str);
?>

I want output as this

10819_21098672691424384960_Copy_of_tristan_data_cleanup_version_FBL_3.2.xlsx

But I am getting output as this

Not sure why I am getting such output .

Body:
You need to convert " to ' and then it will work:-

<?php

   $str = 'C:\xampp\htdocs\sanimailer\storage\mail-attachments\10819_21098672691424384960_C
opy_of_tristan_data_cleanup_version_FBL_3.2.xlsx';

   echo basename($str);
?>

Output:- https://eval.in/829073

The problem you are facing because "\10" converted to that symbol

check here:- https://eval.in/829077


问:
How can I add an alert when Geolocation Services are denied?
It had worked previously in my code, however with the recent changes I made it seems to be broken. I tried looking online for solutions, however this seems specific to me in terms of what I need. All i want is for an "alert();" to be showen if the browser Geolocation Services request is denied. Here is the code without the alert added in. Thank you.</p>

```<code>      if (navigator.geolocation) {
            // Locate position
            navigator.geolocation.getCurrentPosition(displayPosition);
        } else {
            alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
        }
        blacklisted_areas = {
            'area 51': [1, 2],
            'pink unicorn zoo': [1, 2],
        };
        // Success callback function
        function displayPosition(pos) {
  var mylat = pos.coords.latitude;
  var mylong = pos.coords.longitude;
  var thediv = document.getElementById('locationinfo');
  thediv.innerHTML = '<p>Your longitude is :' + mylong + ' and your latitide is ' + mylat + '</p>';

  var blacklisted = false;
  for (let x of Object.values(blacklisted_areas)) {
    if (mylat === x[0] && mylong === x[1]) {
      blacklisted = true;
    }
  }
  if(!blacklisted){
    window.location="insertURLHere";
  }

}
</code>```

答:
Just handle error case:</p>

```<code>navigator.geolocation.getCurrentPosition(displayPosition, onError);
function onError (error) {
    if (error.code == error.PERMISSION_DENIED)
       alert("you denied geolocation");
};
</code>```

Body:
It had worked previously in my code, however with the recent changes I made it seems to be broken. I tried looking online for solutions, however this seems specific to me in terms of what I need. All i want is for an "alert();" to be showen if the browser Geolocation Services request is denied. Here is the code without the alert added in. Thank you.

      if (navigator.geolocation) {
            // Locate position
            navigator.geolocation.getCurrentPosition(displayPosition);
        } else {
            alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
        }
        blacklisted_areas = {
            'area 51': [1, 2],
            'pink unicorn zoo': [1, 2],
        };
        // Success callback function
        function displayPosition(pos) {
  var mylat = pos.coords.latitude;
  var mylong = pos.coords.longitude;
  var thediv = document.getElementById('locationinfo');
  thediv.innerHTML = '
Your longitude is :' + mylong + ' and your latitide is ' + mylat + '
';

  var blacklisted = false;
  for (let x of Object.values(blacklisted_areas)) {
    if (mylat === x[0] && mylong === x[1]) {
      blacklisted = true;
    }
  }
  if(!blacklisted){
    window.location="insertURLHere";
  }

}

Body:
Just handle error case:

navigator.geolocation.getCurrentPosition(displayPosition, onError);
function onError (error) {
    if (error.code == error.PERMISSION_DENIED)
       alert("you denied geolocation");
};


问:
Oracle APEX shuttle item validation
Using Oracle APEX 3.0.1

I have two shuttle items named P1_SHUTTLE and P1_SHUTTLE_2.

I need a means of checking/validating the shuttle so that when a user selects an item from left to right, only one item is ever allowed in the right shuttle.

What can I do to check if the shuttle has already got an item and disallow further items to be added to it when the user attempts to do so?

答:
I think you're going about this the wrong way.

The whole purpose of using a shuttle item, as opposed to a simple item with a select list or list of values, is that the user can choose more than one item.

If they are only allowed to choose one item, don't use a shuttle.

Title: Oracle APEX shuttle item validation


问:
how to convert from one date format to another in mysql
I am using MySQL and I want to get all the dates in the previous week from a column, say xyz, which is of type date and has the format YYYY-MM-DD. However, when I use

```<code>select
    *
from
    tablename
where
    xyz > date_sub(curdate(),INTERVAL 1 week);
</code>```

I get dates which are not within the past 1 week. I get dates which are one month from now and some random dates.

答:
You query is pulling all records in which xyz (your date column I assume) is newer than one week ago. This could in fact be future records. If you want to exclusively view things from the previous week, you need to use the between keyword.

```<code>select
    *
from
    tablename
where
    xyz between date_sub(curdate(), INTERVAL 1 week) and curdate()
</code>```

Body:
I am using MySQL and I want to get all the dates in the previous week from a column, say xyz, which is of type date and has the format YYYY-MM-DD. However, when I use

select
    *
from
    tablename
where
    xyz > date_sub(curdate(),INTERVAL 1 week);

I get dates which are not within the past 1 week. I get dates which are one month from now and some random dates.

Body:
You query is pulling all records in which xyz (your date column I assume) is newer than one week ago. This could in fact be future records. If you want to exclusively view things from the previous week, you need to use the between keyword.

select
    *
from
    tablename
where
    xyz between date_sub(curdate(), INTERVAL 1 week) and curdate()


问:
How do I get list of all tables in a database using TSQL?
What is the best way to get the names of all of the tables in a specific database on SQL Server?</p>

答:
```<code>SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
ORDER BY TABLE_NAME
</code>```

OwnerDisplayName: Ray Vega


问:
Custom TypeAdapter for Retrofit 2.0
I'm consuming an API that provides much more information that I need.
Im using Retrofit and GSON to get the data and create a list of POJO with the needed values.
I made a custom TypeAdapter, and inside of it, I get the response and return a list of objects. When using a local JSON object, it work fine with the custom TypeAdapter, but with Retrofit I go the error.

```<code>Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
</code>```

Any ideas why is that? What Im I doing wrong?

EDIT:

I changed the GsonBuilder, to pass the right type to the Retrofit Builder, like this:

```<code>Type collectionType = new TypeToken<List<Article>>(){}.getType();
    gsonBuilder.registerTypeAdapter(collectionType,new ArticleTypeAdapter());
</code>```

JSON

```<code>{
"status": "OK",
"copyright": "Copyright (c) 2017 The New York Times Company.  All Rights Reserved.",
"num_results": 5,
"results": [
    {
        "url": "https://www.nytimes.com/2017/06/29/automobiles/autoreviews/video-review-a-family-friendly-ferrari-for-the-family-of-means.html",
        "adx_keywords": "Ferrari SpA;Ferrari GTC4Lusso;Automobiles",
        "column": "Driven",
        "section": "Automobiles",
        "byline": "By TOM VOELK",
        "type": "Article",
        "title": "Video Review: A Family-Friendly Ferrari, for the Family of Means",
        "abstract": "The all-wheel-drive V12 GTC4Lusso seats four comfortably. With its svelte silhouette, it may look like a station wagon. It is anything but.",
        "published_date": "2017-06-29",
        "source": "The New York Times",
        "id": 100000005178442,
        "asset_id": 100000005178442,
        "views": 1,
        "des_facet": [
            "AUTOMOBILES"
        ],
        "org_facet": [
            "FERRARI SPA"
        ],
        "per_facet": "",
        "geo_facet": "",
        "media": [
            {
                "type": "image",
                "subtype": "photo",
                "caption": "Ferrari GTC4Lusso",
                "copyright": "Martin Campbell",
                "approved_for_syndication": 1,
                "media-metadata": [
                    {
                        "url": "https://static01.nyt.com/images/2017/06/26/automobiles/autoreviews/27driven1/27driven1-thumbStandard.jpg",
                        "format": "Standard Thumbnail",
                        "height": 75,
                        "width": 75
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/26/automobiles/autoreviews/27driven1/27driven1-mediumThreeByTwo210.jpg",
                        "format": "mediumThreeByTwo210",
                        "height": 140,
                        "width": 210
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/26/automobiles/autoreviews/27driven1/27driven1-mediumThreeByTwo440.jpg",
                        "format": "mediumThreeByTwo440",
                        "height": 293,
                        "width": 440
                    }
                ]
            }
        ]
    },
    {
        "url": "https://www.nytimes.com/2017/07/06/automobiles/wheels/luxury-cars-dealers-sales.html",
        "adx_keywords": "Automobiles;Luxury Goods and Services;Customer Relations;United States;Lexus Division of Toyota Motor Corp;Cadillac Division of General Motors Corp;Alfa Romeo Automobiles;Lincoln Motor Co",
        "column": "Wheels",
        "section": "Automobiles",
        "byline": "By ERIC A. TAUB",
        "type": "Article",
        "title": "How to Soothe Luxury-Car Buyers: Add Perks and Subtract Haggling",
        "abstract": "Several automakers aim to change the shopping experience with fixed prices, after-sale care and even ways to avoid the dealership altogether.",
        "published_date": "2017-07-06",
        "source": "The New York Times",
        "id": 100000005135624,
        "asset_id": 100000005135624,
        "views": 2,
        "des_facet": [
            "AUTOMOBILES",
            "LUXURY GOODS AND SERVICES",
            "CUSTOMER RELATIONS"
        ],
        "org_facet": [
            "LEXUS DIVISION OF TOYOTA MOTOR CORP",
            "CADILLAC DIVISION OF GENERAL MOTORS CORP",
            "ALFA ROMEO AUTOMOBILES",
            "LINCOLN MOTOR CO"
        ],
        "per_facet": "",
        "geo_facet": [
            "UNITED STATES"
        ],
        "media": [
            {
                "type": "image",
                "subtype": "photo",
                "caption": "Lexus has introduced a fixed-price program, called Lexus Plus, in which the buyer deals with only one person from beginning to end.",
                "copyright": "Alex Wroblewski for The New York Times",
                "approved_for_syndication": 1,
                "media-metadata": [
                    {
                        "url": "https://static01.nyt.com/images/2017/07/06/business/07WHEELS1/07WHEELS1-thumbStandard.jpg",
                        "format": "Standard Thumbnail",
                        "height": 75,
                        "width": 75
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/07/06/business/07WHEELS1/07WHEELS1-mediumThreeByTwo210.jpg",
                        "format": "mediumThreeByTwo210",
                        "height": 140,
                        "width": 210
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/07/06/business/07WHEELS1/07WHEELS1-mediumThreeByTwo440.jpg",
                        "format": "mediumThreeByTwo440",
                        "height": 293,
                        "width": 440
                    }
                ]
            }
        ]
    },
    {
        "url": "https://www.nytimes.com/2017/06/29/automobiles/wheels/why-fog-lamps-are-starting-to-disappear.html",
        "adx_keywords": "Automobile Safety Features and Defects;AAA Foundation for Traffic Safety;Mercedes-Benz;Consumer Reports;Insurance Institute for Highway Safety",
        "column": "Wheels",
        "section": "Automobiles",
        "byline": "By JAMES G. COBB",
        "type": "Article",
        "title": "Why Fog Lamps Are Starting to Disappear",
        "abstract": "Several luxury automakers have moved away from fog lights, saying that new high-tech headlights render them obsolete.",
        "published_date": "2017-06-29",
        "source": "The New York Times",
        "id": 100000005172500,
        "asset_id": 100000005172500,
        "views": 3,
        "des_facet": [
            "AUTOMOBILE SAFETY FEATURES AND DEFECTS"
        ],
        "org_facet": [
            "AAA FOUNDATION FOR TRAFFIC SAFETY",
            "MERCEDES-BENZ",
            "CONSUMER REPORTS",
            "INSURANCE INSTITUTE FOR HIGHWAY SAFETY"
        ],
        "per_facet": "",
        "geo_facet": "",
        "media": [
            {
                "type": "image",
                "subtype": "photo",
                "caption": "General Motors’ headquarters and other buildings in the Detroit skyline, obscured by early morning fog. Some automakers have quietly omitted front fog lights from many new models, saying that high-tech headlights make them unnecessary.",
                "copyright": "Kevin Miyazaki for The New York Times",
                "approved_for_syndication": 1,
                "media-metadata": [
                    {
                        "url": "https://static01.nyt.com/images/2017/06/29/business/30WHEELS1/30WHEELS1-thumbStandard.jpg",
                        "format": "Standard Thumbnail",
                        "height": 75,
                        "width": 75
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/29/business/30WHEELS1/30WHEELS1-mediumThreeByTwo210.jpg",
                        "format": "mediumThreeByTwo210",
                        "height": 140,
                        "width": 210
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/29/business/30WHEELS1/30WHEELS1-mediumThreeByTwo440.jpg",
                        "format": "mediumThreeByTwo440",
                        "height": 293,
                        "width": 440
                    }
                ]
            }
        ]
    },
    {
        "url": "https://www.nytimes.com/2017/07/06/automobiles/autoreviews/video-review-volvo-v90-cross-country-rolls-into-suv-territory.html",
        "adx_keywords": "Automobiles;Volvo Car Corp;2017 Volvo V90 Cross Country",
        "column": "Driven",
        "section": "Automobiles",
        "byline": "By TOM VOELK",
        "type": "Article",
        "title": "Video Review: Volvo V90 Cross Country Rolls Into S.U.V. Territory",
        "abstract": "Americans are buying S.U.V.s and crossovers in record numbers, but it’s worth keeping an open mind about Volvo’s station wagon.",
        "published_date": "2017-07-06",
        "source": "The New York Times",
        "id": 100000005194798,
        "asset_id": 100000005194798,
        "views": 4,
        "des_facet": [
            "AUTOMOBILES"
        ],
        "org_facet": [
            "VOLVO CAR CORP"
        ],
        "per_facet": "",
        "geo_facet": "",
        "media": ""
    },
    {
        "url": "https://www.nytimes.com/2017/06/08/automobiles/saab-autos-cars.html",
        "adx_keywords": "Automobiles;Saab Automobile AB;Bankruptcies;Portland (Ore)",
        "column": "Wheels",
        "section": "Automobiles",
        "byline": "By NICK KURCZEWSKI",
        "type": "Article",
        "title": "In Portland, a Rare Outpost for Die-Hard Saab Fans",
        "abstract": "The Swedish automaker filed for bankruptcy in 2011, leaving a vanishingly small number of dealerships for fans of the company.",
        "published_date": "2017-06-08",
        "source": "The New York Times",
        "id": 100000005095241,
        "asset_id": 100000005095241,
        "views": 5,
        "des_facet": [
            "AUTOMOBILES",
            "BANKRUPTCIES"
        ],
        "org_facet": [
            "SAAB AUTOMOBILE AB"
        ],
        "per_facet": "",
        "geo_facet": [
            "PORTLAND (ORE)"
        ],
        "media": [
            {
                "type": "image",
                "subtype": "photo",
                "caption": "Saab filed for bankruptcy in 2011, but Garry Small Saab in Portland, Ore., has continued to service and sell the brand’s cars.",
                "copyright": "Amanda Lucier for The New York Times",
                "approved_for_syndication": 1,
                "media-metadata": [
                    {
                        "url": "https://static01.nyt.com/images/2017/06/08/business/09WHEELS1/09WHEELS1-thumbStandard.jpg",
                        "format": "Standard Thumbnail",
                        "height": 75,
                        "width": 75
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/08/business/09WHEELS1/09WHEELS1-mediumThreeByTwo210.jpg",
                        "format": "mediumThreeByTwo210",
                        "height": 140,
                        "width": 210
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/08/business/09WHEELS1/09WHEELS1-mediumThreeByTwo440.jpg",
                        "format": "mediumThreeByTwo440",
                        "height": 293,
                        "width": 440
                    }
                ]
            }
        ]
    }
]
</code>```

}

Type Adapter's read method

```<code>public List<Article> read(JsonReader in) throws IOException {

    final List<Article> article_list = new ArrayList<>();
    in.beginObject();
    while(in.hasNext()){
        switch (in.nextName()){
            case "results":
                in.beginArray();
                while(in.hasNext()){
                    final Article article = new Article();
                    in.beginObject();
                    while (in.hasNext()){
                        switch (in.nextName()){

                            case "id":
                                article.setId(Long.valueOf(in.nextString()));
                                break;
                            case "title":
                                article.setTitle(in.nextString());
                                break;
                            case "url":
                                article.setUrl(in.nextString());
                                break;
                            case "adx_keywords":
                                article.setAdxKeywords(in.nextString());
                                break;
                            case "section":
                                article.setSection(in.nextString());
                                break;
                            case "byline":
                                article.setByline(in.nextString());
                                break;
                            case "abstract":
                                article.set_abstract(in.nextString());
                                break;
                            case "published_date":
                                article.setPublishedDate(in.nextString());
                                break;
                            case "media":
                                if(!in.peek().equals(JsonToken.BEGIN_ARRAY)){
                                    in.skipValue();
                                    break;
                                }
                                in.beginArray();
                                final ArrayList<Media> media_list = new ArrayList<>();
                                while(in.hasNext()){
                                    in.beginObject();
                                    while(in.hasNext()){
                                        switch (in.nextName()){
                                            case "media-metadata":
                                                in.beginArray();
                                                while(in.hasNext()){
                                                    in.beginObject();
                                                    final Media media = new Media();
                                                    while(in.hasNext()){
                                                        switch (in.nextName()){
                                                            case "url":
                                                                media.setUrl(in.nextString());
                                                                break;
                                                            case "format":
                                                                media.setFormat(in.nextString());
                                                                break;
                                                            default:
                                                                in.skipValue();
                                                                break;
                                                        }
                                                    }
                                                    in.endObject();
                                                    media_list.add(media);
                                                }
                                                in.endArray();
                                                break;
                                            default:
                                                in.skipValue();
                                                break;
                                        }
                                    }
                                    in.endObject();
                                }
                                in.endArray();
                                for(Media m : media_list){
                                    if(m.getFormat().equals("mediumThreeByTwo440")){
                                        article.setMedia(m);
                                        break;
                                    }
                                }
                                break;

                            default:
                                in.skipValue();
                                break;
                        }/**/
                    }
                    in.endObject();
                    article_list.add(article);
                }
                in.endArray();
                break;
            default:
                in.skipValue();
                break;

        }

    }
    in.endObject();

    Timber.d(article_list.toString());
    return article_list;
}
</code>```

Article and Media classes (no methods)

```<code>public class Article {
private Long id;
private String url;
private String adxKeywords;
private String section;
private String byline;
private String title;
private String _abstract;
private String publishedDate;
private Media media;
}

public class Media {
private String url;
private String format;
}
</code>```

Retrofit Builder

```<code>final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Article.class,new ArticleTypeAdapter());
    final Gson gson = gsonBuilder.create();
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
</code>```

答:
You need do something like this:-

```<code>public class Response{
    public String status;
    public String copyright;
    public int num_results;
    public Article[] results;
}
</code>```

You have to pass a response class with the same structure of response you are receiving from the server.
Please follow the steps:-

You don't required a different type adapter for each request you can simply create the retrofit with default Gson converter factory like this:-

```<code>Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
</code>```

Now you need to define a Service for API request like this:-

```<code>public class ArticleService{
   @GET("endpoint")//What ever is your request type
   Call<Response> getArticals(/** body query param or other required data**// )
}
</code>```

After that you request creation will be something like this:-

```<code>ArticleService service = retrofit.create(ArticleService.class);
</code>```

Title: Custom TypeAdapter for Retrofit 2.0

Body:
I'm consuming an API that provides much more information that I need.
Im using Retrofit and GSON to get the data and create a list of POJO with the needed values.
I made a custom TypeAdapter, and inside of it, I get the response and return a list of objects. When using a local JSON object, it work fine with the custom TypeAdapter, but with Retrofit I go the error.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Any ideas why is that? What Im I doing wrong?

EDIT:

I changed the GsonBuilder, to pass the right type to the Retrofit Builder, like this:

Type collectionType = new TypeToken<List
>(){}.getType();
    gsonBuilder.registerTypeAdapter(collectionType,new ArticleTypeAdapter());

JSON

{
"status": "OK",
"copyright": "Copyright (c) 2017 The New York Times Company.  All Rights Reserved.",
"num_results": 5,
"results": [
    {
        "url": "https://www.nytimes.com/2017/06/29/automobiles/autoreviews/video-review-a-family-friendly-ferrari-for-the-family-of-means.html",
        "adx_keywords": "Ferrari SpA;Ferrari GTC4Lusso;Automobiles",
        "column": "Driven",
        "section": "Automobiles",
        "byline": "By TOM VOELK",
        "type": "Article",
        "title": "Video Review: A Family-Friendly Ferrari, for the Family of Means",
        "abstract": "The all-wheel-drive V12 GTC4Lusso seats four comfortably. With its svelte silhouette, it may look like a station wagon. It is anything but.",
        "published_date": "2017-06-29",
        "source": "The New York Times",
        "id": 100000005178442,
        "asset_id": 100000005178442,
        "views": 1,
        "des_facet": [
            "AUTOMOBILES"
        ],
        "org_facet": [
            "FERRARI SPA"
        ],
        "per_facet": "",
        "geo_facet": "",
        "media": [
            {
                "type": "image",
                "subtype": "photo",
                "caption": "Ferrari GTC4Lusso",
                "copyright": "Martin Campbell",
                "approved_for_syndication": 1,
                "media-metadata": [
                    {
                        "url": "https://static01.nyt.com/images/2017/06/26/automobiles/autoreviews/27driven1/27driven1-thumbStandard.jpg",
                        "format": "Standard Thumbnail",
                        "height": 75,
                        "width": 75
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/26/automobiles/autoreviews/27driven1/27driven1-mediumThreeByTwo210.jpg",
                        "format": "mediumThreeByTwo210",
                        "height": 140,
                        "width": 210
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/26/automobiles/autoreviews/27driven1/27driven1-mediumThreeByTwo440.jpg",
                        "format": "mediumThreeByTwo440",
                        "height": 293,
                        "width": 440
                    }
                ]
            }
        ]
    },
    {
        "url": "https://www.nytimes.com/2017/07/06/automobiles/wheels/luxury-cars-dealers-sales.html",
        "adx_keywords": "Automobiles;Luxury Goods and Services;Customer Relations;United States;Lexus Division of Toyota Motor Corp;Cadillac Division of General Motors Corp;Alfa Romeo Automobiles;Lincoln Motor Co",
        "column": "Wheels",
        "section": "Automobiles",
        "byline": "By ERIC A. TAUB",
        "type": "Article",
        "title": "How to Soothe Luxury-Car Buyers: Add Perks and Subtract Haggling",
        "abstract": "Several automakers aim to change the shopping experience with fixed prices, after-sale care and even ways to avoid the dealership altogether.",
        "published_date": "2017-07-06",
        "source": "The New York Times",
        "id": 100000005135624,
        "asset_id": 100000005135624,
        "views": 2,
        "des_facet": [
            "AUTOMOBILES",
            "LUXURY GOODS AND SERVICES",
            "CUSTOMER RELATIONS"
        ],
        "org_facet": [
            "LEXUS DIVISION OF TOYOTA MOTOR CORP",
            "CADILLAC DIVISION OF GENERAL MOTORS CORP",
            "ALFA ROMEO AUTOMOBILES",
            "LINCOLN MOTOR CO"
        ],
        "per_facet": "",
        "geo_facet": [
            "UNITED STATES"
        ],
        "media": [
            {
                "type": "image",
                "subtype": "photo",
                "caption": "Lexus has introduced a fixed-price program, called Lexus Plus, in which the buyer deals with only one person from beginning to end.",
                "copyright": "Alex Wroblewski for The New York Times",
                "approved_for_syndication": 1,
                "media-metadata": [
                    {
                        "url": "https://static01.nyt.com/images/2017/07/06/business/07WHEELS1/07WHEELS1-thumbStandard.jpg",
                        "format": "Standard Thumbnail",
                        "height": 75,
                        "width": 75
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/07/06/business/07WHEELS1/07WHEELS1-mediumThreeByTwo210.jpg",
                        "format": "mediumThreeByTwo210",
                        "height": 140,
                        "width": 210
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/07/06/business/07WHEELS1/07WHEELS1-mediumThreeByTwo440.jpg",
                        "format": "mediumThreeByTwo440",
                        "height": 293,
                        "width": 440
                    }
                ]
            }
        ]
    },
    {
        "url": "https://www.nytimes.com/2017/06/29/automobiles/wheels/why-fog-lamps-are-starting-to-disappear.html",
        "adx_keywords": "Automobile Safety Features and Defects;AAA Foundation for Traffic Safety;Mercedes-Benz;Consumer Reports;Insurance Institute for Highway Safety",
        "column": "Wheels",
        "section": "Automobiles",
        "byline": "By JAMES G. COBB",
        "type": "Article",
        "title": "Why Fog Lamps Are Starting to Disappear",
        "abstract": "Several luxury automakers have moved away from fog lights, saying that new high-tech headlights render them obsolete.",
        "published_date": "2017-06-29",
        "source": "The New York Times",
        "id": 100000005172500,
        "asset_id": 100000005172500,
        "views": 3,
        "des_facet": [
            "AUTOMOBILE SAFETY FEATURES AND DEFECTS"
        ],
        "org_facet": [
            "AAA FOUNDATION FOR TRAFFIC SAFETY",
            "MERCEDES-BENZ",
            "CONSUMER REPORTS",
            "INSURANCE INSTITUTE FOR HIGHWAY SAFETY"
        ],
        "per_facet": "",
        "geo_facet": "",
        "media": [
            {
                "type": "image",
                "subtype": "photo",
                "caption": "General Motors’ headquarters and other buildings in the Detroit skyline, obscured by early morning fog. Some automakers have quietly omitted front fog lights from many new models, saying that high-tech headlights make them unnecessary.",
                "copyright": "Kevin Miyazaki for The New York Times",
                "approved_for_syndication": 1,
                "media-metadata": [
                    {
                        "url": "https://static01.nyt.com/images/2017/06/29/business/30WHEELS1/30WHEELS1-thumbStandard.jpg",
                        "format": "Standard Thumbnail",
                        "height": 75,
                        "width": 75
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/29/business/30WHEELS1/30WHEELS1-mediumThreeByTwo210.jpg",
                        "format": "mediumThreeByTwo210",
                        "height": 140,
                        "width": 210
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/29/business/30WHEELS1/30WHEELS1-mediumThreeByTwo440.jpg",
                        "format": "mediumThreeByTwo440",
                        "height": 293,
                        "width": 440
                    }
                ]
            }
        ]
    },
    {
        "url": "https://www.nytimes.com/2017/07/06/automobiles/autoreviews/video-review-volvo-v90-cross-country-rolls-into-suv-territory.html",
        "adx_keywords": "Automobiles;Volvo Car Corp;2017 Volvo V90 Cross Country",
        "column": "Driven",
        "section": "Automobiles",
        "byline": "By TOM VOELK",
        "type": "Article",
        "title": "Video Review: Volvo V90 Cross Country Rolls Into S.U.V. Territory",
        "abstract": "Americans are buying S.U.V.s and crossovers in record numbers, but it’s worth keeping an open mind about Volvo’s station wagon.",
        "published_date": "2017-07-06",
        "source": "The New York Times",
        "id": 100000005194798,
        "asset_id": 100000005194798,
        "views": 4,
        "des_facet": [
            "AUTOMOBILES"
        ],
        "org_facet": [
            "VOLVO CAR CORP"
        ],
        "per_facet": "",
        "geo_facet": "",
        "media": ""
    },
    {
        "url": "https://www.nytimes.com/2017/06/08/automobiles/saab-autos-cars.html",
        "adx_keywords": "Automobiles;Saab Automobile AB;Bankruptcies;Portland (Ore)",
        "column": "Wheels",
        "section": "Automobiles",
        "byline": "By NICK KURCZEWSKI",
        "type": "Article",
        "title": "In Portland, a Rare Outpost for Die-Hard Saab Fans",
        "abstract": "The Swedish automaker filed for bankruptcy in 2011, leaving a vanishingly small number of dealerships for fans of the company.",
        "published_date": "2017-06-08",
        "source": "The New York Times",
        "id": 100000005095241,
        "asset_id": 100000005095241,
        "views": 5,
        "des_facet": [
            "AUTOMOBILES",
            "BANKRUPTCIES"
        ],
        "org_facet": [
            "SAAB AUTOMOBILE AB"
        ],
        "per_facet": "",
        "geo_facet": [
            "PORTLAND (ORE)"
        ],
        "media": [
            {
                "type": "image",
                "subtype": "photo",
                "caption": "Saab filed for bankruptcy in 2011, but Garry Small Saab in Portland, Ore., has continued to service and sell the brand’s cars.",
                "copyright": "Amanda Lucier for The New York Times",
                "approved_for_syndication": 1,
                "media-metadata": [
                    {
                        "url": "https://static01.nyt.com/images/2017/06/08/business/09WHEELS1/09WHEELS1-thumbStandard.jpg",
                        "format": "Standard Thumbnail",
                        "height": 75,
                        "width": 75
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/08/business/09WHEELS1/09WHEELS1-mediumThreeByTwo210.jpg",
                        "format": "mediumThreeByTwo210",
                        "height": 140,
                        "width": 210
                    },
                    {
                        "url": "https://static01.nyt.com/images/2017/06/08/business/09WHEELS1/09WHEELS1-mediumThreeByTwo440.jpg",
                        "format": "mediumThreeByTwo440",
                        "height": 293,
                        "width": 440
                    }
                ]
            }
        ]
    }
]

}

Type Adapter's read method

public List
 read(JsonReader in) throws IOException {

    final List
 article_list = new ArrayList<>();
    in.beginObject();
    while(in.hasNext()){
        switch (in.nextName()){
            case "results":
                in.beginArray();
                while(in.hasNext()){
                    final Article article = new Article();
                    in.beginObject();
                    while (in.hasNext()){
                        switch (in.nextName()){

                            case "id":
                                article.setId(Long.valueOf(in.nextString()));
                                break;
                            case "title":
                                article.setTitle(in.nextString());
                                break;
                            case "url":
                                article.setUrl(in.nextString());
                                break;
                            case "adx_keywords":
                                article.setAdxKeywords(in.nextString());
                                break;
                            case "section":
                                article.setSection(in.nextString());
                                break;
                            case "byline":
                                article.setByline(in.nextString());
                                break;
                            case "abstract":
                                article.set_abstract(in.nextString());
                                break;
                            case "published_date":
                                article.setPublishedDate(in.nextString());
                                break;
                            case "media":
                                if(!in.peek().equals(JsonToken.BEGIN_ARRAY)){
                                    in.skipValue();
                                    break;
                                }
                                in.beginArray();
                                final ArrayList<Media> media_list = new ArrayList<>();
                                while(in.hasNext()){
                                    in.beginObject();
                                    while(in.hasNext()){
                                        switch (in.nextName()){
                                            case "media-metadata":
                                                in.beginArray();
                                                while(in.hasNext()){
                                                    in.beginObject();
                                                    final Media media = new Media();
                                                    while(in.hasNext()){
                                                        switch (in.nextName()){
                                                            case "url":
                                                                media.setUrl(in.nextString());
                                                                break;
                                                            case "format":
                                                                media.setFormat(in.nextString());
                                                                break;
                                                            default:
                                                                in.skipValue();
                                                                break;
                                                        }
                                                    }
                                                    in.endObject();
                                                    media_list.add(media);
                                                }
                                                in.endArray();
                                                break;
                                            default:
                                                in.skipValue();
                                                break;
                                        }
                                    }
                                    in.endObject();
                                }
                                in.endArray();
                                for(Media m : media_list){
                                    if(m.getFormat().equals("mediumThreeByTwo440")){
                                        article.setMedia(m);
                                        break;
                                    }
                                }
                                break;

                            default:
                                in.skipValue();
                                break;
                        }/**/
                    }
                    in.endObject();
                    article_list.add(article);
                }
                in.endArray();
                break;
            default:
                in.skipValue();
                break;

        }

    }
    in.endObject();

    Timber.d(article_list.toString());
    return article_list;
}

Article and Media classes (no methods)

public class Article {
private Long id;
private String url;
private String adxKeywords;
private String section;
private String byline;
private String title;
private String _abstract;
private String publishedDate;
private Media media;
}

public class Media {
private String url;
private String format;
}

Retrofit Builder

final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Article.class,new ArticleTypeAdapter());
    final Gson gson = gsonBuilder.create();
    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

Body:
You need do something like this:-

public class Response{
    public String status;
    public String copyright;
    public int num_results;
    public Article[] results;
}

You have to pass a response class with the same structure of response you are receiving from the server.
Please follow the steps:-

You don't required a different type adapter for each request you can simply create the retrofit with default Gson converter factory like this:-

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Now you need to define a Service for API request like this:-

public class ArticleService{
   @GET("endpoint")//What ever is your request type
   Call<Response> getArticals(/** body query param or other required data**// )
}

After that you request creation will be something like this:-

ArticleService service = retrofit.create(ArticleService.class);


问:
Textfield in Custom Table View Cell dissappears from initial textfield and appears in other cells textfield upon scrolling
```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"inventoryItem";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.textLabel.font = [UIFont systemFontOfSize:15];

}
 UILabel *name = (UILabel *)[cell viewWithTag:1];

NSLog(@"%@", name.text);

cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return inventoryItems.count;
}
</code>```

I realize this is to do with the dequeueReuasableCellWithIdentifier but I am unsure on how to solve this. I have the textfield on storyboard and then I have an action to send all these textfields  with respect to their cells to a database. The code for the textfield is in the IBAction to send the data and am storing. I will add the IBAction code :

```<code> - (IBAction)submitCountTapped:(id)sender {

NSMutableDictionary *dic;

if(inventoryItems.count>0){
    NSMutableArray *prods = [[NSMutableArray alloc] init];

    for (int a=0; a<inventoryItems.count; a++) {

        if([inventoryItems[a] objectForKey:@"InventoryID"]!=nil){

            UITableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:a inSection:0]];

            UITextField *countTextfield = (UITextField *)[cell viewWithTag:4];

            double countValue = [countTextfield.text doubleValue];

            NSNumber *count = [NSNumber numberWithDouble:countValue];

            dic = [NSMutableDictionary dictionaryWithObjectsAndKeys: [self fetchDict:@"CustomerData"][@"User_ID"], @"User_ID", count, @"manual_quantity", inventoryItems[a][@"InventoryID"], @"InventoryID", nil];

            [prods addObject:dic];
        }
    }

    NSDictionary *outerDic = @{@"Data":prods};

    if([self isInternet]){

        [self fetchPostAddress:[NSString stringWithFormat:@"http://localhost/Backend/webservice/set-inventory-manually.php"] andParameter:[self jsonconvert:outerDic]andIdentifier:@"manualInventory"];

    }
}
</code>```

}

答:
Create a Custom UITableViewCell class from custom Cell.

In  tableView: cellForRowAtIndexPath:

```<code>ConditionTableViewCell *objCell = (ConditionTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"conditionCell"];
objCell.countTextfield.text = @"Your text";
return objCell;
</code>```

Body:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"inventoryItem";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.textLabel.font = [UIFont systemFontOfSize:15];

}
 UILabel *name = (UILabel *)[cell viewWithTag:1];

NSLog(@"%@", name.text);

cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return inventoryItems.count;
}

I realize this is to do with the dequeueReuasableCellWithIdentifier but I am unsure on how to solve this. I have the textfield on storyboard and then I have an action to send all these textfields  with respect to their cells to a database. The code for the textfield is in the IBAction to send the data and am storing. I will add the IBAction code :

 - (IBAction)submitCountTapped:(id)sender {

NSMutableDictionary *dic;

if(inventoryItems.count>0){
    NSMutableArray *prods = [[NSMutableArray alloc] init];

    for (int a=0; a<inventoryItems.count; a++) {

        if([inventoryItems[a] objectForKey:@"InventoryID"]!=nil){

            UITableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:a inSection:0]];

            UITextField *countTextfield = (UITextField *)[cell viewWithTag:4];

            double countValue = [countTextfield.text doubleValue];

            NSNumber *count = [NSNumber numberWithDouble:countValue];

            dic = [NSMutableDictionary dictionaryWithObjectsAndKeys: [self fetchDict:@"CustomerData"][@"User_ID"], @"User_ID", count, @"manual_quantity", inventoryItems[a][@"InventoryID"], @"InventoryID", nil];

            [prods addObject:dic];
        }
    }

    NSDictionary *outerDic = @{@"Data":prods};

    if([self isInternet]){

        [self fetchPostAddress:[NSString stringWithFormat:@"http://localhost/Backend/webservice/set-inventory-manually.php"] andParameter:[self jsonconvert:outerDic]andIdentifier:@"manualInventory"];

    }
}

}

Body:
Create a Custom UITableViewCell class from custom Cell.

In  tableView: cellForRowAtIndexPath:

ConditionTableViewCell *objCell = (ConditionTableViewCell *) [tableView dequeueReusableCellWithIdentifier:@"conditionCell"];
objCell.countTextfield.text = @"Your text";
return objCell;


问:
Sidekiq worker shutdown
I have got strange errors

```<code>2016-07-15T14:34:09.334Z 16484 TID-33ld0 WARN: Terminating 1 busy worker threads
2016-07-15T14:34:09.334Z 16484 TID-33ld0 WARN: Work still in progress [#<struct Sidekiq::BasicFetch::UnitOfWork queue="queue:load_xml", job="{\"class\":\"GuitarmaniaWorker\",\"args\":[],\"retry\":false,\"queue\":\"load_xml\",\"jid\":\"56c01b371c3ee077c2ccf440\",\"created_at\":1468590072.35382,\"enqueued_at\":1468590072.3539252}">]
2016-07-15T14:34:09.334Z 16484 TID-33ld0 DEBUG: Re-queueing terminated jobs
2016-07-15T14:34:09.335Z 16484 TID-33ld0 INFO: Pushed 1 jobs back to Redis
2016-07-15T14:34:09.336Z 16484 TID-33ld0 INFO: Bye!
</code>```

What can cause it?

Locally all work great but after deployment on production server this errors appeared.

Any suggestions.

答:
This means the Sidekiq is being shut down. In the event of a normal "kill" operation (TERM signal), Sidekiq server will attempt to shutdown gracefully by waiting 8 seconds for jobs to be complete. It will then stop the job execution and re-queue for the next time the server starts.

That begs the question, why is your Sidekiq shutting down. Possible reasons are: you on command-line or a script killed the process; you or your data host shut down the machine; your OS ran out of memory. The last reason is the most likely if you're not sure of the cause.

If the memory leak occurs soon after startup, you may be running too many Sidekiq processes and/or your machine may not have enough memory to load the app. If the message happens after some time, it's possible you have a memory leak - run free periodically after starting Sidekiq to see if memory usage scales up, which would indicate a leak. Sometimes a memory leak is due to a library, sometimes it's your own application. More about tracking down leaks in Ruby here.

Title: Sidekiq worker shutdown

Body:
I have got strange errors

2016-07-15T14:34:09.334Z 16484 TID-33ld0 WARN: Terminating 1 busy worker threads
2016-07-15T14:34:09.334Z 16484 TID-33ld0 WARN: Work still in progress [#<struct Sidekiq::BasicFetch::UnitOfWork queue="queue:load_xml", job="{\"class\":\"GuitarmaniaWorker\",\"args\":[],\"retry\":false,\"queue\":\"load_xml\",\"jid\":\"56c01b371c3ee077c2ccf440\",\"created_at\":1468590072.35382,\"enqueued_at\":1468590072.3539252}">]
2016-07-15T14:34:09.334Z 16484 TID-33ld0 DEBUG: Re-queueing terminated jobs
2016-07-15T14:34:09.335Z 16484 TID-33ld0 INFO: Pushed 1 jobs back to Redis
2016-07-15T14:34:09.336Z 16484 TID-33ld0 INFO: Bye!

What can cause it?

Locally all work great but after deployment on production server this errors appeared.

Any suggestions.


问:
DART async/await not waiting
So I've been working on experimenting with DART (whereby my core languages are C++, and embedded C derivates). Hence my code is probably not pretty as I'm more of a procedural programmer, but I'm getting by and learning... I've been struggling around Futures pertaining to await sync, and basically, I simply can't get DART to WAIT. The following code establishes a socket connection to a small embedded device and extracts info. That all works, but notice the order of operations SHOULD be main() gets some info from the console, then should call the method cardStatus to run off and get the info from the embedded device via the socket connection. This is where the await should occur. When the Future is returned, it should go off to the printstuff() method. I've added print statements that should go in order and read:

This should print 1st

This should print 2nd

This should print 3rd

Instead since the wait is not occurring on the cardstatus call (which is time consuming), I get:

This should print 1st

This should print 3rd

This should print 2nd

I've followed another thread on the use of async, and seem to be at least following one solid way of using this Other thread (I tried a .then with a completer with a similar result, so there is something core I feel I'm missing).. but I've been stuck on this for a week.

Code below, along with the console output.

```<code>import 'dart:io';
import 'dart:async' show Future;

const String STATUS = "#111111;";

String defaultIP = "10.1.14.202";
int defaultConfigPort = 5111;
int defaultControlPort = 6722;

var card = new Map();

getInput(String defaults) {
  String takenin = stdin.readLineSync();
  if (takenin == '') takenin = defaults;
  return takenin;
}

Future main() async {
  stdout.write('What is the IP address of the card ($defaultIP): ');
  String ipaddress = getInput(defaultIP);
  defaultIP = ipaddress;
  print ("This should print 1st");
  stdout.writeln("Connecting to $defaultIP");
  await cardStatus(defaultIP, defaultConfigPort, STATUS, card);
  printstuff();
}

printstuff() {
  stdout.writeln(card['subnet']);
  print ("This should print 3rd");
}
Future cardStatus(String ip, int port, String message, Map card) {
  return new Future.delayed(Duration.ZERO, () {
    Socket.connect(ip, port).then((socket) {
      print('Connected to: '
          '${socket.remoteAddress.address}:${socket.remotePort}');

      socket.listen((data) {
        print(new String.fromCharCodes(data).trim());
        List str1 = (new String.fromCharCodes(data).trim().split(','));
        print(str1);
        print ("This should print 2nd");
        //var card = new Map();
        card['ip'] = str1[0];
        card['subnet'] = str1[1];
        card['gateway'] = str1[2];
        card['unknown'] = str1[3];
        card['persist'] = str1[4] == 'true';
        card['build'] = str1[5];
        card['serial'] = str1[6].substring(0, 14);
        card['cloudpassword'] = str1[6].substring(14, 20);
        card['DNS'] = str1[7];
        card['cloudhost'] = str1[8];
        card['cloudenabled'] = str1[9] == 'true';
        print(card['ip']);
      },
          onDone: () {
            print("Done");
            socket.destroy();
          });

//Send the request
      socket.write(message);
    });
  });
}
</code>```

and this is the current console output. notice the null shouldn't be a null if the cardStatus would have completed it would be printed str1.

```<code>What is the IP address of the card (10.1.14.202):
This should print 1st
Connecting to 10.1.14.202
null
This should print 3rd
Connected to: 10.1.14.202:5111
>10.1.14.202,255.255.255.0,10.1.14.1,,0,435,F44900A60040F8000000,192.168.1.1,connect.tutuuu.com,0;
[>10.1.14.202, 255.255.255.0, 10.1.14.1, , 0, 435, F44900A60040F8000000, 192.168.1.1, connect.tutuuu.com, 0;]
This should print 2nd
10.1.14.202
Done

Process finished with exit code 0
</code>```

Thanks for all the help!

答:
You are missing return before Socket.connect. As it stands now your code just starts connecting but never awaits it through future. I would highly recommend using as much as possible the new await / async syntax.

Here is a running example that does get google homepage:

```<code>import 'dart:io';
import 'dart:async' show Future;

Future main() async {
  print("This should print 1st");
  await cardStatus('www.google.com', 80, 'GET /\nHTTP 1.1\n\n');
  printstuff();
}

printstuff() {
  print("This should print 3rd");
}

Future cardStatus(String ip, int port, String message) {
  return new Future.delayed(Duration.ZERO, () {
    return Socket.connect(ip, port).then((socket) {
      print('Connected to: '
          '${socket.remoteAddress.address}:${socket.remotePort}');

      socket.listen((data) {
        List str1 = (new String.fromCharCodes(data).trim().split(','));
        print(str1.first);
        print("This should print 2nd");
      }, onDone: () {
        print("Done");
        socket.destroy();
      }, onError: (e) {
        print("Error while listening: $e");
      });
      socket.write(message);
    });
  });
}
</code>```

Below slightly redacted version that uses awaits, and try / catch to handle errors:

```<code>import 'dart:io';
import 'dart:async' show Future;

Future main() async {
  print("This should print 1st");
  await cardStatus('www.google.com', 80, 'GET /\nHTTP 1.1\n\n');
  print("This should print 3rd");
}

Future<String> cardStatus(String ip, int port, String message) async {
  var socket = await Socket.connect(ip, port);
  print('Connected to: '
      '${socket.remoteAddress.address}:${socket.remotePort}');
  socket.write(message);
  print("Sent request");
  try {
    var response = await socket.fold(
        '',
        (String acc, List<int> data) =>
            acc + new String.fromCharCodes(data).trim());
    print("Received response: ${response.substring(0, 10)}");
    return response;
  } finally {
    socket.close();
  }
}
</code>```

Title: DART async/await not waiting

Body:
So I've been working on experimenting with DART (whereby my core languages are C++, and embedded C derivates). Hence my code is probably not pretty as I'm more of a procedural programmer, but I'm getting by and learning... I've been struggling around Futures pertaining to await sync, and basically, I simply can't get DART to WAIT. The following code establishes a socket connection to a small embedded device and extracts info. That all works, but notice the order of operations SHOULD be main() gets some info from the console, then should call the method cardStatus to run off and get the info from the embedded device via the socket connection. This is where the await should occur. When the Future is returned, it should go off to the printstuff() method. I've added print statements that should go in order and read:

This should print 1st

This should print 2nd

This should print 3rd

Instead since the wait is not occurring on the cardstatus call (which is time consuming), I get:

This should print 1st

This should print 3rd

This should print 2nd

I've followed another thread on the use of async, and seem to be at least following one solid way of using this Other thread (I tried a .then with a completer with a similar result, so there is something core I feel I'm missing).. but I've been stuck on this for a week.

Code below, along with the console output.

import 'dart:io';
import 'dart:async' show Future;

const String STATUS = "#111111;";

String defaultIP = "10.1.14.202";
int defaultConfigPort = 5111;
int defaultControlPort = 6722;

var card = new Map();

getInput(String defaults) {
  String takenin = stdin.readLineSync();
  if (takenin == '') takenin = defaults;
  return takenin;
}

Future main() async {
  stdout.write('What is the IP address of the card ($defaultIP): ');
  String ipaddress = getInput(defaultIP);
  defaultIP = ipaddress;
  print ("This should print 1st");
  stdout.writeln("Connecting to $defaultIP");
  await cardStatus(defaultIP, defaultConfigPort, STATUS, card);
  printstuff();
}

printstuff() {
  stdout.writeln(card['subnet']);
  print ("This should print 3rd");
}
Future cardStatus(String ip, int port, String message, Map card) {
  return new Future.delayed(Duration.ZERO, () {
    Socket.connect(ip, port).then((socket) {
      print('Connected to: '
          '${socket.remoteAddress.address}:${socket.remotePort}');

      socket.listen((data) {
        print(new String.fromCharCodes(data).trim());
        List str1 = (new String.fromCharCodes(data).trim().split(','));
        print(str1);
        print ("This should print 2nd");
        //var card = new Map();
        card['ip'] = str1[0];
        card['subnet'] = str1[1];
        card['gateway'] = str1[2];
        card['unknown'] = str1[3];
        card['persist'] = str1[4] == 'true';
        card['build'] = str1[5];
        card['serial'] = str1[6].substring(0, 14);
        card['cloudpassword'] = str1[6].substring(14, 20);
        card['DNS'] = str1[7];
        card['cloudhost'] = str1[8];
        card['cloudenabled'] = str1[9] == 'true';
        print(card['ip']);
      },
          onDone: () {
            print("Done");
            socket.destroy();
          });

//Send the request
      socket.write(message);
    });
  });
}

and this is the current console output. notice the null shouldn't be a null if the cardStatus would have completed it would be printed str1.

What is the IP address of the card (10.1.14.202):
This should print 1st
Connecting to 10.1.14.202
null
This should print 3rd
Connected to: 10.1.14.202:5111
>10.1.14.202,255.255.255.0,10.1.14.1,,0,435,F44900A60040F8000000,192.168.1.1,connect.tutuuu.com,0;
[>10.1.14.202, 255.255.255.0, 10.1.14.1, , 0, 435, F44900A60040F8000000, 192.168.1.1, connect.tutuuu.com, 0;]
This should print 2nd
10.1.14.202
Done

Process finished with exit code 0

Thanks for all the help!

Body:
You are missing return before Socket.connect. As it stands now your code just starts connecting but never awaits it through future. I would highly recommend using as much as possible the new await / async syntax.

Here is a running example that does get google homepage:

import 'dart:io';
import 'dart:async' show Future;

Future main() async {
  print("This should print 1st");
  await cardStatus('www.google.com', 80, 'GET /\nHTTP 1.1\n\n');
  printstuff();
}

printstuff() {
  print("This should print 3rd");
}

Future cardStatus(String ip, int port, String message) {
  return new Future.delayed(Duration.ZERO, () {
    return Socket.connect(ip, port).then((socket) {
      print('Connected to: '
          '${socket.remoteAddress.address}:${socket.remotePort}');

      socket.listen((data) {
        List str1 = (new String.fromCharCodes(data).trim().split(','));
        print(str1.first);
        print("This should print 2nd");
      }, onDone: () {
        print("Done");
        socket.destroy();
      }, onError: (e) {
        print("Error while listening: $e");
      });
      socket.write(message);
    });
  });
}

Below slightly redacted version that uses awaits, and try / catch to handle errors:

import 'dart:io';
import 'dart:async' show Future;

Future main() async {
  print("This should print 1st");
  await cardStatus('www.google.com', 80, 'GET /\nHTTP 1.1\n\n');
  print("This should print 3rd");
}

Future<String> cardStatus(String ip, int port, String message) async {
  var socket = await Socket.connect(ip, port);
  print('Connected to: '
      '${socket.remoteAddress.address}:${socket.remotePort}');
  socket.write(message);
  print("Sent request");
  try {
    var response = await socket.fold(
        '',
        (String acc, List<int> data) =>
            acc + new String.fromCharCodes(data).trim());
    print("Received response: ${response.substring(0, 10)}");
    return response;
  } finally {
    socket.close();
  }
}


问:
More than one file was found with OS independent path 'lib/x86/libusb.so'
I am using libusb in my android application. When I am trying to build libusb native library then I get below error message, *.so files generated.

Error:Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
  More than one file was found with OS independent path 'lib/x86/libusb.so'

build.gradle

```<code>import org.apache.tools.ant.taskdefs.condition.Os

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.williams.libusbpoc"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }

    sourceSets.main {
        jniLibs.srcDir 'src/main/libs'
        jni.srcDirs = [] //disable automatic ndk-build call
    }

    // call regular ndk-build(.cmd) script from app directory
    task ndkBuild(type: Exec) {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
        } else {
            commandLine 'ndk-build', '-C', file('src/main').absolutePath
        }
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation ('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile "org.jetbrains.anko:anko-appcompat-v7-commons:$anko_version"
}
</code>```

I am on windows machine. Does anyone know what could be the issue ?

答:
I removed jniLibs.srcDir 'src/main/libs' code inside sourceSets.main block. It was creating *.so files twice.

```<code>sourceSets.main {
    jniLibs.srcDir 'src/main/libs'
    jni.srcDirs = [] //disable automatic ndk-build call
}
</code>```

Body:
I am using libusb in my android application. When I am trying to build libusb native library then I get below error message, *.so files generated.

Error:Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
  More than one file was found with OS independent path 'lib/x86/libusb.so'

build.gradle

import org.apache.tools.ant.taskdefs.condition.Os

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.williams.libusbpoc"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }

    sourceSets.main {
        jniLibs.srcDir 'src/main/libs'
        jni.srcDirs = [] //disable automatic ndk-build call
    }

    // call regular ndk-build(.cmd) script from app directory
    task ndkBuild(type: Exec) {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
        } else {
            commandLine 'ndk-build', '-C', file('src/main').absolutePath
        }
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation ('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.0-beta2'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    compile "org.jetbrains.anko:anko-appcompat-v7-commons:$anko_version"
}

I am on windows machine. Does anyone know what could be the issue ?

Body:
I removed jniLibs.srcDir 'src/main/libs' code inside sourceSets.main block. It was creating *.so files twice.

sourceSets.main {
    jniLibs.srcDir 'src/main/libs'
    jni.srcDirs = [] //disable automatic ndk-build call
}


问:
Upgrading rsync on OS X using Homebrew
The rsync version on my OS X (10.10.3) is an old one, 2.6.9.  I've tried to upgrade it using Homebrew but I get the following error:

```<code>Error: No available formula for rsync
</code>```

The new one is supposed to be 3.0+ and much quicker, but how do I install this without deleting the old one?

答:
Warning: homebrew/dupes was deprecated. This tap is now empty as all
  its formulae were migrated.

Title: Upgrading rsync on OS X using Homebrew

Body:
The rsync version on my OS X (10.10.3) is an old one, 2.6.9.  I've tried to upgrade it using Homebrew but I get the following error:

Error: No available formula for rsync

The new one is supposed to be 3.0+ and much quicker, but how do I install this without deleting the old one?