问:
React Native Android device throws error for Fetch while uploading a json file : TypeError: Network request failed
I have written code to call Fetch method to  Post Json file to IPFS .
I am writing the  JSON file locally  which succeds , but later when i call the POST method  using FORMDATA to write json file to IPFS it fails.
Same code works fine on iOS . Not sure what is the issue with Android.

Also tried using IP of the server , using  xmlhttprequest , different options for setting cors/no-cors etc but still  getting the same error .

I am using Android version 8.0, Reactnative version 0.57 and  "react-native-fs": "^2.13.3".
Can somebody suggest an alternate way to make network calls.Cant use native code as this code is in JS library.Kindly provide your valuable feedback.
Below is the code snippet :

```<code>justcall(valueToWrite){
  var path = RNFS.DocumentDirectoryPath + '/writeddo.json';
   //var path =  RNFS.LibraryDirectoryPath + '/writeddo.json';
    console.log("path",path);
    return new Promise((resolve, reject) => {
     // write the file
     RNFS.writeFile(path, valueToWrite,'utf8')
       .then((success) => {
         console.log('FILE WRITTEN!');
         let formdata = new FormData();
         formdata.append('file', {
           uri: path,
           name: 'writeddo.json',
           type: 'multipart/form-data'
         });
         console.log("formdata",formdata);
         console.log("IPFSADD Url",IPFSADD);

           fetch(IPFSADD, {
             method: 'POST',
             headers: {
              // 'Accept': 'application/json',
              'Content-Type': 'multipart/form-data',
             },
             //mode: "no-cors",  //, cors, *same-origin
             body: formdata
            })
            // .then((serviceResponse) => { return serviceResponse.json() } )
             .then((serviceResponse) => {
             console.log("Justcall response", serviceResponse);
                return this.deleteJsonFile(path).then(() => {
                    resolve(serviceResponse)
                })
                .catch((error) => {
                  console.error("Error while deleting the file error:", error)
                  reject(new Error(error))
                })
            })
           .catch((error) => {
            console.error("fetch error:", error)
            reject(new Error(error))
            })

        }) // Write File
       .catch((err) => {
         console.log("Error while writing file locally" +err.toString());
         reject(new Error(err))
       });
     }) //Promise
}

fetch error: TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394)
    at XMLHttpRequest.js:507
    at RCTDeviceEventEmitter.emit (EventEmitter.js:190)
    at MessageQueue.__callFunction (MessageQueue.js:349)
    at MessageQueue.js:106
    at MessageQueue.__guard (MessageQueue.js:297)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)
</code>```

答:
I solved this issue by using RNFetchBlob to POST the file with  below code :</p>

```<code>uploadToIPFS(valueToWrite , filename ,name) {
  var path = RNFS.DocumentDirectoryPath + '/'+filename;
  console.log("path",path);
  let newValueToWrite =  Buffer.from(valueToWrite).toString('base64');
  return new Promise((resolve, reject) => {
    // write the file to IPFS
        RNFetchBlob.fetch('POST',IPFSADD, {
           'Content-Type' :  'application/json', //'multipart/form-data',
         }, [
          { name : 'name', filename : filename, data: newValueToWrite},
        ])
        .then(fetchBlobResponse => {
                  console.log("[IPFS backup] UPLOAD response!", fetchBlobResponse);
                  // Ensure we have `data` and a 200 response
                  if (
                    fetchBlobResponse.data &&
                    fetchBlobResponse.respInfo &&
                    fetchBlobResponse.respInfo.status === 200
                  ) {
                    console.log("[IPFS backup] UPLOAD SUCCESS!");
                    const responseData = JSON.parse(fetchBlobResponse.data);
                    console.log(
                      "[IPFS Response " +
                      responseData
                    );
                    resolve(fetchBlobResponse.data)
                  } else {
                    reject (new Error("[IPFS backup] Upload failure! HTTP status: " +
                        fetchBlobResponse.respInfo.status));
                  }
                });
    }) //Promise
}
</code>```

Body:
I have written code to call Fetch method to  Post Json file to IPFS .
I am writing the  JSON file locally  which succeds , but later when i call the POST method  using FORMDATA to write json file to IPFS it fails.
Same code works fine on iOS . Not sure what is the issue with Android.

Also tried using IP of the server , using  xmlhttprequest , different options for setting cors/no-cors etc but still  getting the same error .

I am using Android version 8.0, Reactnative version 0.57 and  "react-native-fs": "^2.13.3".
Can somebody suggest an alternate way to make network calls.Cant use native code as this code is in JS library.Kindly provide your valuable feedback.
Below is the code snippet :

justcall(valueToWrite){
  var path = RNFS.DocumentDirectoryPath + '/writeddo.json';
   //var path =  RNFS.LibraryDirectoryPath + '/writeddo.json';
    console.log("path",path);
    return new Promise((resolve, reject) => {
     // write the file
     RNFS.writeFile(path, valueToWrite,'utf8')
       .then((success) => {
         console.log('FILE WRITTEN!');
         let formdata = new FormData();
         formdata.append('file', {
           uri: path,
           name: 'writeddo.json',
           type: 'multipart/form-data'
         });
         console.log("formdata",formdata);
         console.log("IPFSADD Url",IPFSADD);

           fetch(IPFSADD, {
             method: 'POST',
             headers: {
              // 'Accept': 'application/json',
              'Content-Type': 'multipart/form-data',
             },
             //mode: "no-cors",  //, cors, *same-origin
             body: formdata
            })
            // .then((serviceResponse) => { return serviceResponse.json() } )
             .then((serviceResponse) => {
             console.log("Justcall response", serviceResponse);
                return this.deleteJsonFile(path).then(() => {
                    resolve(serviceResponse)
                })
                .catch((error) => {
                  console.error("Error while deleting the file error:", error)
                  reject(new Error(error))
                })
            })
           .catch((error) => {
            console.error("fetch error:", error)
            reject(new Error(error))
            })

        }) // Write File
       .catch((err) => {
         console.log("Error while writing file locally" +err.toString());
         reject(new Error(err))
       });
     }) //Promise
}

fetch error: TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (whatwg-fetch.js:504)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:580)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:394)
    at XMLHttpRequest.js:507
    at RCTDeviceEventEmitter.emit (EventEmitter.js:190)
    at MessageQueue.__callFunction (MessageQueue.js:349)
    at MessageQueue.js:106
    at MessageQueue.__guard (MessageQueue.js:297)
    at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:105)

Body:
I solved this issue by using RNFetchBlob to POST the file with  below code :

uploadToIPFS(valueToWrite , filename ,name) {
  var path = RNFS.DocumentDirectoryPath + '/'+filename;
  console.log("path",path);
  let newValueToWrite =  Buffer.from(valueToWrite).toString('base64');
  return new Promise((resolve, reject) => {
    // write the file to IPFS
        RNFetchBlob.fetch('POST',IPFSADD, {
           'Content-Type' :  'application/json', //'multipart/form-data',
         }, [
          { name : 'name', filename : filename, data: newValueToWrite},
        ])
        .then(fetchBlobResponse => {
                  console.log("[IPFS backup] UPLOAD response!", fetchBlobResponse);
                  // Ensure we have `data` and a 200 response
                  if (
                    fetchBlobResponse.data &&
                    fetchBlobResponse.respInfo &&
                    fetchBlobResponse.respInfo.status === 200
                  ) {
                    console.log("[IPFS backup] UPLOAD SUCCESS!");
                    const responseData = JSON.parse(fetchBlobResponse.data);
                    console.log(
                      "[IPFS Response " +
                      responseData
                    );
                    resolve(fetchBlobResponse.data)
                  } else {
                    reject (new Error("[IPFS backup] Upload failure! HTTP status: " +
                        fetchBlobResponse.respInfo.status));
                  }
                });
    }) //Promise
}


来源: stackexchange

问:
How to use a declared variable that contains a table name, as a join in a for loop. Oracle PL/SQL
The name of a materialized view I want to use as part of some SQL in a stored procedure, is held within a table. I need to get the name of the table stored in a variable so that the procedure can use it. The part that will receive the table name is in a for loop. How can I use a variable in the loop?

This is an example of what I mean:

```<code>declare
l_dblink varchar2(100) := 'DB1';
V_MV_NAME varchar2(2000);

begin

SELECT mv_name into V_MV_NAME
FROM track_mv
WHERE
CREATED_AT = (select MAX(CREATED_AT) from track_mv);

for rws in (

  select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2)  TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
    from dba_tables@DB1 a, MAT_VIEW_ANON b
    where a.table_name = b.segment_name

and a.table_name in
(select table_name from BOB_TABLE where driver_table is null)
and a.owner in (select distinct schema from BOB_TABLE c)
group by a.owner,a.table_name
order by a.table_name
)
loop...
</code>```

Here, V_MV_NAME holds the variable. I want to use that variable in the body of the query:

```<code>for rws in (

  select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2)  TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
    from dba_tables@DB1 a, MAT_VIEW_ANON b
    where a.table_name = b.segment_name
</code>```

So it may read something like this:

```<code>from dba_tables@DB1 a, ||V_MV_NAME|| 'b'
</code>```

Or similar. The code is already in place with the hard coded values. This would be the simplest thing to do if it is possible?

答:
The name of a materialized view I want to use as part of some SQL in a stored procedure, is held within a table

This is a bad idea. It won't scale, you have to switch your code to dynamic SQL which is ugly and hard to maintain. For simple cases it is ... ah, OK, kind of acceptable, but for something like you have - huh, I wouldn't want to do that.

I suggest you find another way.

Why would you want to do it, anyway? Use materialized view name as is, not stored in some table.

ContentLicense: CC BY-SA 4.0

Body:
The name of a materialized view I want to use as part of some SQL in a stored procedure, is held within a table. I need to get the name of the table stored in a variable so that the procedure can use it. The part that will receive the table name is in a for loop. How can I use a variable in the loop?

This is an example of what I mean:

declare
l_dblink varchar2(100) := 'DB1';
V_MV_NAME varchar2(2000);

begin

