问:
Match part of string against array of string in javascript
I have an array with 1500 strings of varint like this:

```<code> var base = ["129;176;2","131;173;2","242;1","221;188;2","138;7","201;20","251;12","32"]
</code>```

The strings of the array can be formed by a single number ("32"), two numbers ("242;1") or three numbers ("131;173;2"), not more than 3 number.

And a variable that contain a string obtained from the concatenation of the strings contained in the array (that variable is created by the user and only from a list of values that can be found in the base array).

```<code> var userCreated = "129;176;2;32;131;173;2;184;3;201;20;251;12"
</code>```

The problem is find a perfect match in the array, but I cannot know the right part to check.

For example:
I do not know if I've to match "129" or "129;176" or "129;176;2", so I need a function that can match the first number, the first and the second numbers, and the first, the second and the third number. When a perfect match is found that portion of string have to be stored in a new variable and removed from the original variable (userCreated).

With a single number I can do:

```<code> var divide = userCreated.split(";");
 for (var i = 0;i<divide.length; i++){
         if(base.indexOf(divide[i]) >= 0){
            var found + i = divide[i];
         }
 }
</code>```

It's possible check sequentially the string in the var against the array to find a perfect match and then check for the rest of the string? It's important to notice that: a match can be found before the "perfect match" (check for "129" can find a match, but there can be a "129;176" in the base array (the perfect match) so the others values can be mismatched...

EDIT:
To clarify the question: The userCreated string can't contain twice a value to be matched in the array. For example: It can contain 126;15 and 126;15;2 but not 126;15 or 126;15;2 twice.
The expected result can be a series of variable with inside every "perfect match", such as:

```<code> var found0 = "129;176;2";
 var found1 = "242;1";
 var found2 = "32";
</code>```

or an array like the original array so:

```<code> var found = ["129;176;2", "242;1", "32"] // Maybe a better solution
</code>```

The number of total match it's in a range from 1 match to 30 match.

EDIT (solution):
After the accepted (and good) answer I've tried to follow a similar way:
I've split my original array in 3 arrays like this:

```<code> base1 = ["28", "34", "16"];
 base2 = ["125;16", "200;45", "167;2"];
 base3 = ["209;145;2", "143;154;2", "211;170;2", "246;170;2", "247;170;2"];
</code>```

then:

```<code> var divide = userCreated.split(";"),
     resultArray3 = [], resultArray2 = [], resultArray1 = [], final = [];
 function tri(divide){
 for (var i = 0, j = 1, k = 2; k<divide.length; i++, j++, k++){
    var tre = base3.indexOf(divide[i]+';'+divide[j]+';'divide[k]);
    if (tre !== -1){
        resultArray3.push(base3[tre]);
        divide.splice(i, 1, "none");
        divide.splice(j, 1, "none");
        divide.splice(k, 1, "none");
    }
 }
 }
 function two(divide){
     for (var i = 0, k = 1; k<divide.length; i++, k++){
            var due = base2.indexOf(divide[i]+';'+divide[k]);
        if (due !== -1){
            resultArray2.push(base2[due]);
            divide.splice(i, 1, "none");
            divide.splice(k, 1, "none");
        }
 }
 }
 function ones(divide){
 for (var k = 0; k<divide.length; k++){
    var uno = base1.indexOf(divide[k]);
        if (uno !== -1){
            resultArray1.push(base1[uno]);
            divide.splice(k, 1, "none");
        }
}
 }
</code>```

and finally:

```<code>final.push.apply(final, resultArray1);
final.push.apply(final, resultArray2);
final.push.apply(final, resultArray3);
</code>```

答:
As @ObsidianAge notes, there might be multiple ways to split the input string into matching portions. I would check if the inputs have to be this way, if possible.

I'm not sure what stopped you from pursuing the solution you described... the easiest implementation of this involves recursion:

let base = ["129", "129;176", "129;176;2","131;173;2","242;1","221;188;2","138;7","201;20","251;12","32", "184;3", "176"]
let userCreated = '129;176;2;32;131;173;2;184;3;201;20;251;12';

let appendSemicolon = (str) => str + ";";
let removeSemicolon = (str) => str.substr(0, str.length-1);

base = base.map(appendSemicolon); // so that '1' is not matched as a prefix of '12;34'

function findMatch(input, depth=0) {
  // returns an array of arrays where:
  //    solutions[i].join("") == input
  //    solutions[i][j] is a string from `base`
  // (empty array if no such solutions exist)
  let solutions = [];
  base.forEach((prefix) => {
    if (!input.startsWith(prefix)) return;
    let rest = input.substr(prefix.length);

    if (rest.length === 0) {
      // easy case: the input has a 'perfect match' in `base`
      console.log(" ".repeat(depth) + `checking '${prefix}' - matching complete!`)
      solutions.push([prefix]);
    } else {
      // we found a matching prefix. It will be a valid solution iff
      // the rest of input can be constructed from the strings in `base`
      console.log(" ".repeat(depth) + `checking '${prefix}' (rest='${rest}')`)
      let subSolutions = findMatch(rest, depth+1);
      solutions = solutions.concat(subSolutions.map((sol) => [prefix].concat(sol)));
    }
  });
  return solutions;
}

findMatch(userCreated + ";").map((parts) => parts.map(removeSemicolon));```

Note that you didn't specify if duplicate entries are allowed in the input string, I'm not trying to optimize this, and I'm using some syntax from the newer revisions of JS, which may not be universally supported by all browsers yet.

Body:
I have an array with 1500 strings of varint like this:

 var base = ["129;176;2","131;173;2","242;1","221;188;2","138;7","201;20","251;12","32"]

The strings of the array can be formed by a single number ("32"), two numbers ("242;1") or three numbers ("131;173;2"), not more than 3 number.

And a variable that contain a string obtained from the concatenation of the strings contained in the array (that variable is created by the user and only from a list of values that can be found in the base array).

 var userCreated = "129;176;2;32;131;173;2;184;3;201;20;251;12"

The problem is find a perfect match in the array, but I cannot know the right part to check.

For example:
I do not know if I've to match "129" or "129;176" or "129;176;2", so I need a function that can match the first number, the first and the second numbers, and the first, the second and the third number. When a perfect match is found that portion of string have to be stored in a new variable and removed from the original variable (userCreated).

With a single number I can do:

 var divide = userCreated.split(";");
 for (var i = 0;i<divide.length; i++){
         if(base.indexOf(divide[i]) >= 0){
            var found + i = divide[i];
         }
 }

It's possible check sequentially the string in the var against the array to find a perfect match and then check for the rest of the string? It's important to notice that: a match can be found before the "perfect match" (check for "129" can find a match, but there can be a "129;176" in the base array (the perfect match) so the others values can be mismatched...

EDIT:
To clarify the question: The userCreated string can't contain twice a value to be matched in the array. For example: It can contain 126;15 and 126;15;2 but not 126;15 or 126;15;2 twice.
The expected result can be a series of variable with inside every "perfect match", such as:

 var found0 = "129;176;2";
 var found1 = "242;1";
 var found2 = "32";

or an array like the original array so:

 var found = ["129;176;2", "242;1", "32"] // Maybe a better solution

The number of total match it's in a range from 1 match to 30 match.

EDIT (solution):
After the accepted (and good) answer I've tried to follow a similar way:
I've split my original array in 3 arrays like this:

 base1 = ["28", "34", "16"];
 base2 = ["125;16", "200;45", "167;2"];
 base3 = ["209;145;2", "143;154;2", "211;170;2", "246;170;2", "247;170;2"];

then:

 var divide = userCreated.split(";"),
     resultArray3 = [], resultArray2 = [], resultArray1 = [], final = [];
 function tri(divide){
 for (var i = 0, j = 1, k = 2; k<divide.length; i++, j++, k++){
    var tre = base3.indexOf(divide[i]+';'+divide[j]+';'divide[k]);
    if (tre !== -1){
        resultArray3.push(base3[tre]);
        divide.splice(i, 1, "none");
        divide.splice(j, 1, "none");
        divide.splice(k, 1, "none");
    }
 }
 }
 function two(divide){
     for (var i = 0, k = 1; k<divide.length; i++, k++){
            var due = base2.indexOf(divide[i]+';'+divide[k]);
        if (due !== -1){
            resultArray2.push(base2[due]);
            divide.splice(i, 1, "none");
            divide.splice(k, 1, "none");
        }
 }
 }
 function ones(divide){
 for (var k = 0; k<divide.length; k++){
    var uno = base1.indexOf(divide[k]);
        if (uno !== -1){
            resultArray1.push(base1[uno]);
            divide.splice(k, 1, "none");
        }
}
 }

and finally:

final.push.apply(final, resultArray1);
final.push.apply(final, resultArray2);
final.push.apply(final, resultArray3);

Body:
As @ObsidianAge notes, there might be multiple ways to split the input string into matching portions. I would check if the inputs have to be this way, if possible.

I'm not sure what stopped you from pursuing the solution you described... the easiest implementation of this involves recursion:

let base = ["129", "129;176", "129;176;2","131;173;2","242;1","221;188;2","138;7","201;20","251;12","32", "184;3", "176"]
let userCreated = '129;176;2;32;131;173;2;184;3;201;20;251;12';

let appendSemicolon = (str) => str + ";";
let removeSemicolon = (str) => str.substr(0, str.length-1);

base = base.map(appendSemicolon); // so that '1' is not matched as a prefix of '12;34'

function findMatch(input, depth=0) {
  // returns an array of arrays where:
  //    solutions[i].join("") == input
  //    solutions[i][j] is a string from `base`
  // (empty array if no such solutions exist)
  let solutions = [];
  base.forEach((prefix) => {
    if (!input.startsWith(prefix)) return;
    let rest = input.substr(prefix.length);

    if (rest.length === 0) {
      // easy case: the input has a 'perfect match' in `base`
      console.log(" ".repeat(depth) + `checking '${prefix}' - matching complete!`)
      solutions.push([prefix]);
    } else {
      // we found a matching prefix. It will be a valid solution iff
      // the rest of input can be constructed from the strings in `base`
      console.log(" ".repeat(depth) + `checking '${prefix}' (rest='${rest}')`)
      let subSolutions = findMatch(rest, depth+1);
      solutions = solutions.concat(subSolutions.map((sol) => [prefix].concat(sol)));
    }
  });
  return solutions;
}

findMatch(userCreated + ";").map((parts) => parts.map(removeSemicolon));

Note that you didn't specify if duplicate entries are allowed in the input string, I'm not trying to optimize this, and I'm using some syntax from the newer revisions of JS, which may not be universally supported by all browsers yet.


来源: stackexchange

问:
Why tensorflow 1.4 does not allow to assign "None" to FLAGS
I just try to transfer to tensorflow 1.4.

But I noticed that TF1.4 does not support None value flag.

```<code>FLAGS = tf.app.flags.FLAGS
FLAGS.something = None # ERROR!(in TF1.4)
</code>```

Here is my error.

```<code>File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/flags.py", line 66, in __setattr__
self._assert_required(name)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/flags.py", line 74, in _assert_required
raise AttributeError('Flag --%s must be specified.' % flag_name)
</code>```

It seems that self._assert_required raise an error. (it didn't exist in TF1.3)

https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/python/platform/flags.py#L66

Why tensorflow 1.4 does not support None value flag? Is there any reason?

答:
As said here, Tensorflow is trying to make it as close as python-gflags. That's why this module is changed like this.

Also look at the commit message

Add mark_flag_as_required functions to make the APIs compatible with
  python-gflags.

Details could be found here.

ContentLicense: CC BY-SA 3.0

Body:
I just try to transfer to tensorflow 1.4.

But I noticed that TF1.4 does not support None value flag.

FLAGS = tf.app.flags.FLAGS
FLAGS.something = None # ERROR!(in TF1.4)

Here is my error.

File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/flags.py", line 66, in __setattr__
self._assert_required(name)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/flags.py", line 74, in _assert_required
raise AttributeError('Flag --%s must be specified.' % flag_name)

It seems that self._assert_required raise an error. (it didn't exist in TF1.3)

https://github.com/tensorflow/tensorflow/blob/r1.4/tensorflow/python/platform/flags.py#L66

Why tensorflow 1.4 does not support None value flag? Is there any reason?


问:
Case insensitive headers in Nginx Lua
Is there a way we can get case insensitive header response from Nginx Lua?

for example I want:

```<code>content_by_lua_block {
  ngx.header["Set-Cookie"] = { 'aaaaaaaaa' }
  ngx.header["SEt-Cookie"] = { 'a123qwds' }
}
</code>```

The response I get is always the last one. I want both cookies as they are different with case sensitivity

答:
According to the HTTP specification field names are case-insensitive, so both of those field names refer to the same field and the second reference overwrites the first one.

If you expect case-sensitive headers (not case-insensitive ones you currently get), then I don't think it's possible, at least not from a spec-compliant HTTP server. Note that field values are case-sensitive, but not field names.

Title: Case insensitive headers in Nginx Lua

Body:
Is there a way we can get case insensitive header response from Nginx Lua?

for example I want:

content_by_lua_block {
  ngx.header["Set-Cookie"] = { 'aaaaaaaaa' }
  ngx.header["SEt-Cookie"] = { 'a123qwds' }
}

The response I get is always the last one. I want both cookies as they are different with case sensitivity


问:
I have 2 functions in my Javascript.One has multiple ajax calls to get the data and other displays the data.The functions are not executed in sequence
```<code>Sample Code

$( document ).ready(function() {
    getData();
    LoadData();
});

function getData() {
        alert('getData');
        Data='';
        $.ajax({
            type: "GET",
            url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            async: false,
            success: function (json) {
                Data= json;
               alert('Data:' + Data);
            },
            error: function (e) {
                alert('error ' + e.status + '  ' + e.responseText);
            }
        });

}

function LoadData() {
        alert('LoadData');

    }
</code>```

The expected Output:
getData
Data:{"label": "Jan", "Value": "1"}
LoadData

The actual Output :
getData
LoadData
Data:{"label": "Jan", "Value": "1"}

What am I doing wrong.Please help me!!

答:
why don't  you call LoadData() after success?
like below

```<code>$( document ).ready(function() {
    getData();

});

function getData() {
        alert('getData');
        Data='';
        $.ajax({
            type: "GET",
            url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            async: false,
            success: function (json) {
                data= json;
               alert('Data:' + data);
                LoadData();
            },
            error: function (e) {
                alert('error ' + e.status + '  ' + e.responseText);
            }
        });

}

function LoadData() {
        alert('LoadData');

    }
</code>```

UPDATE :

as you said , you are having multiple ajax calls,

one work around could be ,

try setting flag for each ajax call and make them true on respective success event , and lastly you need to call loadData() from all success completion and in loadData(){ ...} body check all the  success are completed or not,

```<code>$( document ).ready(function() {
    getData();
     $flag1= flase;
     $flag2= flase;
     $flag3= flase;
     $flag4= flase;

});

  function LoadData() {
         if($flag1 && $flag2 && $flag3 && $flag4)
             {
                   alert('LoadData');
             }
       }
</code>```

and in each ajax call's success

```<code>         success: function (json) {
            data= json;
           alert('Data:' + data);
           $flag1=true;
            LoadData();
        },
</code>```

and don't forget to make all flag false in $(document).ready(){}

Body:
Sample Code

$( document ).ready(function() {
    getData();
    LoadData();
});

function getData() {
        alert('getData');
        Data='';
        $.ajax({
            type: "GET",
            url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            async: false,
            success: function (json) {
                Data= json;
               alert('Data:' + Data);
            },
            error: function (e) {
                alert('error ' + e.status + '  ' + e.responseText);
            }
        });

}

function LoadData() {
        alert('LoadData');

    }

The expected Output:
getData
Data:{"label": "Jan", "Value": "1"}
LoadData

The actual Output :
getData
LoadData
Data:{"label": "Jan", "Value": "1"}

What am I doing wrong.Please help me!!

Body:
why don't  you call LoadData() after success?
like below

$( document ).ready(function() {
    getData();

});

function getData() {
        alert('getData');
        Data='';
        $.ajax({
            type: "GET",
            url: "http://localhost:34126/SAL/FCDataService.svc/GetMonthlyInvValue",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            async: false,
            success: function (json) {
                data= json;
               alert('Data:' + data);
                LoadData();
            },
            error: function (e) {
                alert('error ' + e.status + '  ' + e.responseText);
            }
        });

}

function LoadData() {
        alert('LoadData');

    }

UPDATE :

as you said , you are having multiple ajax calls,

one work around could be ,

try setting flag for each ajax call and make them true on respective success event , and lastly you need to call loadData() from all success completion and in loadData(){ ...} body check all the  success are completed or not,

$( document ).ready(function() {
    getData();
     $flag1= flase;
     $flag2= flase;
     $flag3= flase;
     $flag4= flase;

});

  function LoadData() {
         if($flag1 && $flag2 && $flag3 && $flag4)
             {
                   alert('LoadData');
             }
       }

and in each ajax call's success

         success: function (json) {
            data= json;
           alert('Data:' + data);
           $flag1=true;
            LoadData();
        },

and don't forget to make all flag false in $(document).ready(){}


问:
Android avoid keyboard covering Edit Text programmatically
I have coded below general, everytime usable functions to display and dismiss keyboard:

|==| Display and Dismiss keyboard Programmatically:

```<code>InputMethodManager iptKeybodMgrVar;

void keybodDspFnc(EditText txtEdtVyuVar)
{
    txtEdtVyuVar.requestFocus();
    if (iptKeybodMgrVar == null)
    {
        iptKeybodMgrVar = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }
    iptKeybodMgrVar.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}

void keybodDsmFnc(EditText txtEdtVyuVar)
{
    iptKeybodMgrVar.hideSoftInputFromWindow(txtEdtVyuVar.getWindowToken(), 0);
}
</code>```

But problem is, When the Edit Text is below Keyboard, The activity does not shift upwards. It shifts only when a user starts typing.

So how do I make it shift upwards as soon as keyboard appears?

I went thru all links below and nothing helped me:

Android: How do I prevent the soft keyboard from pushing my view up?

adjustPan not preventing keyboard from covering EditText

Android : Soft Keyboard covering edit text up (adjustresize or adjustpan doesnt work)

https://readyandroid.wordpress.com/android-soft-keyboard-covers-edittext-field-overscroll-to-soft-keyboard/

I tried and didn't work:

```<code>android:windowSoftInputMode="adjustPan|stateAlwaysHidden"

android:windowSoftInputMode="adjustResize|stateAlwaysHidden"

android:windowSoftInputMode="adjustResize|adjustPan"
</code>```

Also tried this codes:

(So, Not duplicate of :) Move layouts up when soft keyboard is shown?

```<code>getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

//This Code brings up the keyboard at starting of the activity and pushes all Edit Text up. So not useful
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
</code>```

I can add ScrollView but it seems like just workaround and doesn't seem a solution.

Feel there should be a solution programmatically like setting something InputMethodManager.

答:
Your root layout

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/root"
android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <!--extra views-->

    <!--add below layout programmatically-->
    <!--<include layout="@layout/layout_dynamic"/>-->

    </ScrollView>
</RelativeLayout>
</code>```

Dynamic layout

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dynamicLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text" />

</LinearLayout>
</code>```

add view dynamically (no need to specify behaviour)

```<code>private void addEditText(){
    RelativeLayout mRootLayout = (RelativeLayout) findViewById(R.id.root);

    LayoutInflater inflater = LayoutInflater.from(mActivity);
    View newView = inflater.inflate(R.layout.layout_dynamic,mRootLayout);
    EditText editText = (EditText) newView.findViewById(R.id.editText);

    mRootLayout.addView(newView);

}
</code>```

Manifest file

```<code> <activity
        android:name=".MainActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustPan"/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have coded below general, everytime usable functions to display and dismiss keyboard:

|==| Display and Dismiss keyboard Programmatically:

InputMethodManager iptKeybodMgrVar;

void keybodDspFnc(EditText txtEdtVyuVar)
{
    txtEdtVyuVar.requestFocus();
    if (iptKeybodMgrVar == null)
    {
        iptKeybodMgrVar = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }
    iptKeybodMgrVar.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}

void keybodDsmFnc(EditText txtEdtVyuVar)
{
    iptKeybodMgrVar.hideSoftInputFromWindow(txtEdtVyuVar.getWindowToken(), 0);
}

But problem is, When the Edit Text is below Keyboard, The activity does not shift upwards. It shifts only when a user starts typing.

So how do I make it shift upwards as soon as keyboard appears?

I went thru all links below and nothing helped me:

Android: How do I prevent the soft keyboard from pushing my view up?

adjustPan not preventing keyboard from covering EditText

Android : Soft Keyboard covering edit text up (adjustresize or adjustpan doesnt work)

https://readyandroid.wordpress.com/android-soft-keyboard-covers-edittext-field-overscroll-to-soft-keyboard/

I tried and didn't work:

android:windowSoftInputMode="adjustPan|stateAlwaysHidden"

android:windowSoftInputMode="adjustResize|stateAlwaysHidden"

android:windowSoftInputMode="adjustResize|adjustPan"

Also tried this codes:

(So, Not duplicate of :) Move layouts up when soft keyboard is shown?

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

//This Code brings up the keyboard at starting of the activity and pushes all Edit Text up. So not useful
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

I can add ScrollView but it seems like just workaround and doesn't seem a solution.

Feel there should be a solution programmatically like setting something InputMethodManager.

Body:
Your root layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/root"
android:layout_height="match_parent">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <!--extra views-->

    <!--add below layout programmatically-->
    <!--<include layout="@layout/layout_dynamic"/>-->

    </ScrollView>
</RelativeLayout>

Dynamic layout

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dynamicLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text" />

</LinearLayout>

add view dynamically (no need to specify behaviour)

private void addEditText(){
    RelativeLayout mRootLayout = (RelativeLayout) findViewById(R.id.root);

    LayoutInflater inflater = LayoutInflater.from(mActivity);
    View newView = inflater.inflate(R.layout.layout_dynamic,mRootLayout);
    EditText editText = (EditText) newView.findViewById(R.id.editText);

    mRootLayout.addView(newView);

}

Manifest file

 <activity
        android:name=".MainActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustPan"/>


问:
jQuery datepicker display year month only
I am using datepicker to select year-month only. I filter out the day part like so:

```<code>$(el).datepicker(
{changeMonth: true,
changeYear: true,
dateFormat:'yymm' }
);
</code>```

The code comes from the dataInit option in jqGrid.
When the user clicks in a day only the year-month is passed back to the input box.

Is there any way to just show months where the days are?

Thanks.

答:
Well, if you're not tied to the datepicker plugin, you could use one of the "monthpickers" that are available, like this one: http://plugins.jquery.com/project/monthpicker.

(Edit) there's also a previous discussion here: In search of JavaScript Month Picker.

ContentLicense: CC BY-SA 2.5

Body:
I am using datepicker to select year-month only. I filter out the day part like so:

$(el).datepicker(
{changeMonth: true,
changeYear: true,
dateFormat:'yymm' }
);

The code comes from the dataInit option in jqGrid.
When the user clicks in a day only the year-month is passed back to the input box.

Is there any way to just show months where the days are?

Thanks.


问:
Built-in libraries to persist a BTree, equivalent to Java's `FileChannel` and `ByteBuffer`
So, I wrote this persistent BTree in Java, following the CLRS algorithms.
I used FileChannel and ByteBuffer to store the tree in a file, reading and writing the nodes when needed.

I tried looking how I could store such a BTree in Go, and discovered os.File, which I think could be used the same way as Java's FileChannel.
However, I could not find an equivalent for ByteBuffer. I looked at bytes.Buffer, and I see how this could work, however it does not have the ByteBuffer's handy putInt, putDouble, etc...

Would I have to implement myself those function to transform ints and doubles to byte arrays? I also looked at encoding.binary, but this looks very cumbersome. I understand that I would have to encode my variables to a byte array every time, then copy that byte array to the buffer.

What structures would be recommended in this case?

答:
Note that bytes.Buffer implements the io.Writer interface. As a result, you can use fmt.Fprintf:

```<code>func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
</code>```

format string parameter can be used to write ints and doubles directly into the buffer. See here for details.

Body:
Note that bytes.Buffer implements the io.Writer interface. As a result, you can use fmt.Fprintf:

func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)