SELECT mv_name into V_MV_NAME
FROM track_mv
WHERE
CREATED_AT = (select MAX(CREATED_AT) from track_mv);

for rws in (

  select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2)  TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
    from dba_tables@DB1 a, MAT_VIEW_ANON b
    where a.table_name = b.segment_name

and a.table_name in
(select table_name from BOB_TABLE where driver_table is null)
and a.owner in (select distinct schema from BOB_TABLE c)
group by a.owner,a.table_name
order by a.table_name
)
loop...

Here, V_MV_NAME holds the variable. I want to use that variable in the body of the query:

for rws in (

  select /*+parallel (4)*/ a.owner,a.table_name, round(sum(b.sum_bytes),2)  TOT_OBJECT_SIZE_MB, EST_ONE_ROW_MB
    from dba_tables@DB1 a, MAT_VIEW_ANON b
    where a.table_name = b.segment_name

So it may read something like this:

from dba_tables@DB1 a, ||V_MV_NAME|| 'b'

Or similar. The code is already in place with the hard coded values. This would be the simplest thing to do if it is possible?


问:
Does HTML Encoding a mailto tag stop spammers
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

```<code><a href="mailto:newbi...">email me</a>
</code>```

Also, are there any other techniques that I've left out?  Which is the best method?

答: From what I've heard, it will help reduce the influx of spam but will not stop it entirely. A minority (for now) of email-address-harvesting bots are smart enough to apply the decoding.</p>

OwnerDisplayName: bendewey

ContentLicense: CC BY-SA 3.0

Body:
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

email me

Also, are there any other techniques that I've left out?  Which is the best method?

LastEditorDisplayName: bendewey

OwnerDisplayName: David

ContentLicense: CC BY-SA 2.5


问:
getViewByID Returns null for the Listview
I have got my main.xml as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <ListView android:layout_height="wrap_content" android:id="@+id/listView1" android:layout_width="match_parent"></ListView>
</LinearLayout>
</code>```

Now i want to get the ListView with id listView1 in the onCreate event of the activity. Here goes my code to achieve this stuff ..

```<code>public class TwitterClient extends Activity {
    private static ListView mTweetsList;

     @SuppressWarnings("deprecation")
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main); // Set the content view.
            TextView txtView = (TextView)findViewById(R.id.textView1); // This works as expected
            mTweetsList = (ListView)findViewById(R.id.listView1); // This returns null
</code>```

The line to get the list view returns null.

```<code>mTweetsList = (ListView)findViewById(R.id.listView1); -- Does not work and returns null !!
</code>```

where as when i use the same function to find the textview by id in the same layout, it works all fine. Can anyone point me to what might be an error here?

Thanks

答: Have you tried cleaning the project (Eclipse->Project->Clean..)? I have found that sometimes R.java gets messed up.</p>

Body:
I have got my main.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <ListView android:layout_height="wrap_content" android:id="@+id/listView1" android:layout_width="match_parent"></ListView>
</LinearLayout>

Now i want to get the ListView with id listView1 in the onCreate event of the activity. Here goes my code to achieve this stuff ..

public class TwitterClient extends Activity {
    private static ListView mTweetsList;

     @SuppressWarnings("deprecation")
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main); // Set the content view.
            TextView txtView = (TextView)findViewById(R.id.textView1); // This works as expected
            mTweetsList = (ListView)findViewById(R.id.listView1); // This returns null

The line to get the list view returns null.

mTweetsList = (ListView)findViewById(R.id.listView1); -- Does not work and returns null !!

where as when i use the same function to find the textview by id in the same layout, it works all fine. Can anyone point me to what might be an error here?

Thanks


问:
How to change fixed line height
I am trying to figure out how to change the line height of a specific item in a theme. It seems that this item has a fixed minimum line height, which I can't get around.

On https://aerycs.cocoto.eu if you put something into the basket an open the preview (top right corner, green link) theres a red title of the item.

I am not able to find out how to make the line height smaller.

You can see a sample image here: https://imgur.com/DNqRb7m

Appreciate all help!

答:
Change CSS </p>

```<code>.basket-item-container .basket-item .meta-container-wrapper .meta-container-wrapper-inner .meta-container .item-name {
    font-weight: 650;
    font-size: 95%;
    line-height: 1.2;/*Add This*/
    display: block;/*Add This*/
}
</code>```

Title: How to change fixed line height

Body:
Change CSS

.basket-item-container .basket-item .meta-container-wrapper .meta-container-wrapper-inner .meta-container .item-name {
    font-weight: 650;
    font-size: 95%;
    line-height: 1.2;/*Add This*/
    display: block;/*Add This*/
}


问:
Add a missing record into the arraylist if it is not in it
Pardon me as I'm quite a beginner in coding. I have tried researching for ways to add some missing record into the lists but still can't seem to fit it correctly into my code.

I have two ArrayLists with different resultsets. Say, the first one is derived in other method and stored in abcList. This list is then used in my current fixChartStats method as a param.

In my code, I will check for the corresponding record in abcList with the second list I derive from the hql query in fixChartStats method.

If the record corresponds, then I'll do the necessary action as shown below to update the ApprovedCount number etc, else i set it to 0.

How do I go about adding the records that are missing in second list I got into the first arraylist (i.e. abcList)? Can anyone here shed some light? Do let me know if my questions are unclear. Thanks in advance, guys!

```<code>private void fixChartStats(List<TAbcModel> abcList, Map<String, Object> param, List<IssueModel> issueList, List<DestModel> destList) throws Exception {

    //initialize the hql query
    //translate all fields from Object[] into individual variable

    firstRow = true;
    for (TAbcModel abc : abcList) {
        if (abc.getId().getAbcYear() = abcYear &&
                abc.getId().getAbcMonthId() = abcMonthId &&
                abc.getId().getAbcApplAccnId().getAccnId().equalsIgnoreCase(abcApplAccnId.getAccnId()) {

            if (firstRow) {
                abc.setApprovedCount(abcApprovedCount);
                abc.setCancelledCount(abcCancelledCount);
                firstRow = false;
            } else {
                abc.setApprovedCount(0);
                abc.setCancelledCount(0);
            }
        }else{
            // How to do the necessary here
            // Below is what I've tried
            abcList.add(abc);
        }
    }
}
</code>```

When I debug, I noticed that it was added into the list. But soon after it was added, ConcurrentModificationException was thrown.

答:
Create a local list and add missing records to it then add all elements from the local list to the abcList

```<code>List<TAbcModel> temp = new ArrayList<>();
</code>```

in your loop:

```<code>} else {
    temp.add(abc);
}
</code>```

after loop

```<code>abcList.addAll(temp);
</code>```

Body:
Pardon me as I'm quite a beginner in coding. I have tried researching for ways to add some missing record into the lists but still can't seem to fit it correctly into my code.

I have two ArrayLists with different resultsets. Say, the first one is derived in other method and stored in abcList. This list is then used in my current fixChartStats method as a param.

In my code, I will check for the corresponding record in abcList with the second list I derive from the hql query in fixChartStats method.

If the record corresponds, then I'll do the necessary action as shown below to update the ApprovedCount number etc, else i set it to 0.

How do I go about adding the records that are missing in second list I got into the first arraylist (i.e. abcList)? Can anyone here shed some light? Do let me know if my questions are unclear. Thanks in advance, guys!

private void fixChartStats(List<TAbcModel> abcList, Map<String, Object> param, List<IssueModel> issueList, List<DestModel> destList) throws Exception {

    //initialize the hql query
    //translate all fields from Object[] into individual variable

    firstRow = true;
    for (TAbcModel abc : abcList) {
        if (abc.getId().getAbcYear() = abcYear &&
                abc.getId().getAbcMonthId() = abcMonthId &&
                abc.getId().getAbcApplAccnId().getAccnId().equalsIgnoreCase(abcApplAccnId.getAccnId()) {

            if (firstRow) {
                abc.setApprovedCount(abcApprovedCount);
                abc.setCancelledCount(abcCancelledCount);
                firstRow = false;
            } else {
                abc.setApprovedCount(0);
                abc.setCancelledCount(0);
            }
        }else{
            // How to do the necessary here
            // Below is what I've tried
            abcList.add(abc);
        }
    }
}

When I debug, I noticed that it was added into the list. But soon after it was added, ConcurrentModificationException was thrown.

Body:
Create a local list and add missing records to it then add all elements from the local list to the abcList

List<TAbcModel> temp = new ArrayList<>();

in your loop:

} else {
    temp.add(abc);
}

after loop

abcList.addAll(temp);


问:
How to shift side navgitation bar from left to right side in vue js
I want to shift my side nav from left to right side of the window using vue js.

I tried including following css top: 0 and right: 0 but it is not opening on the right side of the navbar.

Unable to solve this problem.

```<code><nav class="navbar navbar-expand-lg bg-dark sticky-top navbar-top" :class="{ navbaropen: opened}">
  <span class="open-slide">
      <a href="#" @click="opened = !opened">
          <div class="con">
              <div class="bar top" :class="{ topopen: opened}"></div>
              <div class="bar mid" :class="{ midopen: opened}"></div>
              <div class="bar bot" :class="{ botopen: opened}"></div>
          </div>
      </a>
  </span>
  </div>
</nav>
<div id="side-menu" class="side-nav" :class="{ sidenavopen: opened}">
    <a href="#">Home</a>
    <a href="#">Contact Us</a>
    <a href="#">Social Media</a>
</div>
.navbaropen{
  background-color: white;
  overflow: hidden;
  height: 63px;
  margin-right: 250px;
}

.navbar a:hover{
  background-color: #ddd;
  color: #000;
}

.side-nav{
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  opacity: 0.9;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.3s;
}

.sidenavopen{
  height: 100%;
  width: 250px;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  opacity: 0.9;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.3s;
}

nav{
  transition: margin-left 0.3s;
}
export default {
    data () {
        return {
            listOne: false,
            listTwo: false,
            opened: false
        }
    }
}
</code>```

I want side nav to be opened on the right side while clicking the navigation button.

答:
use left:auto for .side-nav class it will works

```<code>.side-nav{
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  left:auto;
  background-color: #111;
  opacity: 0.9;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.3s;
}
</code>```

Body:
I want to shift my side nav from left to right side of the window using vue js.

I tried including following css top: 0 and right: 0 but it is not opening on the right side of the navbar.

Unable to solve this problem.

    Home
    Contact Us
    Social Media

.navbaropen{
  background-color: white;
  overflow: hidden;
  height: 63px;
  margin-right: 250px;
}

.navbar a:hover{
  background-color: #ddd;
  color: #000;
}

.side-nav{
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  opacity: 0.9;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.3s;
}

.sidenavopen{
  height: 100%;
  width: 250px;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  background-color: #111;
  opacity: 0.9;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.3s;
}

nav{
  transition: margin-left 0.3s;
}
export default {
    data () {
        return {
            listOne: false,
            listTwo: false,
            opened: false
        }
    }
}

I want side nav to be opened on the right side while clicking the navigation button.

Body:
use left:auto for .side-nav class it will works

.side-nav{
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  right: 0;
  left:auto;
  background-color: #111;
  opacity: 0.9;
  overflow-x: hidden;
  padding-top: 60px;
  transition: 0.3s;
}


问:
How to deserialize JSON to IList<KeyValuePair<string, object>> with whitespaces in key?
I have a big problem with deserializing my JSON to an object. It should be deserialized to IList<KeyValuePair<string, object>> the problem is that the keys have white spaces.

```<code>"spec": {
         "SOMETHING WITH SPACES" : "10"
         etc.
         ...
}
</code>```

public class SomeObject
{
...
public IList<KeyValuePair<string, object>> spec{ get; set; }
...
}
```

<p>Deserializing code:</p>

<pre class="lang-cs prettyprint-override"><code>var sr = new ServiceStack.Text.JsonSerializer<SomeObject>();
var esResult = sr.DeserializeFromString(responseJson);
</code>```

responseJson is a GET from ElasticSearch.

What I get to my field it is null.
If I have key without whitespaces it's deserializing normally and I'm getting my IList<KeyValuePair<string, object>>

答:
If you don't mind using Newtonsoft.Json:</p>

```<code>    const string json = @"{""spec"": { ""SOMETHING WITH SPACES"" : ""10"", ""SOMETHING WITH MORE SPACES"" : ""20"" }}";
    dynamic data = JsonConvert.DeserializeObject(json);
    Dictionary<string, string> list = data["spec"].ToObject<Dictionary<string, string>>();
    foreach (var item in list)
    {
        Console.WriteLine(item.Key + ", " + item.Value);
    }
</code>```

Body:
I have a big problem with deserializing my JSON to an object. It should be deserialized to IList<KeyValuePair<string, object>> the problem is that the keys have white spaces.

"spec": {
         "SOMETHING WITH SPACES" : "10"
         etc.
         ...
}

public class SomeObject
{
...
public IList<KeyValuePair<string, object>> spec{ get; set; }
...
}

Deserializing code:

var sr = new ServiceStack.Text.JsonSerializer<SomeObject>();
var esResult = sr.DeserializeFromString(responseJson);

responseJson is a GET from ElasticSearch.

What I get to my field it is null.
If I have key without whitespaces it's deserializing normally and I'm getting my IList<KeyValuePair<string, object>>

Body:
If you don't mind using Newtonsoft.Json:

    const string json = @"{""spec"": { ""SOMETHING WITH SPACES"" : ""10"", ""SOMETHING WITH MORE SPACES"" : ""20"" }}";
    dynamic data = JsonConvert.DeserializeObject(json);
    Dictionary<string, string> list = data["spec"].ToObject<Dictionary<string, string>>();
    foreach (var item in list)
    {
        Console.WriteLine(item.Key + ", " + item.Value);
    }


问:
Obj-C, need to find out if an imageview is inside another imageview?
I'm just wondering if there's some methods which would make it simple to determine if an image view is inside another image view.

In my app theres several imageviews which can be dragged into another larger image view.

So far i think I'll have to check x and y co-ordinates against each object in a loop.

Just thought I'd ask

EDIT
The views will be on top of the larger view.
I need to evaluate locations rather than view hierarchy.

答: Use CGRectIntersectsRect and/or CGRectContainsRect with the frames of your image views.


问:
.child-div overflows .parent-div
guys!

I'm making an own portfolio website. The idea is to make full height pages. So regarding this, I got 2 questions.

How can I make .child-div not larger than its .parent-div?

How can I make p-elements height not larger than its .child-div?

Thinking that there is some (maybe the same) solution to both problems.

Overflow is not an option, because it just hide the rest of element.

I tried to set .parent as display: table and .child as display: table-cell but I didn't succeed.
UPD: Also tried to make an table-row div between .parent and. child width width: 100% and height: 33%. Unfortunately without expected result..

Here is the example how it should look like, but .child overflows the .parent.

html {
  height: 100%;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
}
.parent {
  height: 100%;
  border: 1px solid red;
}
.child-30 {
  min-height: calc(100%/3);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
  min-height: calc(100%/3);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
@media only screen and (max-width: 750px) {
  .child-30, .child-70 {float: left; width: 100%;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
  <div class="child-70 left"></div>
  <div class="child-30 right"></div>
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
</div></code>```

And here is the link how it should look like with paragraphs

Same problem here

答:
Check this out, although it is better if it is full page.
https://jsfiddle.net/indefinite/g7aqvkoy/33/

I removed height:100% in  your .parent
and added

.parent::after{
  content: "";
    clear: both;
  display: table;
}
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  height: 100%;
   padding:10px;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
  padding:10px;
}
.parent {
  border: 1px solid red;
}
.child-30 {
    min-height: calc(100%/3);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
    min-height: calc(100%/3);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
.parent::after{
  content: "";
    clear: both;
  display: table;
}
@media only screen and (max-width: 750px) {
 .parent{
   display:flex;
   flex-direction:column;
 }
.child-30 {
   width: 97%;
}
 .child-70{
   width:97%;

 }
  .parent::after{
  content: "";
    clear: both;
  display: table;
}

}</code>```

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

```

Title: .child-div overflows .parent-div

Body:
guys!

I'm making an own portfolio website. The idea is to make full height pages. So regarding this, I got 2 questions.

How can I make .child-div not larger than its .parent-div?

How can I make p-elements height not larger than its .child-div?

Thinking that there is some (maybe the same) solution to both problems.

Overflow is not an option, because it just hide the rest of element.

I tried to set .parent as display: table and .child as display: table-cell but I didn't succeed.
UPD: Also tried to make an table-row div between .parent and. child width width: 100% and height: 33%. Unfortunately without expected result..

Here is the example how it should look like, but .child overflows the .parent.

html {
  height: 100%;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
}
.parent {
  height: 100%;
  border: 1px solid red;
}
.child-30 {
  min-height: calc(100%/3);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
  min-height: calc(100%/3);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
@media only screen and (max-width: 750px) {
  .child-30, .child-70 {float: left; width: 100%;}
}

And here is the link how it should look like with paragraphs

Same problem here

Body:
Check this out, although it is better if it is full page.
https://jsfiddle.net/indefinite/g7aqvkoy/33/

I removed height:100% in  your .parent
and added

.parent::after{
  content: "";
    clear: both;
  display: table;
}

html {
  height: 100%;
   padding:10px;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
  padding:10px;
}
.parent {
  border: 1px solid red;
}
.child-30 {
    min-height: calc(100%/3);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
    min-height: calc(100%/3);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
.parent::after{
  content: "";
    clear: both;
  display: table;
}
@media only screen and (max-width: 750px) {
 .parent{
   display:flex;
   flex-direction:column;
 }
.child-30 {
   width: 97%;
}
 .child-70{
   width:97%;

 }
  .parent::after{
  content: "";
    clear: both;
  display: table;
}

}

<div class="parent clearfix">
  <div class="child-30 left">
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
  </div>
  <div class="child-70 right">
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
  </div>
  <div class="child-70 left">
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
  </div>
  <div class="child-30 right">
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
  </div>
  <div class="child-30 left">
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
  </div>
  <div class="child-70 right">
    <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </p>
  </div>
</div>
<br/><br/>


问:
How to use operators in array of wheres
I'm trying to use => operator in a array of wheres
but the query is using the operator as the binding

```<code>Model::updateOrCreate([
        ['client_id', $client->id],
        ['created_at', '=>', '2019-05-01 00:00:00',],
    ],
    [
        'client_id' => $client->id,
    ]
);
</code>```

This does not work, the query looks like this

```<code>[
    "query"    =>
        "select * from `models` where (`client_id` = ? and `created_at` = ?) limit 1",
    "bindings" => [
        0 => 5,
        1 => "=>",
    ],
];
</code>```

I searched the web and could not find the proper documentation for the function
addArrayOfWheres

Thank you.

答:
=> is not a valid operator for clauses, you should use >=.

A full list of allowed operators can be found in the source code.

```<code>/**
 * All of the available clause operators.
 *
 * @var array
 */
public $operators = [
    '=', '<', '>', '<=', '>=', '<>', '!=', '<=>',
    'like', 'like binary', 'not like', 'ilike',
    '&', '|', '^', '<<', '>>',
    'rlike', 'regexp', 'not regexp',
    '~', '~*', '!~', '!~*', 'similar to',
    'not similar to', 'not ilike', '~~*', '!~~*',
];
</code>```

Title: How to use operators in array of wheres

Body:
I'm trying to use => operator in a array of wheres
but the query is using the operator as the binding

Model::updateOrCreate([
        ['client_id', $client->id],
        ['created_at', '=>', '2019-05-01 00:00:00',],
    ],
    [
        'client_id' => $client->id,
    ]
);

This does not work, the query looks like this

[
    "query"    =>
        "select * from `models` where (`client_id` = ? and `created_at` = ?) limit 1",
    "bindings" => [
        0 => 5,
        1 => "=>",
    ],
];

I searched the web and could not find the proper documentation for the function
addArrayOfWheres

Thank you.

Body:
=> is not a valid operator for clauses, you should use >=.

A full list of allowed operators can be found in the source code.

/**
 * All of the available clause operators.
 *
 * @var array
 */
public $operators = [
    '=', '<', '>', '<=', '>=', '<>', '!=', '<=>',
    'like', 'like binary', 'not like', 'ilike',
    '&', '|', '^', '<<', '>>',
    'rlike', 'regexp', 'not regexp',
    '~', '~*', '!~', '!~*', 'similar to',
    'not similar to', 'not ilike', '~~*', '!~~*',
];


问:
RN code-push: testing component that hooks into codePushStatusDidChange
I'm using the react-native-code-push codePush HOC, and running some logic in response to a codePushStatusDidChange event hook, in particular, when the status is SyncStatus.UPDATE_INSTALLED.

I haven't had luck finding out whether there is a way to emulate code push events when running in dev mode, to verify that our code is responding properly to the event hook.  Is this possible, or is it necessary to release new versions to the code push server?

Side question: if the installMode is set to codePush.InstallMode.ON_NEXT_SUSPEND, is the event hook supposed to receive a SyncStatus.UPDATE_INSTALLED on the next restart? (I suppose once I can get the first question figured out, I can answer the second one on my own!).

答:
@twelve17 Hi.
I can share my experience regarding testing & CodePush usage.
We have both e2e tests (detox + jet) and unit tests (react-native-test-utils + jest).
When we run our e2e tests we specify the environment and switch codePush setting in the root HOC:

checkFrequency: isTest()
    ? codePush.CheckFrequency.MANUAL
    : codePush.CheckFrequency.ON_APP_START,
```

In this case (manual check & update), codePush doesn't do anything while the app is running. It works fine with e2e testing because you really don't need any codePush tasks while running them, definitely.

Regarding unit tests: we don't test the HOC itself (for now), we've just covered only some stateless components, so here I can only recommend you either skip such tests (because codePush is the 3rd-party lib) or write your own wrapper for any of its commands and mock/stub them in case of tests are running.

Body:
@twelve17 Hi.
I can share my experience regarding testing & CodePush usage.
We have both e2e tests (detox + jet) and unit tests (react-native-test-utils + jest).
When we run our e2e tests we specify the environment and switch codePush setting in the root HOC:

checkFrequency: isTest()
    ? codePush.CheckFrequency.MANUAL
    : codePush.CheckFrequency.ON_APP_START,

In this case (manual check & update), codePush doesn't do anything while the app is running. It works fine with e2e testing because you really don't need any codePush tasks while running them, definitely.

Regarding unit tests: we don't test the HOC itself (for now), we've just covered only some stateless components, so here I can only recommend you either skip such tests (because codePush is the 3rd-party lib) or write your own wrapper for any of its commands and mock/stub them in case of tests are running.


问:
Optional but mutually exclusive switches in a function
I want to write a function in a custom powershell module that can defines some switches.

The function should be call aither with no switch at all, or with one switch. Multiple switches are not allowed.

Ex:

```<code>Get-Foo -Value "text"                          # Should return "text"
Get-Foo -Value "2019-01-01T00:00:00Z" -AsDate  # Should return the value as date
Get-Foo -Value "42" -AsInteger                 # Should return 42 as integer
Get-Foo -Value "xxx" -AsDate -AsInteger        # Should fail
</code>```

In order to support these cases, I'm playing with parameter sets :

```<code>function Get-Foo{
    param(
        [Parameter(Mandatory=$true)]
        [string]$Value,
        [Parameter(ParameterSetName='AsDate')]
        [Switch]$AsDate,
        [Parameter(ParameterSetName='AsInteger')]
        [Switch]$AsInteger

    )

    switch ($PsCmdlet.ParameterSetName) {
        "AsDate" {
            [datetime]::Parse($Value)
        }
        "AsInteger" {
            [int]::Parse($Value)
        }
        "__AllParameterSets" {
            $Value
        }
    }
}
</code>```

However, this does not works as expected. Passing one of the two switches works. Passing the two switches fails (but it's intended).

PAssing no switch at all fails, because it can't resolve the parameter set.

How to fix this ?

答:
If you give the function a DefaultParameterSetName, and change the last switch test to be Default, things should work:

```<code>function Get-Foo {
    [CmdletBinding(DefaultParameterSetName = 'None')]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Value,
        [Parameter(ParameterSetName='AsDate')]
        [Switch]$AsDate,
        [Parameter(ParameterSetName='AsInteger')]
        [Switch]$AsInteger

    )

    switch ($PsCmdlet.ParameterSetName) {
        "AsDate" {
            [datetime]::Parse($Value)
        }
        "AsInteger" {
            [int]::Parse($Value)
        }
        default {
            $Value
        }
    }
}
</code>```

Result:

```<code>Get-Foo -Value "text"                          # Returns "text"
Get-Foo -Value "2019-01-01T00:00:00Z" -AsDate  # Returns the value as date (if Parse() is possible)
Get-Foo -Value "42" -AsInteger                 # Returns 42 as integer (if Parse() is possible)
Get-Foo -Value "xxx" -AsDate -AsInteger        # Fails
</code>```

Note: for more complex Switch() comparisons, consider the break statement to stop the switch from comparing after a match. See about_Switch

Body:
I want to write a function in a custom powershell module that can defines some switches.

The function should be call aither with no switch at all, or with one switch. Multiple switches are not allowed.

Ex:

Get-Foo -Value "text"                          # Should return "text"
Get-Foo -Value "2019-01-01T00:00:00Z" -AsDate  # Should return the value as date
Get-Foo -Value "42" -AsInteger                 # Should return 42 as integer
Get-Foo -Value "xxx" -AsDate -AsInteger        # Should fail

In order to support these cases, I'm playing with parameter sets :

function Get-Foo{
    param(
        [Parameter(Mandatory=$true)]
        [string]$Value,
        [Parameter(ParameterSetName='AsDate')]
        [Switch]$AsDate,
        [Parameter(ParameterSetName='AsInteger')]
        [Switch]$AsInteger

    )

    switch ($PsCmdlet.ParameterSetName) {
        "AsDate" {
            [datetime]::Parse($Value)
        }
        "AsInteger" {
            [int]::Parse($Value)
        }
        "__AllParameterSets" {
            $Value
        }
    }
}

However, this does not works as expected. Passing one of the two switches works. Passing the two switches fails (but it's intended).

PAssing no switch at all fails, because it can't resolve the parameter set.

How to fix this ?

Body:
If you give the function a DefaultParameterSetName, and change the last switch test to be Default, things should work:

function Get-Foo {
    [CmdletBinding(DefaultParameterSetName = 'None')]
    param(
        [Parameter(Mandatory=$true)]
        [string]$Value,
        [Parameter(ParameterSetName='AsDate')]
        [Switch]$AsDate,
        [Parameter(ParameterSetName='AsInteger')]
        [Switch]$AsInteger

    )

    switch ($PsCmdlet.ParameterSetName) {
        "AsDate" {
            [datetime]::Parse($Value)
        }
        "AsInteger" {
            [int]::Parse($Value)
        }
        default {
            $Value
        }
    }
}

Result:

Get-Foo -Value "text"                          # Returns "text"
Get-Foo -Value "2019-01-01T00:00:00Z" -AsDate  # Returns the value as date (if Parse() is possible)
Get-Foo -Value "42" -AsInteger                 # Returns 42 as integer (if Parse() is possible)
Get-Foo -Value "xxx" -AsDate -AsInteger        # Fails

Note: for more complex Switch() comparisons, consider the break statement to stop the switch from comparing after a match. See about_Switch


问:
python re.sub with an integer operation
I currently have a pattern substitution that does the following:

```<code>x = re.sub('(\d+)','\g<1>','100')
=> x = 100
</code>```

I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is there a way to do this so that => x = 10

Thanks,
Richard

答:
```<code>import re

t = 'a b c 100 200'

f = lambda x: str(int(x.group(0)) / 10)
re.sub('\d+', f, t)

# returns 'a b c 10 20'
</code>```

Title: python re.sub with an integer operation

Body:
I currently have a pattern substitution that does the following:

x = re.sub('(\d+)','\g<1>','100')
=> x = 100

I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is there a way to do this so that => x = 10

Thanks,
Richard


问:
Jupyter Notebook in customised docker image is not launching
I have prepared the customised docker image with base image as jupyter/scipy-notebook. But after successfully building the docker image, when I am trying to run it then jupyter is not launching. I have attached the screenshot. I am not able to figure out what is missing and why. I have used norebook.sh to launch jupyter notebook. Codes are shown below:

#!/bin/bash'
# Strict mode
``set -euo pipefail

IFS=$'\n\t'

# Set configuration defaults
: ${PASSWORD:=""}
: ${PEM_FILE:="/key.pem"}
: ${USE_HTTP:=0}

HASH=$(python -c "from IPython.lib import passwd; print(passwd('${PASSWORD}'))")
unset PASSWORD

if [ $USE_HTTP -ne 0 ]; then
  CERTFILE_OPTION=""
else
if [ ! -f $PEM_FILE ]; then
    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout $PEM_FILE -out $PEM_FILE \
      -subj "/C=XX/ST=XX/L=XX/O=dockergenerated/CN=dockergenerated"
fi

CERTFILE_OPTION="--certfile=$PEM_FILE"
fi

jupyter notebook \
    --port 8888 \
    --ip=0.0.0.0 \
    $CERTFILE_OPTION \
    --NotebookApp.password="$HASH" \
        --allow-root

unset HASH

I have taken this script from mayanlab/zika and made some changes as this script use very old versions of jupyter. I also tried with the IP address shown in screenshot as 127.0.0.1:8888  and localhost:8888 but nothing works. Kindly suggest.

.

答:
You are running the container on the host port 8887 (last command), so try http://127.0.0.1:8887 in your browser.

The Port binding syntax in django is -p host_port:container_port, see e.g. Docker Docs


问:
Slide up Animation using ObjectAnimator
I am trying to use ObjectAnimator for slide up translate animation because,  as we know onclicklistener won't work if we use normal translation animation like this,

<translate
    android:duration="1000"
    android:fromYDelta="100%"
    android:toYDelta="10%" />
```

<p>The above xml code works fine but as I said before onclicklistener not working after animation.
I tried ObjectAnimator like the below one </p>

<pre class="lang-java prettyprint-override"><code>ObjectAnimator mover = ObjectAnimator.ofFloat(filterLayout, "translationY", 1.0f, 0.1f);
mover.start();
</code>```

But it doesn't give the same result as translate xml does.

Any help would be appreciated.

答:
I know it's late but, please check the below code and see if works for your case. I took the XML code you shared as a reference to this. </p>

```<code>ObjectAnimator.ofPropertyValuesHolder(
        view,
        PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, 100.0f, 10.0f));
</code>```

Title: Slide up Animation using ObjectAnimator

Body:
I am trying to use ObjectAnimator for slide up translate animation because,  as we know onclicklistener won't work if we use normal translation animation like this,

<translate
    android:duration="1000"
    android:fromYDelta="100%"
    android:toYDelta="10%" />

The above xml code works fine but as I said before onclicklistener not working after animation.
I tried ObjectAnimator like the below one

ObjectAnimator mover = ObjectAnimator.ofFloat(filterLayout, "translationY", 1.0f, 0.1f);
mover.start();

But it doesn't give the same result as translate xml does.

Any help would be appreciated.

Body:
I know it's late but, please check the below code and see if works for your case. I took the XML code you shared as a reference to this.

ObjectAnimator.ofPropertyValuesHolder(
        view,
        PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, 100.0f, 10.0f));


问:
How to shutdown and reboot the emulator through code in android?
I have implemented the code like:

```<code>Intent i = new Intent(Intent.ACTION_REBOOT);
sendBroadcast(i);
</code>```

it get the error(runtime):

```<code>java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.REBOOT from pid=*** and uid=***
</code>```

答: Normal SDK applications cannot cause phones to shut down or reboot. Only applications that are part of the firmware (i.e., signed by the firmware sining key) can hold the proper permission and perform those actions.</p>

Body:
I have implemented the code like:

Intent i = new Intent(Intent.ACTION_REBOOT);
sendBroadcast(i);

it get the error(runtime):

java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.REBOOT from pid=*** and uid=***


问:
RNN encoder-decoder model keeps overfitting
i've trainning a machine translation model (from english to vietnamese) with RNN, LSTM with 25000 example pairs (for training set -> 20000, test set -> 5000) the model i used like below but val_acc always reach to ~0,37 and does not increment althought i used some other models and epoch is about 100:

```<code>model = Sequential()
model.add(Embedding(src_vocab, n_units, input_length=src_timesteps, mask_zero=True))
model.add(Bidirectional(LSTM(n_units)))
model.add(Dropout(0.2))
model.add(RepeatVector(tar_timesteps))
model.add(Bidirectional(LSTM(n_units, return_sequences=True)))
model.add(Dropout(0.2))
model.add(TimeDistributed(Dense(512, activation='relu')))
model.add(Dropout(0.2))
model.add(TimeDistributed(Dense(tar_vocab, activation='softmax')))
return model
</code>```

i want the model prevents overfitting,hope you guys help me solve the problem

答:
20k training instances is extremally small training data for neural machine translation. If you want to train anything on this data, you should use as little parameters as possible and strong regularization (dropout, L2, something as SwitchOut).

If I understand your code correctly, you are doing the vanilla encoder-decoder architecture by Sutkever at al. Although it is a simple model, it has relatively weak modeling capabilities. On such a small dataset, the attention model might be more suitable.

Body:
i've trainning a machine translation model (from english to vietnamese) with RNN, LSTM with 25000 example pairs (for training set -> 20000, test set -> 5000) the model i used like below but val_acc always reach to ~0,37 and does not increment althought i used some other models and epoch is about 100:

model = Sequential()
model.add(Embedding(src_vocab, n_units, input_length=src_timesteps, mask_zero=True))
model.add(Bidirectional(LSTM(n_units)))
model.add(Dropout(0.2))
model.add(RepeatVector(tar_timesteps))
model.add(Bidirectional(LSTM(n_units, return_sequences=True)))
model.add(Dropout(0.2))
model.add(TimeDistributed(Dense(512, activation='relu')))
model.add(Dropout(0.2))
model.add(TimeDistributed(Dense(tar_vocab, activation='softmax')))
return model

i want the model prevents overfitting,hope you guys help me solve the problem


问:
MySQL 5.7.26 does not accept \N for nullable int column using Load Data Infile
MySQL does not accept the \N value as null when I'm sure I've used it in the past for the same purpose.

Steps:

CREATE TABLE t (i INT NULL, name varchar(50));

Create a file called test.txt with tab separated fields:

```<code>1   John
\N  Jim
</code>```

In MySQL:

```<code>LOAD DATA INFILE '/var/lib/mysql-files/test.txt'
INTO TABLE t
Fields terminated BY "\t"
Escaped by ''
Lines terminated BY "\r\n";
</code>```

Error:

ERROR 1366 (HY000): Incorrect integer value: '\N' for column 'i' at row 2

答:
I should have done this:</p>

```<code>LOAD DATA infile '/var/lib/mysql-files/test.txt'
INTO TABLE t
fields terminated BY "\t"
Escaped by '\\'
lines terminated BY "\r\n";
</code>```

Body:
MySQL does not accept the \N value as null when I'm sure I've used it in the past for the same purpose.

Steps:

CREATE TABLE t (i INT NULL, name varchar(50));

Create a file called test.txt with tab separated fields:

1   John
\N  Jim

In MySQL:

LOAD DATA INFILE '/var/lib/mysql-files/test.txt'
INTO TABLE t
Fields terminated BY "\t"
Escaped by ''
Lines terminated BY "\r\n";

Error:

ERROR 1366 (HY000): Incorrect integer value: '\N' for column 'i' at row 2

Body:
I should have done this:

LOAD DATA infile '/var/lib/mysql-files/test.txt'
INTO TABLE t
fields terminated BY "\t"
Escaped by '\\'
lines terminated BY "\r\n";


问:
Load AutoCad DWG files in Python
There a requirement to rendering AutoCad DWG file in Python.
My first Question is,

1:- Is is possible to render/load dwg file in python and view the file/image in python environment?

2:- How can I do that? I tried using arcpy, but as it is a proprietary software of ArcGIS, it is not possible to directly import the library? What are the alternatives to that?

I even explored a lot of sources on the internet but not found anything useful.
Tried comtypes.client also for importing and viewing the same.

```<code>import array
import comtypes.client
acad = comtypes.client.GetActiveObject("AutoCAD.Application")
doc = acad.ActiveDocument
ms = doc.ModelSpace
doc.Import("sample.dwg", array.array('d', [0, 0, 0]), 1.0)
</code>```

I am getting this error, I have downloaded AutoCAD software also still I am getting this error. Please suggest what I am missing and what is the error actually means.

OSError                                   Traceback (most recent call last)
 in
3 try:
----> 4         acad = comtypes.client.GetActiveObject("AutoCAD.Application")
5 except:
~\Anaconda3\envs\py36\lib\site-packages\comtypes\client_init_.py in GetActiveObject(progid, interface, dynamic)
172     """
--> 173     clsid = comtypes.GUID.from_progid(progid)
174     if dynamic:
~\Anaconda3\envs\py36\lib\site-packages\comtypes\GUID.py in from_progid(cls, progid)
77             inst = cls()
---> 78             _CLSIDFromProgID(str(progid), byref(inst))
79             return inst
_ctypes/callproc.c in GetResult()
OSError: [WinError -2147221005] Invalid class string

答:
You can try something like this:</p>

```<code>import comtypes.client
import time
try:
        acad = comtypes.client.GetActiveObject("AutoCAD.Application")
except:
        acad = comtypes.client.CreateObject("AutoCAD.Application")
while not acad.GetAcadState().IsQuiescent :
    time.sleep(5)
acad.Visible = True
doc = acad.Documents.Open("C:\\Temp\\Sample.dwg")
</code>```

Title: Load AutoCad DWG files in Python

Body:
There a requirement to rendering AutoCad DWG file in Python.
My first Question is,

1:- Is is possible to render/load dwg file in python and view the file/image in python environment?

2:- How can I do that? I tried using arcpy, but as it is a proprietary software of ArcGIS, it is not possible to directly import the library? What are the alternatives to that?

I even explored a lot of sources on the internet but not found anything useful.
Tried comtypes.client also for importing and viewing the same.

import array
import comtypes.client
acad = comtypes.client.GetActiveObject("AutoCAD.Application")
doc = acad.ActiveDocument
ms = doc.ModelSpace
doc.Import("sample.dwg", array.array('d', [0, 0, 0]), 1.0)

I am getting this error, I have downloaded AutoCAD software also still I am getting this error. Please suggest what I am missing and what is the error actually means.

OSError                                   Traceback (most recent call last)
 in
3 try:
----> 4         acad = comtypes.client.GetActiveObject("AutoCAD.Application")
5 except:
~\Anaconda3\envs\py36\lib\site-packages\comtypes\client_init_.py in GetActiveObject(progid, interface, dynamic)
172     """
--> 173     clsid = comtypes.GUID.from_progid(progid)
174     if dynamic:
~\Anaconda3\envs\py36\lib\site-packages\comtypes\GUID.py in from_progid(cls, progid)
77             inst = cls()
---> 78             _CLSIDFromProgID(str(progid), byref(inst))
79             return inst
_ctypes/callproc.c in GetResult()
OSError: [WinError -2147221005] Invalid class string

Body:
You can try something like this:

import comtypes.client
import time
try:
        acad = comtypes.client.GetActiveObject("AutoCAD.Application")
except:
        acad = comtypes.client.CreateObject("AutoCAD.Application")
while not acad.GetAcadState().IsQuiescent :
    time.sleep(5)
acad.Visible = True
doc = acad.Documents.Open("C:\\Temp\\Sample.dwg")


问:
Overloads of std::isnan and std::isinf for integral types
Cppreference mentions the overloads of std::isnan and std::isinf (and maybe others) for integral types. This makes the following call unambiguous:

```<code>std::isnan(1);
</code>```

However, I cannot find any such overloads mentioned in the C++ Standard. I checked C++11 and the current draft, and there are only overloads for float, double, and long double.

As for compiler behavior, GCC and Clang both compile the code, but MSVC does not. Who is right? Where did the integral overload on cppreference come from?

答:
That's a synopsis, and there is a footnote

For each set of overloaded functions within , with the exception of abs, there shall be additional overloads sufficient to ensure:

...

Otherwise, if any argument of arithmetic type corresponding to a double parameter has type double or an integer type, then all arguments of arithmetic type corresponding to double parameters are effectively cast to double.

which corresponds to the bool isnan( IntegralType arg ) description

A set of overloads or a function template accepting the arg argument of any integral type. Equivalent to (2) (the argument is cast to double).

Body:
Cppreference mentions the overloads of std::isnan and std::isinf (and maybe others) for integral types. This makes the following call unambiguous:

std::isnan(1);

However, I cannot find any such overloads mentioned in the C++ Standard. I checked C++11 and the current draft, and there are only overloads for float, double, and long double.

As for compiler behavior, GCC and Clang both compile the code, but MSVC does not. Who is right? Where did the integral overload on cppreference come from?


问:
Open source alternative to Tableau?
I am looking for an interactive exploratory tool to embed in a commercial application.
I am looking for a commercial-friendly licensed open source alternative to the wonderful Tableau system</p>

答:
Take a look at Pentaho. It's built from open source parts so you should be able to reuse parts of that. There's also R, though that is really more of a statistical programming framework than an ready-to-use exploratory tool.

If you're looking for something that's as easy to use as Tableau though, I'm afraid you won't find any open source solutions.

Title: Open source alternative to Tableau?


问:
Getting all elements from JSON API response
Getting an API response as below and wanted to get the names for all the fields using restassured.

```<code>{
    "expand": "projects",
    "projects": [
        {
            "expand": "issuetypes",
            "issuetypes": [
                {
                    "subtask": false,
                    "expand": "fields",
                    "fields": {
                        "summary": {
                            "required": true,
                            "schema": {
                                "type": "string",
                                "system": "summary"
                            },
                            "name": "Summary",
                            "hasDefaultValue": false,
                            "operations": [
                                "set"
                            ]
                        },
                        "customfield_10100": {
                            "required": false,
                            "schema": {
                                "type": "any",
                                "custom": "com.pyxis.greenhopper.jira:gh-epic-link",
                                "customId": 10100
                            },
                            "name": "Epic Link",
                            "hasDefaultValue": false,
                            "operations": [
                                "set"
                            ]
                        },
                        "customfield_10102": {
                            "required": true,
                            "schema": {
                                "type": "string",
                                "custom": "com.pyxis.greenhopper.jira:gh-epic-label",
                                "customId": 10102
                            },
                            "name": "Epic Name",
                            "hasDefaultValue": false,
                            "operations": [
                                "set"
                            ]
                        },
                       }
                }
            ]
        }
    ]
}
</code>```

I tried to get the names using respStg1.jsonPath().getList("projects.issuetypes.fields.[*].name"), but getting gpath error. Please help if there is any way to get the name of all the fields under projects.issuetypes.fields.

答:
Try with this = [*].[*].[*].[*].name
This should work
For future you can use this link to evaluate jsonPath : http://jsonpath.com/

and for jsonPath syntax and wildcards refer this link : https://support.smartbear.com/alertsite/docs/monitors/api/endpoint/jsonpath.html

Body:
Getting an API response as below and wanted to get the names for all the fields using restassured.

{
    "expand": "projects",
    "projects": [
        {
            "expand": "issuetypes",
            "issuetypes": [
                {
                    "subtask": false,
                    "expand": "fields",
                    "fields": {
                        "summary": {
                            "required": true,
                            "schema": {
                                "type": "string",
                                "system": "summary"
                            },
                            "name": "Summary",
                            "hasDefaultValue": false,
                            "operations": [
                                "set"
                            ]
                        },
                        "customfield_10100": {
                            "required": false,
                            "schema": {
                                "type": "any",
                                "custom": "com.pyxis.greenhopper.jira:gh-epic-link",
                                "customId": 10100
                            },
                            "name": "Epic Link",
                            "hasDefaultValue": false,
                            "operations": [
                                "set"
                            ]
                        },
                        "customfield_10102": {
                            "required": true,
                            "schema": {
                                "type": "string",
                                "custom": "com.pyxis.greenhopper.jira:gh-epic-label",
                                "customId": 10102
                            },
                            "name": "Epic Name",
                            "hasDefaultValue": false,
                            "operations": [
                                "set"
                            ]
                        },
                       }
                }
            ]
        }
    ]
}

I tried to get the names using respStg1.jsonPath().getList("projects.issuetypes.fields.[*].name"), but getting gpath error. Please help if there is any way to get the name of all the fields under projects.issuetypes.fields.


问:
Rails update element based on AJAX request?
I've been reading a lot about Rails and AJAX and 5.1 Unobtrusive javascript. It explains a lot about responding to Rails version of AJAX calls with a .js file for example.

However what im wanting to do isn't serving up an entire .js file, it's simply updating an element after a <% link_to %> POST request. From my understanding setting remote: true submits it as a AJAX request.

Essentially I have a "Post" which a user can like via a linked Like button. This sends a POST request to the "Post" controller which updates a post to liked and adds a like to the post.

Unfortunately to see the effects of the post being liked (Which is simply that the link changes color as well as the font-awesome icon) you need to refresh the page. I basically want it to update without needing refresh.

I "think" based off what i've read I need to make a respond do and respond via .js to the request with a .js file in the view I want to update (for instance if the controller action is called "like", maybe a like.js.erb file in the view im updating?). But I don't want to serve an entire new page..or would this simply just run the .js?

Then I could do something like $('i.fa-icon#id').style.color = "blue" or something? (Im assuming I can send data from the controller to the .js.erb file?). Not sure the best way to do this, don't rails elements a lot of times have some sort of data-attribute or something (Im still a beginner at this).

答:
Your description is quite correct!
Opposed to the other answer, you don't even need a event listener but as you said you want to have a respond_to in the controller.
So starting from the html:

```<code># post/index.html.erb
<div id="like-button">
  <%= button_to "Like this post", post_path(@post), remote: true %>
</div>
</code>```

Note, that when you use a button_to helper it'll be a POST request by default.

If you click it, it'll go to the controller#update, which you want to change to this:

```<code>#posts_controller.rb
...
def update
  @post.save
    respond_to do |format|
      format.html { redirect_to post_path(@post) }
      format.js  # <-- will render `app/views/posts/update.js.erb`
    end
end
</code>```

Note: the format.html is rendered when JS is disabled.
Now in the scenario that JS is enabled, it executes the app/views/posts/update.js.erb file. It can look like this:

```<code>const likeButton = document.getElementById('like-button');
likeButton.innerHTML = '<%= j render "posts/liked-link", post: @post %>';
</code>```

What is the last line doing? Of course, you can change the style directly with the JavaScript, but you can also render a new partial - and this you will create in a new html file:

```<code># app/views/posts/liked_link.html.erb
<div id="like-button ">
 <p>"You liked this post!" </p>
</div>
</code>```

I just changed the link/button to ap now, but of course you can do whatever you want.

Hope that makes sense :)

Body:
Your description is quite correct!
Opposed to the other answer, you don't even need a event listener but as you said you want to have a respond_to in the controller.
So starting from the html:

# post/index.html.erb
<div id="like-button">
  <%= button_to "Like this post", post_path(@post), remote: true %>
</div>

Note, that when you use a button_to helper it'll be a POST request by default.

If you click it, it'll go to the controller#update, which you want to change to this:

#posts_controller.rb
...
def update
  @post.save
    respond_to do |format|
      format.html { redirect_to post_path(@post) }
      format.js  # <-- will render `app/views/posts/update.js.erb`
    end
end

Note: the format.html is rendered when JS is disabled.
Now in the scenario that JS is enabled, it executes the app/views/posts/update.js.erb file. It can look like this:

const likeButton = document.getElementById('like-button');
likeButton.innerHTML = '<%= j render "posts/liked-link", post: @post %>';

What is the last line doing? Of course, you can change the style directly with the JavaScript, but you can also render a new partial - and this you will create in a new html file:

# app/views/posts/liked_link.html.erb
<div id="like-button ">
 <p>"You liked this post!" </p>
</div>

I just changed the link/button to ap now, but of course you can do whatever you want.

Hope that makes sense :)


问:
How do create a variable length array in C in Visual Studio 2010 enviroment?
I want to create a variable length array for my code in the Visual Studio 2010 environment.

I had tried the code using the array of length x, as it is passing by the user. But I am facing the error as:

"error C2466:cannot allocate an array of constant size 0" ,"error C2133: 'v_X_array' : unknown size".

```<code>func1(int x)
{
    int v_X_array[x];
    int i;
    for (i=0; i<x; i++)
    {
        v_X_array[i] = i;
    }
}
</code>```

I expect the answer as v_X_array[0] = 0, v_X_array[1] =1, v_X_array[2]=2 ... v_X_array[10]=10 ; for x = 10;

How can I do this?

Note: as calloc and malloc should not be used.

答:
If you need your code to be portable, you cannot use that kind of array definition to handle memory areas.

Without going into specific implementations, you have two generic approaches that you can use:

Define an array big enough for the worst case. This is tightly dependent on the application, so you are on your own.

Define the "array" using dynamic allocation. With that, you can define memory areas of any arbitrary size.

If you choose option 2:

a. Do not forget to de-allocate the memory when you no longer need it.

b. To avoid frequent allocation and de-allocation, you may define the buffer once (perhaps bigger then necessary for the current call) and use it several times. You may and up with the same result as option 1 above - define a large array from the start.

Since you should not use dynamic allocation ("calloc and malloc should not be used"), then you are left with option 1.

I expect the ans as v_X_array[0] = 0, v_X_array[1] =1, v_X_array[2]=2 ... v_X_array[10]=10 ; for x = 10;

You expect to store 11 values in an array which can hold only 10?

Body:
I want to create a variable length array for my code in the Visual Studio 2010 environment.

I had tried the code using the array of length x, as it is passing by the user. But I am facing the error as:

"error C2466:cannot allocate an array of constant size 0" ,"error C2133: 'v_X_array' : unknown size".

func1(int x)
{
    int v_X_array[x];
    int i;
    for (i=0; i<x; i++)
    {
        v_X_array[i] = i;
    }
}

I expect the answer as v_X_array[0] = 0, v_X_array[1] =1, v_X_array[2]=2 ... v_X_array[10]=10 ; for x = 10;

How can I do this?

Note: as calloc and malloc should not be used.


问:
How can I env variables in fastlane for creating the template
I have build and distributed my iOS app using fastlane, for that I have created script in fast file, so now I want pass the env variable in this script for creating the template, this same template I can use my other iOS apps as well, so how can I pass env variables in my fastlane script?</p>

答:
Fastfile and Co are just Ruby code, so you can use ENV['XYZ'] to access any environment variables.

To set environment variables, there are multiple options in fastlane. Some are described at https://docs.fastlane.tools/advanced/other/#environment-variables
Fastlane also supports dotenv to set environment variables via files: https://docs.fastlane.tools/best-practices/keys/#dotenv


问:
Reject issue: "We are not able to continue because we need a demo QR code or AR marker (image) to fully assess your app features."
I have a project in a flutter. It has QR code scanner and the QR code is generated from the web and is called using API. QR code scanner scans the QR-code to get the information of the user. I submitted my app and got rejected saying :

```<code>We have started the review of your app, but we are not able to continue
because we need a demo QR code or AR marker (image) to fully assess your
app features.
</code>```

Next Steps

```<code>To help us proceed with the review of your app, please provide the demo
details in the App Review Information section for your app in App Store
Connect or reply to this message with the requested demo information.
Please ensure that the information you provide includes any data necessary
to demonstrate the functionality of your app features.
</code>```

To provide QR codes or images information:

```<code>- Log in to App Store Connect
- Click on "My Apps"
- Select your app
- Click on the app version on the left side of the screen
- Scroll down to "App Review Information"
- Provide information in "Notes" as appropriate
- Click "Save"
- Once you've completed all changes, click the "Save" button at the top of
the Version Information page.
</code>```

Then I created a demo video to use QR code scanner and wrote some

notes as:

```<code>  *The QR code image for each user is provided from our API and set on
  lock
  screen by the user.
  *The purpose of the camera permission is to scan the QR code.
  *The Scanned QR code returns the details uploaded by the user whose
  phone is lost. A demo video is attached on attachment.
</code>```

I again submitted to the app store and still, it rejected saying the same error as above. I couldn't find the possible solutions. Anyone could help me?

答:
I have faced the same rejection earlier. To approve my app, I have given
  the sample URL, Which basically contains an image of the QR Code. By using this URL reviewer team can review the whole
  functionality of the app.

Also, Give some step or video which is helpful to the reviewer team.

Sample QR image

That's it!

Body:
I have a project in a flutter. It has QR code scanner and the QR code is generated from the web and is called using API. QR code scanner scans the QR-code to get the information of the user. I submitted my app and got rejected saying :

We have started the review of your app, but we are not able to continue
because we need a demo QR code or AR marker (image) to fully assess your
app features.

Next Steps

To help us proceed with the review of your app, please provide the demo
details in the App Review Information section for your app in App Store
Connect or reply to this message with the requested demo information.
Please ensure that the information you provide includes any data necessary
to demonstrate the functionality of your app features.

To provide QR codes or images information:

- Log in to App Store Connect
- Click on "My Apps"
- Select your app
- Click on the app version on the left side of the screen
- Scroll down to "App Review Information"
- Provide information in "Notes" as appropriate
- Click "Save"
- Once you've completed all changes, click the "Save" button at the top of
the Version Information page.

Then I created a demo video to use QR code scanner and wrote some

notes as:

  *The QR code image for each user is provided from our API and set on
  lock
  screen by the user.
  *The purpose of the camera permission is to scan the QR code.
  *The Scanned QR code returns the details uploaded by the user whose
  phone is lost. A demo video is attached on attachment.

I again submitted to the app store and still, it rejected saying the same error as above. I couldn't find the possible solutions. Anyone could help me?


问:
Signal handling in Pylons
I have a pylons project where I need to update some in-memory structures periodically. This should be done on-demand. I decided to come up with a signal handler for this. User sends SIGUSR1 to the main pylons thread and it is handled by the project.

This works except after handling the signal, the server crashes with following exception:

```<code>File "/usr/lib/python2.6/SocketServer.py", line 264, in handle_request
   fd_sets = select.select([self], [], [], timeout)
select.error: (4, 'Interrupted system call')
</code>```

Is it possible to fix this?

TIA.

答:
Yes, it is possible, but not easy using the stock Python libraries. This is due to Python translating all OS errors to exceptions. However, EINTR should really cause a retry of the system call used.  Whenever you start using signals in Python you will see this error sporadically.

I have code that fixes this (SafeSocket), by forking Python modules and adding that functionality. But it needs to be added everywhere system calls are used. So it's possible, but not easy. But you can use my open-source code, it may save you years of work. ;-)

The basic pattern is this (implemented as a system call decorator):

```<code># decorator to make system call methods safe from EINTR
def systemcall(meth):
    # have to import this way to avoid a circular import
    from _socket import error as SocketError
    def systemcallmeth(*args, **kwargs):
        while 1:
            try:
                    rv = meth(*args, **kwargs)
            except EnvironmentError as why:
                if why.args and why.args[0] == EINTR:
                    continue
                else:
                    raise
            except SocketError as why:
                if why.args and why.args[0] == EINTR:
                    continue
                else:
                    raise
            else:
                break
        return rv
    return systemcallmeth
</code>```

You could also just use that around your select call.

Title: Signal handling in Pylons

Body:
I have a pylons project where I need to update some in-memory structures periodically. This should be done on-demand. I decided to come up with a signal handler for this. User sends SIGUSR1 to the main pylons thread and it is handled by the project.

This works except after handling the signal, the server crashes with following exception:

File "/usr/lib/python2.6/SocketServer.py", line 264, in handle_request
   fd_sets = select.select([self], [], [], timeout)
select.error: (4, 'Interrupted system call')

Is it possible to fix this?

TIA.

Body:
Yes, it is possible, but not easy using the stock Python libraries. This is due to Python translating all OS errors to exceptions. However, EINTR should really cause a retry of the system call used.  Whenever you start using signals in Python you will see this error sporadically.

I have code that fixes this (SafeSocket), by forking Python modules and adding that functionality. But it needs to be added everywhere system calls are used. So it's possible, but not easy. But you can use my open-source code, it may save you years of work. ;-)

The basic pattern is this (implemented as a system call decorator):

# decorator to make system call methods safe from EINTR
def systemcall(meth):
    # have to import this way to avoid a circular import
    from _socket import error as SocketError
    def systemcallmeth(*args, **kwargs):
        while 1:
            try:
                    rv = meth(*args, **kwargs)
            except EnvironmentError as why:
                if why.args and why.args[0] == EINTR:
                    continue
                else:
                    raise
            except SocketError as why:
                if why.args and why.args[0] == EINTR:
                    continue
                else:
                    raise
            else:
                break
        return rv
    return systemcallmeth

You could also just use that around your select call.


问:
upload image to server using Alamofire
this is my code that I want to upload image to server using Alamofire, it not error but it can't push image to server. what should I do?</p>

```<code>let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"

let parameters = ["name": rname]

do {
    urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
    print(error)
}

urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    let image = UIImage.init(named: "myImage")
    let imgData = UIImageJPEGRepresentation(image!, 0.2)!

Alamofire.upload(multipartFormData: { MultipartFormData in

        MultipartFormData.append(imgData, withName: "fileset", fileName: "name", mimeType: "image/jpg")

    },with: urlRequest,encodingCompletion: { encodingResult in

        switch encodingResult {

        case .success(let upload, _, _):

            upload.responseJSON { response in

                if let info = response.result.value as? Dictionary<String, AnyObject> {

                    if let links = info["links"] as? Dictionary<String, AnyObject> {

                        if let imgLink = links["image_link"] as? String {
                            print("LINK: \(imgLink)")
                        }
                    }
                }

            } case .failure(let error):
                print(error)
        }
    })
</code>```

答:
Updated code to Swift 5.

In swift 5 there is a change in this line

```<code>let imageData = UIImageJPEGRepresentation(image!, 0.2)!
</code>```

To like this

```<code>let imageData = image.jpegData(compressionQuality: 0.50)
</code>```

Whole code to upload image

```<code>let param: [String:Any] = ["your_parameters"]
var image = UIImage()
image = UIImage(named: "edit.png")!
let imageData = image.jpegData(compressionQuality: 0.50)
print(image, imageData!)

AF.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(imageData!, withName: "file", fileName: "swift_file.png", mimeType: "image/png")
        for (key, value) in param {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
        }
    }, to: "your_url")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                //Print progress
                print("uploading \(progress)")

            })

            upload.responseJSON { response in
                //print response.result

            }
        case .failure( _): break
            //print encodingError.description
        }
    }
}
</code>```

Title: upload image to server using Alamofire

Body:
this is my code that I want to upload image to server using Alamofire, it not error but it can't push image to server. what should I do?

let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"

let parameters = ["name": rname]

do {
    urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
    print(error)
}

urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    let image = UIImage.init(named: "myImage")
    let imgData = UIImageJPEGRepresentation(image!, 0.2)!

Alamofire.upload(multipartFormData: { MultipartFormData in

        MultipartFormData.append(imgData, withName: "fileset", fileName: "name", mimeType: "image/jpg")

    },with: urlRequest,encodingCompletion: { encodingResult in

        switch encodingResult {

        case .success(let upload, _, _):

            upload.responseJSON { response in

                if let info = response.result.value as? Dictionary<String, AnyObject> {

                    if let links = info["links"] as? Dictionary<String, AnyObject> {

                        if let imgLink = links["image_link"] as? String {
                            print("LINK: \(imgLink)")
                        }
                    }
                }

            } case .failure(let error):
                print(error)
        }
    })

Body:
Updated code to Swift 5.

In swift 5 there is a change in this line

let imageData = UIImageJPEGRepresentation(image!, 0.2)!

To like this

let imageData = image.jpegData(compressionQuality: 0.50)

Whole code to upload image

let param: [String:Any] = ["your_parameters"]
var image = UIImage()
image = UIImage(named: "edit.png")!
let imageData = image.jpegData(compressionQuality: 0.50)
print(image, imageData!)

AF.upload(multipartFormData: { (multipartFormData) in
        multipartFormData.append(imageData!, withName: "file", fileName: "swift_file.png", mimeType: "image/png")
        for (key, value) in param {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
        }
    }, to: "your_url")
    { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                //Print progress
                print("uploading \(progress)")

            })

            upload.responseJSON { response in
                //print response.result

            }
        case .failure( _): break
            //print encodingError.description
        }
    }
}


问:
Table header disappears when searching through the HTML table with Javascript function
I've run into some trouble regarding a search function within a php script. The search function is written in javascript and is supposed to loop through the entire table below and pick out the matching content the same time the user types into the search field. The functions search within the 'Beskrivelse' tab. However, when I start typing in the search field, the table header (Username, Beskrivelse, Links, Kommentar, Billede, Rediger) also disappears as it is also a part of the table.

My question is; how can I keep the header constant while searching through the table rows below the header? The header is not supposed to go away at any time.

Table header is shown
Table header is hidden

Here's the full code for the php script:

<?php
//including the database connection file
include_once("config.php");

//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM 3difpensum ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT * FROM 3difstortab ORDER BY ID DESC"); // using mysqli_query instead
?>

 <title>Homepage</title>

Logout

 <input type="text" class="searchfield" id="myInput" onkeyup="myFunction()" placeholder="Søg efter Beskrivelse...">

 Add New Data

  Username
  Beskrivelse
  Links
  Kommentar
  Billede
  Rediger

 <?php
 //while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
 while($res = mysqli_fetch_array($result)) {
  echo "
";
  echo "".$res['ejer']."	";
  echo "".$res['beskrivelse']."	";
  echo "".$res['links']."	";
  echo "".$res['kommentar']."	";
  echo ""."	";
  echo "Edit | Delete	";
 }
 ?>

```