format string parameter can be used to write ints and doubles directly into the buffer. See here for details.


问:
Disconnected from Server in shinyapps, but local's working
I deployed my Shiny code to shinyapps.io successful.
My data has little much rows (over 190,000), these data's can display in my local PC but shinyapps cannot with 'Disconnected from the server.'

So I get Basic-plan and set memory size is xxxlarge and config some other settings.

But my apps shut-down with 'Disconnected from the server.' continue..

How can I set my server setting?

Please help me, and sorry my bad English.

Here is server log and url
https://tmap.shinyapps.io/break_map/
(RN count 3~19, and all select mech_cd, then shut-down)

```<code>2016-08-24T05:34:08.539162+00:00 shinyapps[121340]: Server version: 0.4.5.2170
2016-08-24T05:34:08.539194+00:00 shinyapps[121340]: R version: 3.3.0
2016-08-24T05:34:08.539201+00:00 shinyapps[121340]: shiny version: 0.13.2
2016-08-24T05:34:08.539203+00:00 shinyapps[121340]: rmarkdown version: NA
2016-08-24T05:34:08.539204+00:00 shinyapps[121340]: knitr version: NA
2016-08-24T05:34:08.539212+00:00 shinyapps[121340]: RJSONIO version: NA
2016-08-24T05:34:08.539204+00:00 shinyapps[121340]: jsonlite version: 0.9.19
2016-08-24T05:34:08.539212+00:00 shinyapps[121340]: htmltools version: 0.3.5
2016-08-24T05:34:08.754267+00:00 shinyapps[121340]: Using jsonlite for JSON processing
2016-08-24T05:34:08.758255+00:00 shinyapps[121340]:
2016-08-24T05:34:08.758256+00:00 shinyapps[121340]: Starting R with process ID: '17'
2016-08-24T05:34:08.964272+00:00 shinyapps[121340]: Loading required package: gsubfn
2016-08-24T05:34:08.970689+00:00 shinyapps[121340]: Loading required package: proto
2016-08-24T05:34:09.000933+00:00 shinyapps[121340]: Warning: no DISPLAY variable so Tk is not available
2016-08-24T05:34:09.011202+00:00 shinyapps[121340]: Loading required package: RSQLite
2016-08-24T05:34:09.016999+00:00 shinyapps[121340]: Loading required package: DBI
2016-08-24T05:34:10.597571+00:00 shinyapps[121340]: Loading required package: tcltk
2016-08-24T05:34:12.215392+00:00 shinyapps[121340]:
2016-08-24T05:34:12.215396+00:00 shinyapps[121340]: Listening on http://0.0.0.0:60468
</code>```

答:
You might be using setwd() in your code. Delete that line or comment it out so you can later choose to run it when running your app locally. Then try again.

```<code>#Set wd if running code locally----
#setwd("/Users/Dropbox/YourPathHere/")
</code>```

Body:
I deployed my Shiny code to shinyapps.io successful.
My data has little much rows (over 190,000), these data's can display in my local PC but shinyapps cannot with 'Disconnected from the server.'

So I get Basic-plan and set memory size is xxxlarge and config some other settings.

But my apps shut-down with 'Disconnected from the server.' continue..

How can I set my server setting?

Please help me, and sorry my bad English.

Here is server log and url
https://tmap.shinyapps.io/break_map/
(RN count 3~19, and all select mech_cd, then shut-down)

2016-08-24T05:34:08.539162+00:00 shinyapps[121340]: Server version: 0.4.5.2170
2016-08-24T05:34:08.539194+00:00 shinyapps[121340]: R version: 3.3.0
2016-08-24T05:34:08.539201+00:00 shinyapps[121340]: shiny version: 0.13.2
2016-08-24T05:34:08.539203+00:00 shinyapps[121340]: rmarkdown version: NA
2016-08-24T05:34:08.539204+00:00 shinyapps[121340]: knitr version: NA
2016-08-24T05:34:08.539212+00:00 shinyapps[121340]: RJSONIO version: NA
2016-08-24T05:34:08.539204+00:00 shinyapps[121340]: jsonlite version: 0.9.19
2016-08-24T05:34:08.539212+00:00 shinyapps[121340]: htmltools version: 0.3.5
2016-08-24T05:34:08.754267+00:00 shinyapps[121340]: Using jsonlite for JSON processing
2016-08-24T05:34:08.758255+00:00 shinyapps[121340]:
2016-08-24T05:34:08.758256+00:00 shinyapps[121340]: Starting R with process ID: '17'
2016-08-24T05:34:08.964272+00:00 shinyapps[121340]: Loading required package: gsubfn
2016-08-24T05:34:08.970689+00:00 shinyapps[121340]: Loading required package: proto
2016-08-24T05:34:09.000933+00:00 shinyapps[121340]: Warning: no DISPLAY variable so Tk is not available
2016-08-24T05:34:09.011202+00:00 shinyapps[121340]: Loading required package: RSQLite
2016-08-24T05:34:09.016999+00:00 shinyapps[121340]: Loading required package: DBI
2016-08-24T05:34:10.597571+00:00 shinyapps[121340]: Loading required package: tcltk
2016-08-24T05:34:12.215392+00:00 shinyapps[121340]:
2016-08-24T05:34:12.215396+00:00 shinyapps[121340]: Listening on http://0.0.0.0:60468