答:
Ok Check this Your issue is resolved

<?php
//including the database connection file
include_once("config.php");

//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM 3difpensum ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT * FROM 3difstortab ORDER BY ID DESC"); // using mysqli_query instead
?>

 <title>Homepage</title>

Logout

 <input type="text" class="searchfield" id="myInput" onkeyup="myFunction()" placeholder="Søg efter Beskrivelse...">

 Add New Data

  Username
  Beskrivelse
  Links
  Kommentar
  Billede
  Rediger

 <?php
 //while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
 while($res = mysqli_fetch_array($result)) {
  echo "
";
  echo "".$res['ejer']."	";
  echo "".$res['beskrivelse']."	";
  echo "".$res['links']."	";
  echo "".$res['kommentar']."	";
  echo ""."	";
  echo "Edit | Delete	";
 }
 ?>

```

Body:
Ok Check this Your issue is resolved

<?php
//including the database connection file
include_once("config.php");

//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM 3difpensum ORDER BY id DESC"); // mysql_query is deprecated
$result = mysqli_query($mysqli, "SELECT * FROM 3difstortab ORDER BY ID DESC"); // using mysqli_query instead
?>

<html>
<head>
 <title>Homepage</title>
 <script>
function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

</script>
<style>
 .container {
  width: 100%;
  text-align: center;
  margin-top: 50px;
  padding: 5px;
 }

 .searchfield {
  margin: 0 auto;
  width: 400px;
  height: 40px;
  font-size: 14px;
  display: inline-block;
  font-family: Helvetica;
 }

 .addmore {
  background-color: #535b63; /* Green */
  border: none;
  color: white;
  padding: 11px 0px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  color: #ffffff;
  font-family: Helvetica;
  width: 400px;
 }

 .secondcontainer {
  width: 100%;
  text-align: center;
  padding: 5px;
 }
 .thirdcontainer {
  width: 100%;
  text-align: center;
  margin-top: 30px;
 }
 .tableview {
  margin: 0 auto;
 }
 .tableheader {
  text-align: center;
  font-family: Helvetica;
  font-size: 14px;
  background-color: #535b63;
  color: #fff;
 }
 .tableheader td {
  padding: 5px;
 }
</style>
</head>

<body>
<a href="logout.php">Logout</a>

<div class="container">
 <input type="text" class="searchfield" id="myInput" onkeyup="myFunction()" placeholder="Søg efter Beskrivelse...">
</div>
<div class="secondcontainer">
 <a href="add.html" class="addmore">Add New Data</a><br/><br/>
</div>

<div class="thirdcontainer">
 <table width='70%' class="tableview" border=0 id="myTable">
 <tr class="tableheader">
  <th>Username</th>
  <th>Beskrivelse</th>
  <th>Links</td>
  <th>Kommentar</th>
  <th>Billede</th>
  <th>Rediger</th>
 </tr>
 <?php
 //while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
 while($res = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>".$res['ejer']."</td>";
  echo "<td>".$res['beskrivelse']."</td>";
  echo "<td>".$res['links']."</td>";
  echo "<td>".$res['kommentar']."</td>";
  echo "<td>"."<img src='".$res['billede']."'></td>";
  echo "<td><a href=\"edit.php?ID=$res[ID]\">Edit</a> | <a href=\"delete.php?ID=$res[ID]\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";
 }
 ?>
 </table>
</div>

</body>
</html>


问:
difference between 2 dates in days saved into new column as float
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

```<code>df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])
</code>```

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

答:
You can try this :</p>

```<code>df = pd.DataFrame()
df['Arrived'] = [pd.Timestamp('01-04-2017')]
df['Left'] = [pd.Timestamp('01-06-2017')]
diff = df['Left'] - df['Arrived']
days = pd.Series(delta.days for delta in (diff)
result = days[0]
</code>```

Body:
I have a python dataframe with 2 columns that contain dates as strings e.g. start_date "2002-06-12" and end_date "2009-03-01". I would like to calculate the difference (days) between these 2 columns for each row and save the results into a new column called for example time_diff of type float.

I have tried:

df["time_diff"] = (pd.Timestamp(df.end_date) - pd.Timestamp(df.start_date )).astype("timedelta64[d]")
pd.to_numeric(df["time_diff"])

based on some tutorials but this gives TypeError: Cannot convert input for the first line. What do I need to change to get this running?

Body:
You can try this :

df = pd.DataFrame()
df['Arrived'] = [pd.Timestamp('01-04-2017')]
df['Left'] = [pd.Timestamp('01-06-2017')]
diff = df['Left'] - df['Arrived']
days = pd.Series(delta.days for delta in (diff)
result = days[0]


问:
Here zoomTo Ignores ViewRect X & Y Positions
I am attempting to display a route in a map. I am displaying route information over the bottom portion of the map. So I need to offset the route when displaying it. In the iOS SDK I can use the method set:

func set(boundingBox: NMAGeoBoundingBox, inside: CGRect, animation: NMAMapAnimation)

The CGRect offsets the route. The Android SDK has a similar method zoomTo

zoomTo(GeoBoundingBox var1, ViewRect var2, Map.Animation var3, float var4)

But it seems to ignore the X and Y starting positions of the ViewRect. It does use the height and width I give it, but the route is always in the center of the screen.

答: The issue is fixed and it will be available in 3.12 release (planned for beginning of July)</p>


问:
virtualbox: what is the difference of --natdnsproxy1 and --natdnshostresolver1?
The virtualbox documentation did not explain it clearly.

https://www.virtualbox.org/manual/ch09.html

9.11.5. Enabling DNS proxy in NAT mode The NAT engine by default offers the same DNS servers to the guest that are configured on the
host. In some scenarios, it can be desirable to hide the DNS server
IPs from the guest, for example when this information can change on
the host due to expiring DHCP leases. In this case, you can tell the
NAT engine to act as DNS proxy using the following command:

VBoxManage modifyvm "VM name" --natdnsproxy1 on

9.11.6. Using the host's resolver as a DNS proxy in NAT mode For resolving network names, the DHCP server of the NAT engine offers a
list of registered DNS servers of the host. If for some reason you
need to hide this DNS server list and use the host's resolver
settings, thereby forcing the VirtualBox NAT engine to intercept DNS
requests and forward them to host's resolver, use the following
command:

VBoxManage modifyvm "VM name" --natdnshostresolver1 on Note that this
setting is similar to the DNS proxy mode, however whereas the proxy
mode just forwards DNS requests to the appropriate servers, the
resolver mode will interpret the DNS requests and use the host's DNS
API to query the information and return it to the guest.

can anyone really understand the difference?

EDIT: need a actual example.

答:
If the natdnsproxy option of a NAT-typed network adapter is enabled, VirtualBox's NAT gateway will accept DNS traffic from the guest and forward it to the resolver used by the host. It will solely act as a network-layer proxy. Only DNS traffic sent to the gateway IP will be redirected, it will not intercept DNS traffic sent to other IPs. Make sure your guest is using your gateway IP (e.g. 10.0.2.2) as resolver (this should work out of the box if your guest does DHCP).

The natdnshostresolver option is similiar - it will cause the NAT gateway to accept DNS traffic too - but the gateway will read (i.e. parse) the query and use the host's operating system APIs to resolve it. On Linux this would be getaddrinfo(). This is the preferred option IMHO.

The number (1) refers to the network adapter and is interchangable. --natdnshostresolver2 on would enable the option for the second interface of the given VM.