Body:
You might be using setwd() in your code. Delete that line or comment it out so you can later choose to run it when running your app locally. Then try again.

#Set wd if running code locally----
#setwd("/Users/Dropbox/YourPathHere/")


问:
Get the time difference between two datetimes
I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I'm having a hard time trying to do something that seems simple: geting the difference between 2 times.

Example:

```<code>var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

//expected result:
"00:39:30"
</code>```

what I tried:

```<code>var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");

console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30
</code>```

I do not understand what is that "10" there. I live in Brazil, so we are utc-0300 if that is relevant.

The result of moment.duration(now.diff(then)) is a duration with the correct internal values:

```<code> days: 0
 hours: 0
 milliseconds: 0
 minutes: 39
 months: 0
 seconds: 30
 years: 0
</code>```

So, I guess my question is: how to convert a momentjs Duration to a time interval? I sure can use

```<code>duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")
</code>```

but i feel that there is something more elegant that I am completely missing.

update

looking closer, in the above example now is:

```<code>Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}
</code>```

and moment(moment.duration(now.diff(then))) is:

```<code>Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}
</code>```

I am not sure why the second value is in Daylight Time (-0200)... but I am sure that i do not like dates :(

update 2

well, the value is -0200 probably because 31/12/1969 was a date where the daylight time was being used... so thats that.

答:
In ES8 using moment, now and start being moment objects.</p>

```<code>const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
</code>```

Body:
I know I can do anything and some more envolving Dates with momentjs. But embarrassingly, I'm having a hard time trying to do something that seems simple: geting the difference between 2 times.

Example:

var now  = "04/09/2013 15:00:00";
var then = "04/09/2013 14:20:30";

//expected result:
"00:39:30"

what I tried:

var now = moment("04/09/2013 15:00:00");
var then = moment("04/09/2013 14:20:30");

console.log(moment(moment.duration(now.diff(then))).format("hh:mm:ss"))
//outputs 10:39:30

I do not understand what is that "10" there. I live in Brazil, so we are utc-0300 if that is relevant.

The result of moment.duration(now.diff(then)) is a duration with the correct internal values:

 days: 0
 hours: 0
 milliseconds: 0
 minutes: 39
 months: 0
 seconds: 30
 years: 0

So, I guess my question is: how to convert a momentjs Duration to a time interval? I sure can use

duration.get("hours") +":"+ duration.get("minutes") +:+ duration.get("seconds")

but i feel that there is something more elegant that I am completely missing.

update

looking closer, in the above example now is:

Tue Apr 09 2013 15:00:00 GMT-0300 (E. South America Standard Time)…}

and moment(moment.duration(now.diff(then))) is:

Wed Dec 31 1969 22:39:30 GMT-0200 (E. South America Daylight Time)…}

I am not sure why the second value is in Daylight Time (-0200)... but I am sure that i do not like dates :(

update 2

well, the value is -0200 probably because 31/12/1969 was a date where the daylight time was being used... so thats that.

Body:
In ES8 using moment, now and start being moment objects.

const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');


问:
How to remove the nuget Packages folder from TFS?
I just went through a dll hell. Turns out that TFS has been synchronizing packages, and I ended up with two versions of Microsoft.Web.Optimization and its dependencies at once. NuGet was convinced that I have the newest versions installed, and even reinstallation changed nothing. But at the same time, my projects wouldn't build or, if they'd build, they wouldn't start, complaining that they can't find the library version given in the manifest.

I managed to solve it by uninstalling the packages from NuGet console, physically removing their folders from the hard disc, and then doing a fresh build (which re-installed the missing latest versions). But the package folders I deleted manually are still sitting around in the Source Control Explorer. And I can't delete them, the Delete button is greyed out when I select one of them. I am afraid that they will come again when I get newest version next time.

How do I prevent it? I would like to remove them from the solution completely. In the worst case, it would be OK to ignore them, but as they are on a level above the projects, I can't enter them into a project's .tfignore file, and Visual Studio didn't let me add a .tfignore file to the solution itself.

答:
Arguably best answered in this post:
https://stackoverflow.com/a/40409464/1690217

The NuGet documentation provides instructions on how to accomplish this and I just followed them successfully for Visual Studio 2015 against VSTS (Azure-hosted TFS). Everything is fully updated as of Nov 2016. This also still works for Visual Studio 2017 RTM (March 2017).

I added the following files as explained above:

.tfignore

```<code>\packages
!\packages\repositories.config
</code>```

.nuget\nugget.config

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <solution>
    <add key="disableSourceControlIntegration" value="true" />
  </solution>
</configuration>
</code>```

I had to delete the packages folder and checkin the delete, then package restore will kickin and rebuild the folder but VS will no longer automatically add it to source control.

Body:
Arguably best answered in this post:
https://stackoverflow.com/a/40409464/1690217

The NuGet documentation provides instructions on how to accomplish this and I just followed them successfully for Visual Studio 2015 against VSTS (Azure-hosted TFS). Everything is fully updated as of Nov 2016. This also still works for Visual Studio 2017 RTM (March 2017).

I added the following files as explained above:

.tfignore

\packages
!\packages\repositories.config

.nuget\nugget.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <solution>
    <add key="disableSourceControlIntegration" value="true" />
  </solution>
</configuration>

I had to delete the packages folder and checkin the delete, then package restore will kickin and rebuild the folder but VS will no longer automatically add it to source control.


问:
Not receiving push notifications if sending "data" (but "notification" works) payloads to GCM/FCM in iOS didReceiveRemoteNotification
I am trying to get "data" payload notifications to be received for our iOS app.

Today we can send GCM notification push notifications as according to:

https://developers.google.com/cloud-messaging/concept-options

(FCM has the same text)

An easy test is using CURL:

```<code>curl -X POST \
  https://gcm-http.googleapis.com/gcm/send \
  -H 'authorization: key=##_GCM_SERVER_ID_##' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'postman-token: ##_POSTMAN_TOKEN_##' \
  -d '{
    "notification": {
        "body": "Test body"
    },
    "to" : "##_DEVICE_TOKEN_##"
}
'
</code>```

This will successfully trigger iOS AppDelegate.didReceiveRemoteNotification:fetchCompletionHandler function.

However, if change it to a data notification:

```<code>curl -X POST \
  https://gcm-http.googleapis.com/gcm/send \
  -H 'authorization: key=##_GCM_SERVER_ID_##' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'postman-token: ##_POSTMAN_TOKEN_##' \
  -d '{
    "data": {
        "body": "Test body"
    },
    "to" : "##_DEVICE_TOKEN_##"
}
'
</code>```

I can't see anything is being sent to the app from GCM (in either didReceiveRemoteNotification functions), even if the app is in background/foreground.

Even though it says in the documentation it should:

https://developers.google.com/cloud-messaging/concept-options#notifications_and_data_messages

Note these further platform-specific details:

On Android, data payload can be retrieved in the Intent used to launch your activity.

On iOS, data payload will be found in didReceiveRemoteNotification:.

GCM can handle pure data push notifications to the APN network right?

Do I need to do anything special to receive data, compared to notification, Push Notifications in iOS?

答:
When sending the Data type message with FCM to iOS devices, they will only be received if content_available is set to true in your FCM request body, eg:

```<code>{
    "to": "--fcm-token--",
    "content_available": true,
    "data": {
        "priority": "high",
        "hello": "world"
    }
}
</code>```

Body:
I am trying to get "data" payload notifications to be received for our iOS app.

Today we can send GCM notification push notifications as according to:

https://developers.google.com/cloud-messaging/concept-options

(FCM has the same text)

An easy test is using CURL:

curl -X POST \
  https://gcm-http.googleapis.com/gcm/send \
  -H 'authorization: key=##_GCM_SERVER_ID_##' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'postman-token: ##_POSTMAN_TOKEN_##' \
  -d '{
    "notification": {
        "body": "Test body"
    },
    "to" : "##_DEVICE_TOKEN_##"
}
'

This will successfully trigger iOS AppDelegate.didReceiveRemoteNotification:fetchCompletionHandler function.

However, if change it to a data notification:

curl -X POST \
  https://gcm-http.googleapis.com/gcm/send \
  -H 'authorization: key=##_GCM_SERVER_ID_##' \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'postman-token: ##_POSTMAN_TOKEN_##' \
  -d '{
    "data": {
        "body": "Test body"
    },
    "to" : "##_DEVICE_TOKEN_##"
}
'

I can't see anything is being sent to the app from GCM (in either didReceiveRemoteNotification functions), even if the app is in background/foreground.

Even though it says in the documentation it should:

https://developers.google.com/cloud-messaging/concept-options#notifications_and_data_messages

Note these further platform-specific details:

On Android, data payload can be retrieved in the Intent used to launch your activity.

On iOS, data payload will be found in didReceiveRemoteNotification:.

GCM can handle pure data push notifications to the APN network right?

Do I need to do anything special to receive data, compared to notification, Push Notifications in iOS?

Body:
When sending the Data type message with FCM to iOS devices, they will only be received if content_available is set to true in your FCM request body, eg:

{
    "to": "--fcm-token--",
    "content_available": true,
    "data": {
        "priority": "high",
        "hello": "world"
    }
}


问:
iterate through multiple lists with python
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

```<code>pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i
</code>```

My source data is as follows:

```<code>CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
</code>```

UserID and Page Number
eeIDlist:

```<code>[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]
</code>```

Desired Output List:

```<code>[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]
</code>```

答:
You have some errors in your code.

You don't need the loop for ee in i. You want to check if '123214' in ['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'] for example not if 123214 in '144128', and in '40013', and in 'John', etc.

Also, you don't need i.append([eeid[0]]) since you are dealing with pagenumbers, and that's enough; you don't want duplicates in your results.

Moreover, pagenumbers should be appended outside the for loop. Otherwise, you would get more than one list appended.

Following is a code that fixes errors of your code:

```<code>CompanyNameList = [
    ['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],
    ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],
    ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],
    ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

eeIDlist = [[144128,1],
            [144138,12],
            [144130,6],
            [144131,9],
            [40013,153],
            [40074,310],
            [40023, 210],
            [40050,250]]

pagenumbers=[]

for i in CompanyNameList:
    for eeid in eeIDlist:
        try:
            # eeid[0] not eeid[1]
            if (str(eeid[0]) in i):
                # eeid[1] not eeid[0]
                pagenumbers.extend([eeid[1]])
        except ValueError:
            print ("Not a valid number")
    i.append(pagenumbers)
    pagenumbers = []

print CompanyNameList
</code>```

Output:

```<code>[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]],
 ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]],
 ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]],
 ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]
</code>```

Body:
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i

My source data is as follows:

CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

UserID and Page Number
eeIDlist:

[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]

Desired Output List:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]

Body:
You have some errors in your code.

You don't need the loop for ee in i. You want to check if '123214' in ['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'] for example not if 123214 in '144128', and in '40013', and in 'John', etc.

Also, you don't need i.append([eeid[0]]) since you are dealing with pagenumbers, and that's enough; you don't want duplicates in your results.

Moreover, pagenumbers should be appended outside the for loop. Otherwise, you would get more than one list appended.

Following is a code that fixes errors of your code:

CompanyNameList = [
    ['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],
    ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],
    ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],
    ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

eeIDlist = [[144128,1],
            [144138,12],
            [144130,6],
            [144131,9],
            [40013,153],
            [40074,310],
            [40023, 210],
            [40050,250]]

pagenumbers=[]

for i in CompanyNameList:
    for eeid in eeIDlist:
        try:
            # eeid[0] not eeid[1]
            if (str(eeid[0]) in i):
                # eeid[1] not eeid[0]
                pagenumbers.extend([eeid[1]])
        except ValueError:
            print ("Not a valid number")
    i.append(pagenumbers)
    pagenumbers = []

print CompanyNameList

Output:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]],
 ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]],
 ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]],
 ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]


问:
Call a method from an activity from an adapter
I am working with an adapter which has several buttons on each item of the ListView. I have, for example two buttons. One for save and another for delete.

When I click on them, I want the adapter to refresh. I have a method on my activity that does that: Update the adapter. I made it since I couldn't make the Notify methods of the adapter work.

I am sending the Activity to the adapter as a parameter and then call the update method from the adapter since I am setting the OnClick methods of each button in the adapter.

The problem is that it doesnt seem to work always. I am guessing it has to do something about the cycle of the activity and Android cleaning memory however I can't seem to understand where is the problem.

I am aware this is some ugly way of doing it, so what should be the best way of doing this?

Summary: I need to refresh the adapter from the adapter itself when I delete an item of the ListView or update it (BaseAdapter)

Edit:
I am adding some code. This is my constructor of my adapter:

```<code>public SpendingPlanAdapter(Context context, SpendingPlan sp, int month, int year, money.activities.SpendingPlan act)
</code>```

Inside the adapter I have an OnCLickListener attached to a button. I am calling the update method like this (Result is the result of a database insert):

```<code>if (result){
                    Toast.makeText(context, context.getResources().getString(R.string.succesfully_deleted), Toast.LENGTH_LONG).show();
                    act.updateAdapter();
                } else {
                    Toast.makeText(context, context.getResources().getString(R.string.oops), Toast.LENGTH_LONG).show();}
</code>```

And this is my UpdateAdapter method:

```<code>public void updateAdapter(){
        SpendingPlanAdapter adapter = new SpendingPlanAdapter(getApplicationContext(), currentSp, currentMonth, currentYear, this);
        limitList.setAdapter(adapter);
    }
</code>```

答:
You can call updateAdapter() like this

```<code>(SpendingPlan (context)).updateAdapter();
</code>```

Body:
I am working with an adapter which has several buttons on each item of the ListView. I have, for example two buttons. One for save and another for delete.

When I click on them, I want the adapter to refresh. I have a method on my activity that does that: Update the adapter. I made it since I couldn't make the Notify methods of the adapter work.

I am sending the Activity to the adapter as a parameter and then call the update method from the adapter since I am setting the OnClick methods of each button in the adapter.

The problem is that it doesnt seem to work always. I am guessing it has to do something about the cycle of the activity and Android cleaning memory however I can't seem to understand where is the problem.

I am aware this is some ugly way of doing it, so what should be the best way of doing this?

Summary: I need to refresh the adapter from the adapter itself when I delete an item of the ListView or update it (BaseAdapter)

Edit:
I am adding some code. This is my constructor of my adapter:

public SpendingPlanAdapter(Context context, SpendingPlan sp, int month, int year, money.activities.SpendingPlan act)

Inside the adapter I have an OnCLickListener attached to a button. I am calling the update method like this (Result is the result of a database insert):

if (result){
                    Toast.makeText(context, context.getResources().getString(R.string.succesfully_deleted), Toast.LENGTH_LONG).show();
                    act.updateAdapter();
                } else {
                    Toast.makeText(context, context.getResources().getString(R.string.oops), Toast.LENGTH_LONG).show();}

And this is my UpdateAdapter method:

public void updateAdapter(){
        SpendingPlanAdapter adapter = new SpendingPlanAdapter(getApplicationContext(), currentSp, currentMonth, currentYear, this);
        limitList.setAdapter(adapter);
    }

Body:
You can call updateAdapter() like this

(SpendingPlan (context)).updateAdapter();


问:
How to check for duplicates in an entire 2d array?
I am a beginner coder just learning arrays. I recently learned 2d arrays and I am trying to find out if there is a duplicate in a 2d array. I know how to check if there is a duplicate in the same column or row, but I cannot figure out how to compare a number if it is not in the same column or row as the number I am trying to compare it to. Here is my code as of now:

```<code>public static boolean correctNumbers(int[][] values) {
    for (int i = 0; i < values.length; i++) {
        for (int j = 0; j < values[i].length; j++) {
            int num = values[i][j];
            for (int k = j + 1; k < values.length; k++) {
                if (num == values[i][k] || num > values.length * values.length || num < 1) {
                    return false;
                }
            }
            for (int l = i + 1; l < values.length; l++) {
                if (num == values[l][j] || num > values.length * values.length || num < 1) {
                    return false;
                }
            }
        }
    }

    return true;
}
</code>```

I need to create a method and I cannot use any other methods in creating it.
Thanks for the help!

Edit: It returns false if there is duplicates in the array, a number in the array is less than 1, or greater than total number of elements in the array. In other words this method is checking to see if the array contains all the values of 1 to (i*j) in the array. I realized I did a bad job of explaining that part. Thanks again!

答:
You can simplify the logic by saving the numbers into a hashset and when you're iterating them check each one if it's already there (meaning duplicate) otherwise add it:

```<code>public static boolean correctNumbers(int[][] values) {
    Set<Integer> set = new HashSet<>();
    for (int i = 0; i < values.length; i++) {
        for (int j = 0; j < values[i].length; j++) {
            int num = values[i][j];
            if (set.contains(num)) {
                return false;
            }
            set.add(num);
        }
    }
    return true;
}
</code>```

EDIT

We can use an array for the same functionality the hashset is doing in the code above:

```<code>public static boolean correctNumbers(int[][] values) {
    int n = values.length;
    int[] dict = new int[n * n + 1];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < values[i].length; j++) {
            int num = values[i][j];
            if (num < 1 || num > n || dict[num] != 0) {
                return false;
            }
            dict[num] = 1;
        }
    }
    return true;
}
</code>```

Body:
I am a beginner coder just learning arrays. I recently learned 2d arrays and I am trying to find out if there is a duplicate in a 2d array. I know how to check if there is a duplicate in the same column or row, but I cannot figure out how to compare a number if it is not in the same column or row as the number I am trying to compare it to. Here is my code as of now:

public static boolean correctNumbers(int[][] values) {
    for (int i = 0; i < values.length; i++) {
        for (int j = 0; j < values[i].length; j++) {
            int num = values[i][j];
            for (int k = j + 1; k < values.length; k++) {
                if (num == values[i][k] || num > values.length * values.length || num < 1) {
                    return false;
                }
            }
            for (int l = i + 1; l < values.length; l++) {
                if (num == values[l][j] || num > values.length * values.length || num < 1) {
                    return false;
                }
            }
        }
    }

    return true;
}

I need to create a method and I cannot use any other methods in creating it.
Thanks for the help!

Edit: It returns false if there is duplicates in the array, a number in the array is less than 1, or greater than total number of elements in the array. In other words this method is checking to see if the array contains all the values of 1 to (i*j) in the array. I realized I did a bad job of explaining that part. Thanks again!

Body:
You can simplify the logic by saving the numbers into a hashset and when you're iterating them check each one if it's already there (meaning duplicate) otherwise add it:

public static boolean correctNumbers(int[][] values) {
    Set<Integer> set = new HashSet<>();
    for (int i = 0; i < values.length; i++) {
        for (int j = 0; j < values[i].length; j++) {
            int num = values[i][j];
            if (set.contains(num)) {
                return false;
            }
            set.add(num);
        }
    }
    return true;
}

EDIT

We can use an array for the same functionality the hashset is doing in the code above:

public static boolean correctNumbers(int[][] values) {
    int n = values.length;
    int[] dict = new int[n * n + 1];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < values[i].length; j++) {
            int num = values[i][j];
            if (num < 1 || num > n || dict[num] != 0) {
                return false;
            }
            dict[num] = 1;
        }
    }
    return true;
}


问:
Connect tables with a specific role
I have 3 roles in my application visitor , individual , facility , and 4 services with table for each one that takes the id of the user

```<code>   - Visitor:-  will have no services
   - Individual:-  will have 2 services
   - Facility:-  will have 3 services
</code>```

I want to connect the roles with the services tables so that each role can only connect to the table with the service it can provide ....  How can I map this with ASP Identity and SQL Server ?

答:
Try This design

I'm adding some sample records below with the given structure

Here there are 3 users and 4 roles.

UserId 2 (Individual) has got 2 roles

RoleId 2 : Admin

RolesId 3 : Normal User

UserId 3 (Facility) has got 3 roles

RoleId 1 : Super Admin

RoleId 2 : Admin

RoleId 3 : Normal User

the below query can be used to retrieve the user roles

```<code>SELECT
*
FROM Users U
INNER JOIN UserRoles UR
  ON U.UserId = UR.UserId
INNER JOIN Roles R
  ON R.RoleId = UR.RoleId
WHERE ISNULL(Ur.ActFl,0)=1--1 : For Active Roles, 0 - For Inactive Roles
</code>```

Title: Connect tables with a specific role

Body:
I have 3 roles in my application visitor , individual , facility , and 4 services with table for each one that takes the id of the user

   - Visitor:-  will have no services
   - Individual:-  will have 2 services
   - Facility:-  will have 3 services

I want to connect the roles with the services tables so that each role can only connect to the table with the service it can provide ....  How can I map this with ASP Identity and SQL Server ?

Body:
Try This design

I'm adding some sample records below with the given structure

Here there are 3 users and 4 roles.

UserId 2 (Individual) has got 2 roles

RoleId 2 : Admin

RolesId 3 : Normal User

UserId 3 (Facility) has got 3 roles

RoleId 1 : Super Admin

RoleId 2 : Admin

RoleId 3 : Normal User

the below query can be used to retrieve the user roles

SELECT
*
FROM Users U
INNER JOIN UserRoles UR
  ON U.UserId = UR.UserId
INNER JOIN Roles R
  ON R.RoleId = UR.RoleId
WHERE ISNULL(Ur.ActFl,0)=1--1 : For Active Roles, 0 - For Inactive Roles


问:
woocommerce multiple products recipe page
I am currently looking for a solution for recipe pages.

Basically, I will have a blog post recipes where we will use our products to make something and users can read. I would like to add a button below the recipe page for example "Make this recipe" and when the button is clicked, all the ingredients that are used to make this recipe are added to the cart.

Is there a plugin that I can use so when I write the blog post, I can select the products that is added to the cart for different recipes?

Or do I need to get a developer to do this?

答: Use WooCommerce Product Bundles, this will allow you to bundle all the ingredients into one product which you can add via a shortcode ie [add_to_cart id="99"] on the post.


问:
Pig dump command getting stuck at 0%
I'm working on an Ubuntu VM, I have a file A.txt which has a below data

```<code>1,2,3
4,5,6
</code>```

and I used below pig relation command:

```<code>a = load '/files/A.txt';
</code>```

then I used the command below to dump a:

```<code>dump a;
</code>```

but it is getting stuck at 0% completion. Please help.

答:
I guess your not loading data appropriately using Pig.

Please find below approach to load data and dump it.

a = load '/files/A.txt' using PigStorage(',') as (x:int, y:int, z:int)

dump a;

Title: Pig dump command getting stuck at 0%

Body:
I'm working on an Ubuntu VM, I have a file A.txt which has a below data

1,2,3
4,5,6

and I used below pig relation command:

a = load '/files/A.txt';

then I used the command below to dump a:

dump a;

but it is getting stuck at 0% completion. Please help.


问:
How can I translate my programmatic WCF configuration into app.config
I have an self hosted WCF server with hard coded configurations. the server worked fine until I tried to implement some new configurations functionality (changed ports,  added ssl) the new config setting did not work (urrr.... ) and I find it hard to locate where are the problems in my code.

instead of digging inside the code that declares the WCF object, I thought about different approach:

Is there any way to dump-to-file those hard coded WCF configuration (the entire  ) into app.config like text file after all configurations are loaded? this will enable me to have a easy global view of the entire settings ..

mmm .. .by the way, does anyone know a way that will do the translation to the opposite direction? config to code.

Any advice will be welcomed!

ofer

答:
I don't think you will find an automatic way to dump your c#/vb code somewhere and have your configuration converted to the config file xml schema (and vice-versa), however if you ask my personal opinion, if you don't have a strong reason to hard-code your configuration in your code (even if you do so, I would rethink that), you should move the wcf configuration out from your code. Configuration is not responsibility of the code. It is configuration, meaning that if you need to change the "configuration", you don't need a new build.

In your code, you should just concentrate in the service consumption logic, leaving the configuration to the back-end engine take care of it. Remember that sometimes you may need adjust some settings, like service throttling, max/min buffer size, MaxItemsInObjectGraph quota, etc. If hard-coded, means a new deployment. If in a config file or other repository, means a simple configuration change.

If you have all your configuration in a config file, when you move your code from environment to environment (Dev, DIT, QA, UAT, Pre-Prod, Production), you can have different settings between environments, if required (because the port number you used is already in use or is blocked in the firewall). The release management team will just configure it properly in the config file.

If you want more control over your service configuration, you could consider creating a factory service for your services, where will get all your configuration from a centralized place (database, xml file, etc), and you will configure your code on-the-fly.

I hope it helps...


问:
Merge multiple row then left join-php mysql
I have two tables: invoices and sales. These are simplified version of them:

Invoices:

```<code>InvoiceNo  |  ProductNo  |  QtyIn
-----------------------------------
F01        |  00001      |  20
F01        |  00002      |  50
F01        |  00003      |  15
F02        |  00002      |  10
</code>```

Sales:

```<code>Date    |  ProductNo  |  QtyOut
---------------------------------
3/2/17  |  00002      |  12
3/3/17  |  00002      |  8
3/4/17  |  00003      |  10
</code>```

What I'm trying to do is to make a stock summary table, which looks like this:

```<code>ProductNo  |  QtyIn  |  QtyOut  |  Stock
-------------------------------------------
00001      |  20     |  0       |  20
00002      |  60     |  20      |  40
00003      |  15     |  10      |  5
</code>```

To make that stock table, as far as I can think is:

Make another database for invoice where same product will be merge
and it's quantity will be sum up.

Make something like the first one for sales.

Then make a join table for both of them.

By this way, I will end up having 5 tables. Is there any simpler way to do this? Thanks.

答:
Mysql Query is</p>

```<code>Select a.ProductNo , a.QtyIn, b.QtyOut, a.QtyIn-b.QtyOut as "Stock" from Invoices a join Sales b on a.productNo=q.productNo
</code>```

Body:
I have two tables: invoices and sales. These are simplified version of them:

Invoices:

InvoiceNo  |  ProductNo  |  QtyIn
-----------------------------------
F01        |  00001      |  20
F01        |  00002      |  50
F01        |  00003      |  15
F02        |  00002      |  10

Sales:

Date    |  ProductNo  |  QtyOut
---------------------------------
3/2/17  |  00002      |  12
3/3/17  |  00002      |  8
3/4/17  |  00003      |  10

What I'm trying to do is to make a stock summary table, which looks like this:

ProductNo  |  QtyIn  |  QtyOut  |  Stock
-------------------------------------------
00001      |  20     |  0       |  20
00002      |  60     |  20      |  40
00003      |  15     |  10      |  5

To make that stock table, as far as I can think is:

Make another database for invoice where same product will be merge
and it's quantity will be sum up.

Make something like the first one for sales.

Then make a join table for both of them.

By this way, I will end up having 5 tables. Is there any simpler way to do this? Thanks.

Body:
Mysql Query is

Select a.ProductNo , a.QtyIn, b.QtyOut, a.QtyIn-b.QtyOut as "Stock" from Invoices a join Sales b on a.productNo=q.productNo


问:
Both if and else part are executing
```<code>  /*Q_INVOKABLE*/ void LinkDestUI::selectDeselectSingleDestination(int iXmlId)
{
   for(const auto &subNode : m_nodeColl)
   {
      if(bMultipleSelect())
      {
         if(subNode->getXmlId() == iXmlId)
         {
             LOG(Severity_Error)<<"1 ";
            subNode->setbSelected(!subNode->bSelected());
         }
      }
      else
      {
         if(subNode->getXmlId() == iXmlId)
         {
             LOG(Severity_Error)<<"2 ";
            subNode->setbSelected(!subNode->bSelected());
         }
         else
         {
             LOG(Severity_Error)<<"3 ";
            subNode->setbSelected(false);
         }
      }
   }
}
</code>```

When i execute my code then compiler goes to else part and exceute both if and else statement inside the else part. why?

答:
That seems ... (temporarily increasing my tactfulness attribute so as to avoid offending) ... rather unlikely :-)

It's probably because the code is being entered more than once and you're just assuming it's executing both parts because of the output.

My advice would be to change the code in the outer else to be:

```<code>LOG(Severity_Error)<<"Starting inner if ";
if(subNode->getXmlId() == iXmlId)
{
    LOG(Severity_Error)<<"2 ";
    subNode->setbSelected(!subNode->bSelected());
}
else
{
    LOG(Severity_Error)<<"3 ";
    subNode->setbSelected(false);
}
LOG(Severity_Error)<<"Ending inner if ";
</code>```

You should not see both blocks executing without an intervening end/start message set.

Title: Both if and else part are executing

Body:
  /*Q_INVOKABLE*/ void LinkDestUI::selectDeselectSingleDestination(int iXmlId)
{
   for(const auto &subNode : m_nodeColl)
   {
      if(bMultipleSelect())
      {
         if(subNode->getXmlId() == iXmlId)
         {
             LOG(Severity_Error)<<"1 ";
            subNode->setbSelected(!subNode->bSelected());
         }
      }
      else
      {
         if(subNode->getXmlId() == iXmlId)
         {
             LOG(Severity_Error)<<"2 ";
            subNode->setbSelected(!subNode->bSelected());
         }
         else
         {
             LOG(Severity_Error)<<"3 ";
            subNode->setbSelected(false);
         }
      }
   }
}

When i execute my code then compiler goes to else part and exceute both if and else statement inside the else part. why?

Body:
That seems ... (temporarily increasing my tactfulness attribute so as to avoid offending) ... rather unlikely :-)

It's probably because the code is being entered more than once and you're just assuming it's executing both parts because of the output.

My advice would be to change the code in the outer else to be:

LOG(Severity_Error)<<"Starting inner if ";
if(subNode->getXmlId() == iXmlId)
{
    LOG(Severity_Error)<<"2 ";
    subNode->setbSelected(!subNode->bSelected());
}
else
{
    LOG(Severity_Error)<<"3 ";
    subNode->setbSelected(false);
}
LOG(Severity_Error)<<"Ending inner if ";

You should not see both blocks executing without an intervening end/start message set.


问:
python google-cloud-storage library does not pick active user-account
I am using this tutorial to connect my GCS. I have multiple account with google and activated one with gcloud auth login and I double checked with gcloud auth list and it shows both accounts but one I need is marked with ACTIVE. But when I try to run the code mentioned in tutorial, getting following error

```<code>google.api_core.exceptions.Forbidden: 403 GET https://www.googleapis.com/storage/v1/b?project=<myproject>&projection=noAcl: <INACTIVE USER ACCOUNT> does not have storage.buckets.list access to project <PROJECT-ID>.
</code>```

I don't know why it is picking up inactive account instead of active account. am I missing something here? Please help

Even I revoked inactive account using command gcloud auth revoke --account, still python scripts referring that account only and throwing the same error.

PS - I am using Anaconda3.

答:
I too had the same issue, It got resolved by exporting env variable GOOGLE_APPLICATION_CREDENTIALS with a value pointing to the path of your bucket credentials JSON file eg.

export GOOGLE_APPLICATION_CREDENTIALS=/Users/myuser/Downloads/googleCredentials.json

This command basically sets default account credentials. This  Hope it helps you too.

Body:
I am using this tutorial to connect my GCS. I have multiple account with google and activated one with gcloud auth login and I double checked with gcloud auth list and it shows both accounts but one I need is marked with ACTIVE. But when I try to run the code mentioned in tutorial, getting following error

google.api_core.exceptions.Forbidden: 403 GET https://www.googleapis.com/storage/v1/b?project=<myproject>&projection=noAcl: <INACTIVE USER ACCOUNT> does not have storage.buckets.list access to project <PROJECT-ID>.

I don't know why it is picking up inactive account instead of active account. am I missing something here? Please help

Even I revoked inactive account using command gcloud auth revoke --account, still python scripts referring that account only and throwing the same error.

PS - I am using Anaconda3.


问:
commit() should be called before retrieving the values for out parameters?
While writing java JDBC code to call a stored procedure I am using con.setAutoCommit(false); My question is what is the difference in the below approaches:

Approach-1:

```<code>        con = DBConnection.getConnection();
        con.setAutoCommit(false);
        stmt= con.prepareCall("{call updateEmp(?,?,?,?,?,?)}");
        stmt.setInt(1, id);
        stmt.setString(2, name);
        stmt.setString(3, role);
        stmt.registerOutParameter(6, java.sql.Types.VARCHAR);

        stmt.executeUpdate();
        con.commit();
        //read the OUT parameter AFTER commit
        String result = stmt.getString(6);
</code>```

or Approach-2:

```<code>        // Read the OUT parameter BEFORE commit
        String result = stmt.getString(6);
        con.commit();
</code>```

答:
Just summing up the above answers in one answer for a quick summary:

1- If commiting, before all out parameters are read, data consistency is questionable. So here approach-2 is not advisable.

2- Suppose an exception occurs while reading the output parameters, then the transaction won't be committed. On the other hand, if we want the transaction to be committed without caring about the out parameters, we can commit before reading them.

3- In approach-2 we are blocking a transaction for longer time. In above sample code, its not a big deal but it may be a problem where we are doing lots of things before committing.

Body:
While writing java JDBC code to call a stored procedure I am using con.setAutoCommit(false); My question is what is the difference in the below approaches:

Approach-1:

        con = DBConnection.getConnection();
        con.setAutoCommit(false);
        stmt= con.prepareCall("{call updateEmp(?,?,?,?,?,?)}");
        stmt.setInt(1, id);
        stmt.setString(2, name);
        stmt.setString(3, role);
        stmt.registerOutParameter(6, java.sql.Types.VARCHAR);

        stmt.executeUpdate();
        con.commit();
        //read the OUT parameter AFTER commit
        String result = stmt.getString(6);

or Approach-2:

        // Read the OUT parameter BEFORE commit
        String result = stmt.getString(6);
        con.commit();


问:
What is the best way to log all user request operations: (inserts, updates, deletes in Sql Server 2008?
I have a database with 50 tables and I want to log users requests, such as inserts, updates or deletes on all the tables in the database.  I can also create a trigger for this for each request type.

What is the best way to do this from a  performance perspective or is there a better way to track this?

答: You can also create audit tables which are populated by triggers (and which allow much more flexibility than change data capture). The critical component is to capture sets of data not try to work row-by-row.  It does add some overhead yes, but if you write the triggers correctly, it isn't that much. Be sure to capture who (including which application if you have multiple applications hitting the database) and when as well as the old and new values. Set up one audit table per table you want audited (too much locking if you use only one audit table). And at the time you set up your system, write the code to get data back from a bad transaction or set of transactions. That makes it easier to recover when you do have something go wrong and you need to revert. We use two tables per table audited, one contains the info about the process that did the changes (name of the application, date, user, etc. and an auditid), the other contains the details about what was changed (old and new values, ID of the record being affected and column affected). Our structure enables us to use the same structure for each table being audited, and allows the tables to change without having to change the audit table and allows us to easily script the audit tables for a new tables. It is also easy for us to see what records were changed at the same time or in the same process or to find out which of the many applications which touch our database was responsible for the bad data as well as telling us who in particular was responsible for the bad data. This helps us track down application bugs and find out why the data was changed the way it was in some cases. It also makes it easier for us to track down all the data that was affected by a broken process rather than just the one we knew about. </p>


问:
How to sum two lists together?
I'm trying to do a sum of two list, for example:

1> example:sum([4,5], [6,7])
[10,12]
```

答:
I like the answer @doan-bui provided. It could also be solved using zip/2 and a list comprehension.

```<code>> [X+Y || {X,Y} <- lists:zip([4, 5], [6, 7]).
[10, 12]
</code>```

Title: How to sum two lists together?

Body:
I like the answer @doan-bui provided. It could also be solved using zip/2 and a list comprehension.

> [X+Y || {X,Y} <- lists:zip([4, 5], [6, 7]).
[10, 12]


问:
Shiny app gets disconnected from the server
Shiny app works fine locally but gets disconnected from the server with following error:

I have installed and loaded the library rgdal, but still keep on getting the error.

答:
Based on the error, it looks like you may not have uploaded your data files when you uploaded your app to shiny. Click File > Publish and make sure all of the files, including your app.R (and/or ui & server files) AND your data files are selected.

Or, do you setwd() at the beginning of your code? If so, delete that line and try again.


问:
Python module importing with sys.path and os.path issue
I spent some time researching this and I just cannot work this out in my head.

I run a program in its own directory home/program/core/main.py

In main.py I try and import a module called my_module.py thats located in a different directory, say home/program/modules/my_module.py

In main.py this is how I append to sys.path so the program can be run on anyone's machine (hopefully).

```<code>import os.path
import sys

# This should give the path to home/program
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__), '..'))
# Which it does when checking with
print os.path.join(os.path.abspath(os.path.dirname(__file__), '..')

# So now sys.path knows the location of where modules directory is, it should work right?

import modules.my_module # <----RAISES ImportError WHY?
</code>```

However if I simply do:

```<code>sys.path.append('home/program/modules')
import my_module
</code>```

It all works fine. But this is not ideal as it now depends on the fact that the program must exist under home/program.

答:
that's because modules isn't a valid python package, probably because it doesn't contain any __init__.py file (You cannot traverse directories with import without them being marked with __init__.py)

So either add an empty __init__.py file or just add the path up to modules so your first snippet is equivalent to the second one:

```<code>sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__), '..','modules'))
import my_module
</code>```

note that you can also import the module by giving the full path to it, using advanced import features: How to import a module given the full path?

Body:
I spent some time researching this and I just cannot work this out in my head.

I run a program in its own directory home/program/core/main.py

In main.py I try and import a module called my_module.py thats located in a different directory, say home/program/modules/my_module.py

In main.py this is how I append to sys.path so the program can be run on anyone's machine (hopefully).

import os.path
import sys

# This should give the path to home/program
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__), '..'))
# Which it does when checking with
print os.path.join(os.path.abspath(os.path.dirname(__file__), '..')

# So now sys.path knows the location of where modules directory is, it should work right?

import modules.my_module # <----RAISES ImportError WHY?

However if I simply do:

sys.path.append('home/program/modules')
import my_module

It all works fine. But this is not ideal as it now depends on the fact that the program must exist under home/program.

Body:
that's because modules isn't a valid python package, probably because it doesn't contain any __init__.py file (You cannot traverse directories with import without them being marked with __init__.py)

So either add an empty __init__.py file or just add the path up to modules so your first snippet is equivalent to the second one:

sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__), '..','modules'))
import my_module

note that you can also import the module by giving the full path to it, using advanced import features: How to import a module given the full path?


答:
Here's some code that does the trick (although it's not the most pythonic):

```<code>from pprint import pprint as pp

company_name_list = [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],
                     ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],
                     ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],
                     ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

id_page_list = [[144128, 1],
                [144138, 12],
                [144130, 6],
                [144131, 9],
                [40013, 153],
                [40074, 310],
                [40023, 210],
                [40050, 250]]

if __name__ == "__main__":
    id_str_page_list = [[str(item[0]), item[1]] for item in id_page_list]
    for employee in company_name_list:
        pages_list = list()
        for id_page in id_str_page_list:
            if id_page[0] == employee[0] or \
                    id_page[0] == employee[1]:
                pages_list.append(id_page[1])
        if pages_list:
            employee.append(pages_list)

    pp(company_name_list)
</code>```

Notes:

I converted the integer ids from id_str_page to strings and saved them into id_str_page_list using [Python]: List Comprehensions to do all the conversions at once

Then I iterate on each employee and if one of its ids is found on the 2nd list on the 1st position, I "save" page number in another list, which at the end (if not empty) I append it to the employee list

I renamed some of the variables to be [Python]: PEP 8 -- Style Guide for Python Code compliant

Output:

```<code>c:\Work\Dev\StackOverflow\q47257333>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py
[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]],
 ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]],
 ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]],
 ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]
</code>```

Title: iterate through multiple lists with python

Body:
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i

My source data is as follows:

CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

UserID and Page Number
eeIDlist:

[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]

Desired Output List:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]

Body:
Here's some code that does the trick (although it's not the most pythonic):

from pprint import pprint as pp

company_name_list = [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],
                     ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],
                     ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],
                     ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

id_page_list = [[144128, 1],
                [144138, 12],
                [144130, 6],
                [144131, 9],
                [40013, 153],
                [40074, 310],
                [40023, 210],
                [40050, 250]]

if __name__ == "__main__":
    id_str_page_list = [[str(item[0]), item[1]] for item in id_page_list]
    for employee in company_name_list:
        pages_list = list()
        for id_page in id_str_page_list:
            if id_page[0] == employee[0] or \
                    id_page[0] == employee[1]:
                pages_list.append(id_page[1])
        if pages_list:
            employee.append(pages_list)

    pp(company_name_list)

Notes:

I converted the integer ids from id_str_page to strings and saved them into id_str_page_list using [Python]: List Comprehensions to do all the conversions at once

Then I iterate on each employee and if one of its ids is found on the 2nd list on the 1st position, I "save" page number in another list, which at the end (if not empty) I append it to the employee list

I renamed some of the variables to be [Python]: PEP 8 -- Style Guide for Python Code compliant

Output:

c:\Work\Dev\StackOverflow\q47257333>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py
[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]],
 ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]],
 ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]],
 ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]


问:
TimeSpan to DateTime conversion
I want to convert a Timespan to Datetime. How can I do this?

I found one method on Google:

```<code>DateTime dt;
TimeSpan ts="XXX";

//We can covnert 'ts' to 'dt' like this:

dt= Convert.ToDateTime(ts.ToString());
</code>```

Is there any other way to do this?

答:
Worked for me.</p>
```<code>var StartTime = new DateTime(item.StartTime.Ticks);
</code>```

Title: TimeSpan to DateTime conversion

Body:
I want to convert a Timespan to Datetime. How can I do this?

I found one method on Google:

DateTime dt;
TimeSpan ts="XXX";

//We can covnert 'ts' to 'dt' like this:

dt= Convert.ToDateTime(ts.ToString());

Is there any other way to do this?

Body:
Worked for me.

var StartTime = new DateTime(item.StartTime.Ticks);


问:
Image Size Creating Timer Problems
The Swing.Timer for my game works depending on the size of the image that I am importing for my background. When I import the image as size 1920 x 1080 the timer is insanely slow and barely updates at all, but it is perfect quality. When the image size is set as 50 x 50 the timer works perfectly but the image itself is incredibly distorted. Is there a way to fix this in java? The code is shown below:

Load Image Class:

```<code>    public class BufferedImageLoader {
    Image image;
    public Image loadImage(String path) {
        try {
            image = ImageIO.read(this.getClass().getResource(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
}
</code>```

Get Loaded image

```<code>    public class ImageLoader {
    BufferedImageLoader bif = new BufferedImageLoader();
    public Image spaceship() {
        return bif.loadImage("/objects/spaceship.png");
    }

    public Image background() {
        return bif.loadImage("/objects/spaceBackground.png");
    }
    public Image asteroid1() {
        return bif.loadImage("/objects/v.png");
    }
    public Image background2() {
        return bif.loadImage("/Other/background.png");
    }
}
</code>```

Code where I am having the problem:

```<code>    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    if(menu)
        ms.render(g2);
    if(game) {
        g2.drawImage(il.background2(), 0, 0, 1000, 750, this);
        g2.drawImage(il.spaceship(), dx, 600, 100, 100, this);
    }
    if(settings)
        ss.render(g2);
    if(credits)
        cs.render(g2);

}
</code>```

il is the ImageLoader Object
I found out when the problem is happening, I just don't really understand why it is happening...

EDIT: For anyone wondering, when I made the background size 1000, 750 (this size that I am drawing it as) the timer is the same as the 1920 x 1080 image, incredibly slow and clunky.

答:
Loading images is time consuming.  You'd be better of pre-loading and caching your images and simply re-using them, for example.

```<code>public enum BufferedImageLoader {
    INSTANCE;
    private Map<String, BufferedImage> cache = new HashMap<>();
    public Image loadImage(String path) {
        BufferedImage image = cache.get(path);
        if (image == null) {
            try {
                image = ImageIO.read(this.getClass().getResource(path));
                cache.put(path, image);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return image;
    }
}
</code>```

Then you could just do...

```<code>public class ImageLoader {
    public Image spaceship() {
        return BufferedImageLoader.INSTANCE.loadImage("/objects/spaceship.png");
    }
</code>```

As a general rule of thumb, don't do anything in your paint methods which might take time to perform, paint should run as fast a possible

Title: Image Size Creating Timer Problems

Body:
The Swing.Timer for my game works depending on the size of the image that I am importing for my background. When I import the image as size 1920 x 1080 the timer is insanely slow and barely updates at all, but it is perfect quality. When the image size is set as 50 x 50 the timer works perfectly but the image itself is incredibly distorted. Is there a way to fix this in java? The code is shown below:

Load Image Class:

    public class BufferedImageLoader {
    Image image;
    public Image loadImage(String path) {
        try {
            image = ImageIO.read(this.getClass().getResource(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
}

Get Loaded image

    public class ImageLoader {
    BufferedImageLoader bif = new BufferedImageLoader();
    public Image spaceship() {
        return bif.loadImage("/objects/spaceship.png");
    }

    public Image background() {
        return bif.loadImage("/objects/spaceBackground.png");
    }
    public Image asteroid1() {
        return bif.loadImage("/objects/v.png");
    }
    public Image background2() {
        return bif.loadImage("/Other/background.png");
    }
}

Code where I am having the problem:

    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    if(menu)
        ms.render(g2);
    if(game) {
        g2.drawImage(il.background2(), 0, 0, 1000, 750, this);
        g2.drawImage(il.spaceship(), dx, 600, 100, 100, this);
    }
    if(settings)
        ss.render(g2);
    if(credits)
        cs.render(g2);

}

il is the ImageLoader Object
I found out when the problem is happening, I just don't really understand why it is happening...

EDIT: For anyone wondering, when I made the background size 1000, 750 (this size that I am drawing it as) the timer is the same as the 1920 x 1080 image, incredibly slow and clunky.

Body:
Loading images is time consuming.  You'd be better of pre-loading and caching your images and simply re-using them, for example.

public enum BufferedImageLoader {
    INSTANCE;
    private Map<String, BufferedImage> cache = new HashMap<>();
    public Image loadImage(String path) {
        BufferedImage image = cache.get(path);
        if (image == null) {
            try {
                image = ImageIO.read(this.getClass().getResource(path));
                cache.put(path, image);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return image;
    }
}

Then you could just do...

public class ImageLoader {
    public Image spaceship() {
        return BufferedImageLoader.INSTANCE.loadImage("/objects/spaceship.png");
    }

As a general rule of thumb, don't do anything in your paint methods which might take time to perform, paint should run as fast a possible


问:
How to fill the pixels of an image in android studio?
I would like to fill in the "pixels" of an example image: a 480x800 image I would like to match up to 800x800 but without changing the width or height, I would like to do so by adding more pixels but a black color without the image being distorted</p>

答:
I believe you are looking for some thing like 9 patch feature
This will give you the ability to specify how image will grow,so you can start from there.