问:
Why doesn't this variable get the correct value?
I'm trying to pass booleans between a controller and view, but in one particular case it's not working and I can't see what I'm doing wrong.

In the controller, I declare a variable, use an expression to give it a value,
and assign that value to a Session object. In the view, I retrieve the value from the session and store it in a new bool. I've also created some some other booleans in the way in the same controller and view. For some reason, while the other boolean variables work correctly, this one does not.

```<code>// In the controller:
bool isDatabaseRecipeRevisionSame = true;

// This evaluates to true:
isDatabaseRecipeRevisionSame = editedRecipe.Revision == savedRecipe.Revision;

Session["match"] = isDatabaseRecipeRevisionSame;

// In the view:
bool isRecipeRevisionSame = (bool)Session["match"];

// or:
bool isRecipeRevisionSame =Convert.ToBoolean(Session["match"]);
</code>```

Regardless of whether I cast or convert the session object into the boolean in the view, the result is false. If I cast the same session object into an integer I get a zero, and using ToString() I get "False". I don't understand how some of them work as expected and this one does not. Can someone please advise?

Thanks in advance.

Edit: responses to comments.

The Recipe.Revision variables are integers. The savedRecipe is retrieved from a database, edited and stored locally as editedRecipe. Before the edits are saved back to the database, savedRecipe.Revision is retrieved from the DB again to confirm that no-one else has changed the DB version since it was first retrieved. If the revisions match, then the edits are saved to the DB.

There are no other threads changing these values, nor are there currently any users other than myself using this database. I actually replicated the problem today within a single method, so I think DBro's probably right about it being a case-sensitivity problem. I've changed some of the code to use ViewBag since I posted this question, so I might not have to rework it any further.

Thanks for the advice.

答:
In your view please use this HttpContext.Current.Session instead of Session as bellow:

```<code>// In the view:
var session = HttpContext.Current.Session["match"];
bool isRecipeRevisionSame = (bool)session;
</code>```

Body:
I'm trying to pass booleans between a controller and view, but in one particular case it's not working and I can't see what I'm doing wrong.

In the controller, I declare a variable, use an expression to give it a value,
and assign that value to a Session object. In the view, I retrieve the value from the session and store it in a new bool. I've also created some some other booleans in the way in the same controller and view. For some reason, while the other boolean variables work correctly, this one does not.

// In the controller:
bool isDatabaseRecipeRevisionSame = true;

// This evaluates to true:
isDatabaseRecipeRevisionSame = editedRecipe.Revision == savedRecipe.Revision;

Session["match"] = isDatabaseRecipeRevisionSame;

// In the view:
bool isRecipeRevisionSame = (bool)Session["match"];

// or:
bool isRecipeRevisionSame =Convert.ToBoolean(Session["match"]);

Regardless of whether I cast or convert the session object into the boolean in the view, the result is false. If I cast the same session object into an integer I get a zero, and using ToString() I get "False". I don't understand how some of them work as expected and this one does not. Can someone please advise?

Thanks in advance.

Edit: responses to comments.

The Recipe.Revision variables are integers. The savedRecipe is retrieved from a database, edited and stored locally as editedRecipe. Before the edits are saved back to the database, savedRecipe.Revision is retrieved from the DB again to confirm that no-one else has changed the DB version since it was first retrieved. If the revisions match, then the edits are saved to the DB.

There are no other threads changing these values, nor are there currently any users other than myself using this database. I actually replicated the problem today within a single method, so I think DBro's probably right about it being a case-sensitivity problem. I've changed some of the code to use ViewBag since I posted this question, so I might not have to rework it any further.

Thanks for the advice.

Body:
In your view please use this HttpContext.Current.Session instead of Session as bellow:

// In the view:
var session = HttpContext.Current.Session["match"];
bool isRecipeRevisionSame = (bool)session;


来源: stackexchange

问:
Git bash help to pick changes and continue till end
I have branches A and B in git. Here I am cherry picking changes from branch A to branch B. For this I have created a tag in branch A and made 10 different commits on top of it. The first commit has been tagged in branch A.

Git cherry pick command takes commit hashes as input.

For this I have a list of commit hashes (SHA) starting from a tag (in  branch A) in a variable like this.

Checkout branch A

```<code>commithash="$(/usr/bin/git log --boundary --pretty=oneline ${tag_name}.. | sed -e 's/- //'| cut -d ' ' -f 1)"

echo $commithash  ---gives spaces delimited commit hashes below.

3f899d3eebce23ce6a1efd3b73ea0b328c8cf3e1 2180e9e8a0a73a5313e70317a20360e3314b2568 f001ad3d03b6a4231d370a3b389d6edbd14db73b 66049c094a0780df7a518ba75d677213168e5211 3a6e53426e85f36b8fc3e19586c18d1ee0abf31b 0b2698bf67ea0c29f0e76fe110a0b89ccbfdecd2 8aed2c998dcd38ac5e01be5d1004d7130b1b2458 07a65386ad8883bf5f774541461cce0779d8b0d2 b57d0d1cea1cf8a151f1244c30b8f08eb7583926
</code>```

I now switch to branch B

For each commit hash in that variable I want to run the command.

```<code>git cherry-pick --strategy-option theirs $(for-each-commit-sha)
</code>```

When running the command it is successful except for a below scenario where it fails.

A. if the output for cherry pick command has the below output the script fails and none of the file are cherry picked.

```<code>error: could not apply 34h5432.. adding dev text for cc in file
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'
</code>```

Below is the output of:

```<code>git status

On branch B
You are currently cherry-picking commit 34h5432...
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Unmerged paths:
  (use "git add/rm <file>..." as appropriate to mark resolution)

    deleted by us:   cc.txt
</code>```

In this scenario I want to run git add cc.txt or issue a git add for whatever is mentioned after "deleted by us: "

```<code>git add cc.txt

git commit -m "adding file"
</code>```

Then continue cherry pick for rest of the commit hashes in the list until the last.

The cherry pick needs to be done from last commit sha to first. In this case start with b57d0d1cea1cf8a151f1244c30b8f08eb7583926 and ends with
3f899d3eebce23ce6a1efd3b73ea0b328c8cf3e1

How can I do that ?

```<code>commithash="$(/usr/bin/git log --boundary --pretty=oneline ${tag_name}.. | sed -e 's/- //'| cut -d ' ' -f 1)"
</code>```

答:
First, git cherry-pick can take a range of commits: you shouldn't have to list those commits manually.

Second, see if git checkout --theirs -- cc.txt would restore your file, before doing an add and git cherry-pick --continue.

ContentLicense: CC BY-SA 4.0

Body:
I have branches A and B in git. Here I am cherry picking changes from branch A to branch B. For this I have created a tag in branch A and made 10 different commits on top of it. The first commit has been tagged in branch A.

Git cherry pick command takes commit hashes as input.

For this I have a list of commit hashes (SHA) starting from a tag (in  branch A) in a variable like this.

Checkout branch A

commithash="$(/usr/bin/git log --boundary --pretty=oneline ${tag_name}.. | sed -e 's/- //'| cut -d ' ' -f 1)"

echo $commithash  ---gives spaces delimited commit hashes below.

3f899d3eebce23ce6a1efd3b73ea0b328c8cf3e1 2180e9e8a0a73a5313e70317a20360e3314b2568 f001ad3d03b6a4231d370a3b389d6edbd14db73b 66049c094a0780df7a518ba75d677213168e5211 3a6e53426e85f36b8fc3e19586c18d1ee0abf31b 0b2698bf67ea0c29f0e76fe110a0b89ccbfdecd2 8aed2c998dcd38ac5e01be5d1004d7130b1b2458 07a65386ad8883bf5f774541461cce0779d8b0d2 b57d0d1cea1cf8a151f1244c30b8f08eb7583926

I now switch to branch B

For each commit hash in that variable I want to run the command.

git cherry-pick --strategy-option theirs $(for-each-commit-sha)

When running the command it is successful except for a below scenario where it fails.

A. if the output for cherry pick command has the below output the script fails and none of the file are cherry picked.

error: could not apply 34h5432.. adding dev text for cc in file
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

Below is the output of:

git status

On branch B
You are currently cherry-picking commit 34h5432...
  (fix conflicts and run "git cherry-pick --continue")
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

Unmerged paths:
  (use "git add/rm <file>..." as appropriate to mark resolution)

    deleted by us:   cc.txt

In this scenario I want to run git add cc.txt or issue a git add for whatever is mentioned after "deleted by us: "

git add cc.txt

git commit -m "adding file"

Then continue cherry pick for rest of the commit hashes in the list until the last.

The cherry pick needs to be done from last commit sha to first. In this case start with b57d0d1cea1cf8a151f1244c30b8f08eb7583926 and ends with
3f899d3eebce23ce6a1efd3b73ea0b328c8cf3e1

How can I do that ?

commithash="$(/usr/bin/git log --boundary --pretty=oneline ${tag_name}.. | sed -e 's/- //'| cut -d ' ' -f 1)"


问:
csv to json parse returns invalid json
I have a csv file which I'm trying to convert to JSON. Even though it does convert it's not valid json.

Here is my csv:

```<code>"timestamp","firstName","lastName","range","sName","location"
"2019/03/08 12:53:47 pm GMT-4","Hi","Y'A","25-34","Parlour",""
</code>```

Here is my code:

```<code>const csv=require('csvtojson');
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj)
});
</code>```

I run it by node foo.js >> foo.json

Error is:

```<code>undefined:1
[ { timestamp: '2019/03/08 12:53:47 pm GMT-4',
</code>```

Expected output:

```<code>[
 {
   "timestamp": "2019/03/08 12:53:47 pm GMT-4",
   "firstName": "Hi",
   "lastName": "Y'A",
   "range": "25-34",
   "sName": "Parlour",
   "location": ""
 }
]
</code>```

答:
Work for me

```<code>let log = (s) => console.log(s);

const csv = require('csvtojson');
let str =
`"timestamp","firstName","lastName","range","sName","location"
"2019/03/08 12:53:47 pm GMT-4","Hi","Y'A","25-34","Parlour",""`
csv().fromString(str).then(log);

/*
[ { timestamp: '2019/03/08 12:53:47 pm GMT-4',
    firstName: 'Hi',
    lastName: 'Y\'A',
    range: '25-34',
    sName: 'Parlour',
    location: '' } ]
*/
</code>```

Works with file also. Check file content: commas, tabs, endlines.

Title: csv to json parse returns invalid json

Body:
I have a csv file which I'm trying to convert to JSON. Even though it does convert it's not valid json.

Here is my csv:

"timestamp","firstName","lastName","range","sName","location"
"2019/03/08 12:53:47 pm GMT-4","Hi","Y'A","25-34","Parlour",""

Here is my code:

const csv=require('csvtojson');
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj)
});

I run it by node foo.js >> foo.json

Error is:

undefined:1
[ { timestamp: '2019/03/08 12:53:47 pm GMT-4',

Expected output:

[
 {
   "timestamp": "2019/03/08 12:53:47 pm GMT-4",
   "firstName": "Hi",
   "lastName": "Y'A",
   "range": "25-34",
   "sName": "Parlour",
   "location": ""
 }
]

Body:
Work for me

let log = (s) => console.log(s);

const csv = require('csvtojson');
let str =
`"timestamp","firstName","lastName","range","sName","location"
"2019/03/08 12:53:47 pm GMT-4","Hi","Y'A","25-34","Parlour",""`
csv().fromString(str).then(log);

/*
[ { timestamp: '2019/03/08 12:53:47 pm GMT-4',
    firstName: 'Hi',
    lastName: 'Y\'A',
    range: '25-34',
    sName: 'Parlour',
    location: '' } ]
*/

Works with file also. Check file content: commas, tabs, endlines.


问:
Add class to div that contain Dog 1 and rows in between
The code is automatically generated so I cannot add classes/id's etc by adding HTML so I am trying to do this using js. I truncated the content, but basically I want to add class "dog1" to the rows that pertain to Dog 1 and class "dog2" to the rows that pertain to Dog 2.

I tried using the script in the attached snippet:

let dogCounter = 1;
let classAttribute = '';
const $trs = $('span:contains("Dog 1")').first().closest('div');

$trs.each((i, div) => {
  const selector = 'span:contains("Dog '+dogCounter+'")';
  if ($(div).find(selector).length) {
   classAttribute = 'dog'+dogCounter;
    dogCounter++;
  }
  $(div).addClass(classAttribute);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dog1 {
  color: red;
}
.dog2 {
  color: blue;
}</code>```

Dog 1 Name

Dog 1 Age

Dog 1 Weight

Date of last appointment

Dog 1 Number

Acceptance

Dog 1 Allergies

Dog 2 Details

Dog 2 Name

Dog 2 Name

Dog 2 Age

Dog 2 Weight

Date of last appointment

Dog 2 Number

Acceptance

Dog 2 Allergies
```

答:
Hope this helps :)
I only added the class to the span, so you may consider adding it to the parent div;
Also, there are divs that don't contain a "Dog *" pattern, so you may have to consider another approach;

Later edit: The rows in between can't be matched by a regex, so you may have to consider splitting your data by starting and ending columns ("Name" column may be the starting column, "Allergies" may be the ending column)

const $dogSpans = $('span:contains("Dog")');

$dogSpans.each((i, span) => {
   matches = $(span).html().toString().match( /Dog [0-9]*/); //may find more than one match
   match = matches[0].toLowerCase(); //we only consider the first match (and we lowercase it)
   matchedClass = match.replace(/\s/g, ''); //we remove spaces to obtain a class name
   $(span).addClass(matchedClass);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dog1 {
  color: red;
}
.dog2 {
  color: blue;
}

.dog15 {
  color: green;
}</code>```

Dog 1 Name

Dog 1 Age

Dog 1 Weight

Date of last appointment

Dog 1 Number

Acceptance

Dog 1 Allergies

Dog 2 Details

Dog 2 Name

Dog 2 Name

Dog 2 Age

Dog 2 Weight

Date of last appointment

Dog 2 Number

Acceptance

Dog 2 Allergies

Dog 15 Name
```

Body:
The code is automatically generated so I cannot add classes/id's etc by adding HTML so I am trying to do this using js. I truncated the content, but basically I want to add class "dog1" to the rows that pertain to Dog 1 and class "dog2" to the rows that pertain to Dog 2.

I tried using the script in the attached snippet:

let dogCounter = 1;
let classAttribute = '';
const $trs = $('span:contains("Dog 1")').first().closest('div');

$trs.each((i, div) => {
  const selector = 'span:contains("Dog '+dogCounter+'")';
  if ($(div).find(selector).length) {
   classAttribute = 'dog'+dogCounter;
    dogCounter++;
  }
  $(div).addClass(classAttribute);
})

.dog1 {
  color: red;
}
.dog2 {
  color: blue;
}

Dog 1 Name

Dog 1 Age

Dog 1 Weight

Date of last appointment

Dog 1 Number

Acceptance

Dog 1 Allergies

Dog 2 Details

Dog 2 Name

Dog 2 Name

Dog 2 Age

Dog 2 Weight

Date of last appointment

Dog 2 Number

Acceptance

Dog 2 Allergies

Body:
Hope this helps :)
I only added the class to the span, so you may consider adding it to the parent div;
Also, there are divs that don't contain a "Dog *" pattern, so you may have to consider another approach;

Later edit: The rows in between can't be matched by a regex, so you may have to consider splitting your data by starting and ending columns ("Name" column may be the starting column, "Allergies" may be the ending column)

const $dogSpans = $('span:contains("Dog")');

$dogSpans.each((i, span) => {
   matches = $(span).html().toString().match( /Dog [0-9]*/); //may find more than one match
   match = matches[0].toLowerCase(); //we only consider the first match (and we lowercase it)
   matchedClass = match.replace(/\s/g, ''); //we remove spaces to obtain a class name
   $(span).addClass(matchedClass);
})

.dog1 {
  color: red;
}
.dog2 {
  color: blue;
}

.dog15 {
  color: green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div><span>Dog 1 Name</span></div>
<div><span>Dog 1 Age</span></div>
<div><span>Dog 1 Weight</span></div>
<div>
<span>Date of last appointment</span></div>
<div><span>Dog 1 Number</span></div>
<div><span>Acceptance</span></div>
<div><div><span>Dog 1 Allergies</span></div></div>
<div><span>Dog 2 Details</span></div>
<div><span>Dog 2 Name</span></div>
<div><span>Dog 2 Name</span></div>
<div><span>Dog 2 Age</span></div>
<div><span>Dog 2 Weight</span></div>
<div><span>Date of last appointment</span></div>
<div><span>Dog 2 Number</span></div>
<div><span>Acceptance</span></div>
<div><span>Dog 2 Allergies</span></div>
<div><span>Dog 15 Name</span></div>


问:
material UI - How can I change the font size of the label in FormControlLabel
How can I change the font size of the label inside the FormControlLabel?
I am using it with React for Front End JS</p>

```<code><FormGroup row>
     <FormControlLabel
     control={
       <Checkbox onClick={() => onClick('rdOption4')} />
    　　　　　 }
     label="All Date"
/>
 </FormGroup>
</code>```

答:
Do it using themes:

```<code>import { createMuiTheme } from '@material-ui/core';
export const theme = createMuiTheme({
    overrides: {
        MuiFormControlLabel: {
            label: {
                fontSize: '0.875rem',
            }
        }
    }
});
</code>```

Themes Documentation

Body:
How can I change the font size of the label inside the FormControlLabel?
I am using it with React for Front End JS

<FormGroup row>
     <FormControlLabel
     control={
       <Checkbox onClick={() => onClick('rdOption4')} />
    　　　　　 }
     label="All Date"
/>
 </FormGroup>

Body:
Do it using themes:

import { createMuiTheme } from '@material-ui/core';
export const theme = createMuiTheme({
    overrides: {
        MuiFormControlLabel: {
            label: {
                fontSize: '0.875rem',
            }
        }
    }
});

Themes Documentation


问:
.net library does not pick keys from app.config
I am working on a error reporting library in c#, and its a static class.
When I am running this library from other applications by adding a reference. It does not pick the AppSetting Keys from app.config.

In that case I need to add the keys to all main applications to make it working.

Are their any other solution to sortout this problem?

Thanks and Regards

答:
If you mean in your library you have an app.config file with values and when you use your library in other applications, the value is not loaded then it is by design.

Only the config file is loaded whose name is "exe name" + ".exe" or web.config in web applications.

You need to copy the appSettings to the EXE application's app.config. Or use alternate configuration for your application.

It is also by design since libraries must take their configuration from their clients.

ContentLicense: CC BY-SA 3.0


问:
Indexing freeze with message: Indexing paused due to batch updated
I've updated Android Studio to version 3.2.

After that update one of my projects don't want to index.

It freezes with the message

"Indexing paused due to batch update".

How can I fix this?

File gradle-wrapper.properties:

```<code>distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
</code>```

File gradle-properties:

```<code>org.gradle.jvmargs=-Xmx1536m
org.gradle.parallel=true
org.gradle.daemon=true
org.gradle.configureondemand=true
</code>```

答: I faced the same issue, because my AS version is not the same with gradle plugin's version.</p>

Body:
I've updated Android Studio to version 3.2.

After that update one of my projects don't want to index.

It freezes with the message

"Indexing paused due to batch update".

How can I fix this?

File gradle-wrapper.properties:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

File gradle-properties:

org.gradle.jvmargs=-Xmx1536m
org.gradle.parallel=true
org.gradle.daemon=true
org.gradle.configureondemand=true


问:
How to call methods from class located in one python file from another python file
I am creating framework using Selenium and Python.
    My data driven Framework should consist of (so far) 3 files:

```<code>1) Config.py have class Config() that have all the nessesary methods such as:
   def setUp() -
   def tearDown()
   def click()
   def send_keys()

2) data.py - with all data

3) test.py - with all of the steps
</code>```

I am currently working on click() method.

I want to pass 2 parameters to this method, it will use slice()
    to identify what kind of locators i am using and click
    accordingly. Unfortunatly no matter what i do - it keeps
    throwing me some errors.

config.py:

```<code>from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException

class Actions(object):

    def __init__(self, driver):
        self.driver = driver

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)

    def tearDown(self):
        self.driver.quit()

    def click(self, elemLocator, elemValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':
            try:
                self.driver.find_element_by_id(elemValue).click()
            except:
                pass
        elif elp[flp] == 'xp':
            try:
                self.driver.find_element_by_xpath(elemValue).click()
            except:
                pass
        elif elp[flp] == 'li':
            try:
                self.driver.find_element_by_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'na':
            try:
                self.driver.find_element_by_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cs':
            try:
                self.driver.find_element_by_css_selector(elemValue).click()
            except:
                pass
        elif elp[flp] == 'pa':
            try:
                self.driver.find_element_by_partial_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'ta':
            try:
                self.driver.find_element_by_tag_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cl':
            try:
                self.driver.find_element_by_class_name(elemValue).click()
            except:
                pass

    def send_keys(self):
        pass
</code>```

test.py:

```<code>from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
from Setup import Actions

action = Actions()
action.setUp()
</code>```

Error Message:

```<code>Traceback (most recent call last):
  File "/Users/a./Desktop/Automation_Work/correct_PPLS/oop/Test.py", line 9, in <module>
    action = Actions()
TypeError: __init__() takes exactly 2 arguments (1 given)
[Finished in 0.153s]
</code>```

答:
Just change the __init__ as below.

```<code>def __init__(self,driver=None):
    if driver != None:
        self.driver = driver
</code>```

Now you can call the __init__ with or without passing driver. However, I suggest declaring the driver out side the class and make it as global so that you can access it anywhere.

Something like this:

```<code>from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
driver = None
class Actions(object):

    def __init__(self, driver):
        self.driver = driver

    def setUp(self,browserName):
        global driver
        if browserName == 'chrome' #<==== creating the driver based on browser (you can pass this as argument while calling this method)
            self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)
        # return driver #<==== return driver so that you can store with other name if you are planning to launch 2nd instance of driver.

action = Actions()
action.setUp("chrome")
</code>```

Body:
I am creating framework using Selenium and Python.
    My data driven Framework should consist of (so far) 3 files:

1) Config.py have class Config() that have all the nessesary methods such as:
   def setUp() -
   def tearDown()
   def click()
   def send_keys()

2) data.py - with all data

3) test.py - with all of the steps

I am currently working on click() method.

I want to pass 2 parameters to this method, it will use slice()
    to identify what kind of locators i am using and click
    accordingly. Unfortunatly no matter what i do - it keeps
    throwing me some errors.

config.py:

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException

class Actions(object):

    def __init__(self, driver):
        self.driver = driver

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)

    def tearDown(self):
        self.driver.quit()

    def click(self, elemLocator, elemValue):
        elp = elemLocator
        flp = slice(0,2)
        if elp[flp] == 'id':
            try:
                self.driver.find_element_by_id(elemValue).click()
            except:
                pass
        elif elp[flp] == 'xp':
            try:
                self.driver.find_element_by_xpath(elemValue).click()
            except:
                pass
        elif elp[flp] == 'li':
            try:
                self.driver.find_element_by_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'na':
            try:
                self.driver.find_element_by_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cs':
            try:
                self.driver.find_element_by_css_selector(elemValue).click()
            except:
                pass
        elif elp[flp] == 'pa':
            try:
                self.driver.find_element_by_partial_link_text(elemValue).click()
            except:
                pass
        elif elp[flp] == 'ta':
            try:
                self.driver.find_element_by_tag_name(elemValue).click()
            except:
                pass
        elif elp[flp] == 'cl':
            try:
                self.driver.find_element_by_class_name(elemValue).click()
            except:
                pass

    def send_keys(self):
        pass

test.py:

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
from Setup import Actions

action = Actions()
action.setUp()

Error Message:

Traceback (most recent call last):
  File "/Users/a./Desktop/Automation_Work/correct_PPLS/oop/Test.py", line 9, in <module>
    action = Actions()
TypeError: __init__() takes exactly 2 arguments (1 given)
[Finished in 0.153s]

Body:
Just change the __init__ as below.

def __init__(self,driver=None):
    if driver != None:
        self.driver = driver

Now you can call the __init__ with or without passing driver. However, I suggest declaring the driver out side the class and make it as global so that you can access it anywhere.

Something like this:

from   selenium import webdriver
from   selenium.webdriver.common.by import By
from   selenium.webdriver.common.keys import Keys
from   selenium.webdriver.support.ui import Select
from   selenium.common.exceptions import NoSuchElementException
from   selenium.common.exceptions import NoAlertPresentException
driver = None
class Actions(object):

    def __init__(self, driver):
        self.driver = driver

    def setUp(self,browserName):
        global driver
        if browserName == 'chrome' #<==== creating the driver based on browser (you can pass this as argument while calling this method)
            self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)
        # return driver #<==== return driver so that you can store with other name if you are planning to launch 2nd instance of driver.

action = Actions()
action.setUp("chrome")


问:
How to use jQuery Template to select option?
I'm working with form that contain select element. I need to fill select with the data coming via json format. How to use jquery template to fill the select element?

I read about jquery template, it's documentation. But still can't get right result.

2 question: Is it good way to use jQuery Template for big data, for example: 4000 columns?

    <select id="sel"></select>

```

```    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');
```

答:
You may have a little change in the code as follows,

    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- These are added to execute the code -->
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>

<div class="col-lg-5">
    <select id="sel"></select>
</div>

<!--
These was your code,

<script id="optionTmpl" type="text/x-jquery-tmpl">
  {{each $options}}
    <option value="${$code}">${$title}</option>
  {{/each}}
</script>

which is changed to =>
-->

<script id="optionTmpl" type="text/x-jquery-tmpl">
    <option value="${code}">${title}</option>
</script></code>```

Body:
I'm working with form that contain select element. I need to fill select with the data coming via json format. How to use jquery template to fill the select element?

I read about jquery template, it's documentation. But still can't get right result.

2 question: Is it good way to use jQuery Template for big data, for example: 4000 columns?

    <select id="sel"></select>

    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');

Body:
You may have a little change in the code as follows,

    var options = [
    { code: "1", title: "A" },
    { code: "2", title: "B" },
    { code: "3", title: "C" },
    { code: "4", title: "D" },
    { code: "5", title: "E" },
    ];
    $('#optionTmpl').tmpl(options).appendTo('#sel');

<!-- These are added to execute the code -->
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>

<div class="col-lg-5">
    <select id="sel"></select>
</div>

<!--
These was your code,

<script id="optionTmpl" type="text/x-jquery-tmpl">
  {{each $options}}
    <option value="${$code}">${$title}</option>
  {{/each}}
</script>

which is changed to =>
-->

<script id="optionTmpl" type="text/x-jquery-tmpl">
    <option value="${code}">${title}</option>
</script>


问:
What is the meaning of "UPDATE table SET column1 = value AND column2 value WHERE condition" in SQL?
If the "," in an UPDATE statement is replaced with AND, what the meaning in SQL?

Normal Update Statement :

```<code>UPDATE table
SET column1 = value ,
    column2 = value
WHERE condition
</code>```

My question statement :

```<code>UPDATE table
SET column1 = value AND column2 = value
WHERE condition
</code>```

The affected rows seem to be different, so I want to know what my question statement mean in SQL?

Original test Data

After inserting query(from original)  : Update testing set column1 = 2 , column2 =5

Normal Update

After inserting query(from original) : Update testing set column1 = 2 AND column2 =5

My Question Statement

if I insert the query(from original) :Update testing set column1 = 2 AND  =4

the output

答:
It's probably wrong to write 2 AND b = 1 though some databases evaluate it and others don't

If your intention is to set multiple columns in one go, you MUST use a comma

If you use this construct, perhaps some databases will process it according to bitwise-logical operation or they will treat any non zero value as true/false and any zero as false/true, and others will process it according to Boolean-logical operation

In the example strawberry kindly posted: https://www.db-fiddle.com/f/3KawkrD8QfjJu6YyfuzB7U/0

Set the db to MySQL and run it; it works out - MySQL is probably treating 2 as true, so the operation becomes:

```<code>SET c = true and true --when b = 1
SET c = true and false --when b=0
</code>```

You can see your c column is set to 1 or 0 depending on the truth

```<code>SET c = (2 AND (b = 1))
        ^^^^^^^^^^^^^^^
        This whole thing is turned into a value.
        for C, it does NOT set column B at all
</code>```

Now change the DB to Postgres and run it again

This time you get an error that AND expects Boolean operands, and the integer 2 is not acceptable

Hence in Postgres while this might be acceptable:

```<code>SET d = (c=1 AND b=2) --sets a true or false value for d
</code>```

Your other form is not acceptable

--

Long story short, you probably intended to set multiple columns: use a comma.

Body:
If the "," in an UPDATE statement is replaced with AND, what the meaning in SQL?

Normal Update Statement :

UPDATE table
SET column1 = value ,
    column2 = value
WHERE condition

My question statement :

UPDATE table
SET column1 = value AND column2 = value
WHERE condition

The affected rows seem to be different, so I want to know what my question statement mean in SQL?

Original test Data

After inserting query(from original)  : Update testing set column1 = 2 , column2 =5

Normal Update

After inserting query(from original) : Update testing set column1 = 2 AND column2 =5

My Question Statement

if I insert the query(from original) :Update testing set column1 = 2 AND  =4

the output

Body:
It's probably wrong to write 2 AND b = 1 though some databases evaluate it and others don't

If your intention is to set multiple columns in one go, you MUST use a comma

If you use this construct, perhaps some databases will process it according to bitwise-logical operation or they will treat any non zero value as true/false and any zero as false/true, and others will process it according to Boolean-logical operation

In the example strawberry kindly posted: https://www.db-fiddle.com/f/3KawkrD8QfjJu6YyfuzB7U/0

Set the db to MySQL and run it; it works out - MySQL is probably treating 2 as true, so the operation becomes:

SET c = true and true --when b = 1
SET c = true and false --when b=0

You can see your c column is set to 1 or 0 depending on the truth

SET c = (2 AND (b = 1))
        ^^^^^^^^^^^^^^^
        This whole thing is turned into a value.
        for C, it does NOT set column B at all

Now change the DB to Postgres and run it again

This time you get an error that AND expects Boolean operands, and the integer 2 is not acceptable

Hence in Postgres while this might be acceptable:

SET d = (c=1 AND b=2) --sets a true or false value for d

Your other form is not acceptable

--

Long story short, you probably intended to set multiple columns: use a comma.


问:
to replace using find word in array from text file
I have problem that str_replace can't replace the second to last word... first word is working then second up to last is not work in array.. I tried enter the message "ducker apple banana chicken" in "chat.php?message=" then become like this:

output:

"***er apple banana chicken"

badwords.txt:

```<code>duck;
apple;
banana;
chicken;
water;
</code>```

chat.php

```<code>$censoredfilter = file("badwords.txt");
$censoredfilter = implode("\n", $censoredfilter);
$censoredfilter = explode(";", $censoredfilter);

$message = $_GET['message'];

for($i = 0; $i<sizeof($censoredfilter);$i++)
{
    $message = str_replace($censoredfilter[$i], "***", $message);
}
</code>```

答:
If you remove the ;'s an alternative solution is:

```<code>$censoredfilter = file("badwords.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$message = str_replace($censoredfilter, '***', $_GET['message']);
</code>```

This works because file() actually returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Adding the FILE_IGNORE_NEW_LINES flag removes the newlines from the end of each element. See the php manual on file for more info.

It also has the added benefit of handling any of the usual line-endings.

Body:
I have problem that str_replace can't replace the second to last word... first word is working then second up to last is not work in array.. I tried enter the message "ducker apple banana chicken" in "chat.php?message=" then become like this:

output:

"***er apple banana chicken"

badwords.txt:

duck;
apple;
banana;
chicken;
water;

chat.php

$censoredfilter = file("badwords.txt");
$censoredfilter = implode("\n", $censoredfilter);
$censoredfilter = explode(";", $censoredfilter);

$message = $_GET['message'];

for($i = 0; $i<sizeof($censoredfilter);$i++)
{
    $message = str_replace($censoredfilter[$i], "***", $message);
}

Body:
If you remove the ;'s an alternative solution is:

$censoredfilter = file("badwords.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$message = str_replace($censoredfilter, '***', $_GET['message']);

This works because file() actually returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Adding the FILE_IGNORE_NEW_LINES flag removes the newlines from the end of each element. See the php manual on file for more info.

It also has the added benefit of handling any of the usual line-endings.


问:
Brackets won't install Emmet plugin
I have just installed the text editor Adobe Brackets to try it out and my first action was to install my favourite plugin, Emmet. I was frustrated to find that the installation failed. I have tried downloading the emmet zip file and dragging into the Extension Manager but the result is the same. I have tried uninstalling and reinstalling Brackets and restarting Windows. I am not prepared to use Brackets without Emmet so how can I fix this?

I am using Windows 10 and I note that Brackets will only install a 32-bit version. Brackets version is Release 1.12 build 1.12.0-17621 (release d3b783b99)

答: for me it was a matter of having no other extension installed. Pretty lightweight, the brackets AND with the necessary plugs (swatch, SCSS, classhint, lint), I'll keep using it. Just saying..</p>

Title: Brackets won't install Emmet plugin


问:
How to create virtual scrolling for images using React js
Whats my requirement: i have some images in my external folder and i need to import to component and display it and also have to use Virtual Scroll here i have to display 1 row in div and in that 1 row have to show 5-6 images

What i did : i consumed images using context from external folder and showed images in 1 rows in div and 5-6 images but i am facing issue unable to set it to Virtual scrolling

as i checked react-virtualized & react-window plugin but i am not sure how my data is used in that format

After using the react-tiny-virtual-list images are getting stacked

below is my code

```<code>class App extends React.Component{

  state={
    Response:[],

  }
  importAll(r) {
    return r.keys().map(r);
  }
  componentWillMount() {
    let data = this.importAll(require.context('./imageFolder/', false, /\.(png|jpe?g|svg)$/));
    this.setState({ Response:data})
  }

  render(){
    return(
      <div className="container" id="imagecontainer">
        <div className="viewport">
              {this.state.Response.map((image, index) =>    <img key={index} src={image} alt="info"></img>      )} }
           </div>

      </div>
    )
  }

 .container {
      padding: 0% 6%;
      height: 400px;
    }
    .viewport {
      height: -webkit-fill-available;
      width: 100%;
      border: 1px solid black;
      overflow: scroll;
    }

img {
  height: 250px;
  width: 150px;
  padding: 35px;
}

After implementing React-tiny-list
 <div id="container">
      <div id="viewport">
      <VirtualList
    height='400px'
    width='100%'
    itemCount={this.state.items.length}
    itemSize={20} // Also supports variable heights (array or function getter)
    style={{padding:'20px'}}
    renderItem={({index, style}) =>
      <div key={index} style={style}>

        <img key={index} src={this.state.items[index]} alt="info"></img>
      </div>
    }
  />
      </div>

    </div>
</code>```

答:
you can also use the https://github.com/bvaughn/react-virtualized plugin in this if you want to display this as table you can choose list or you can choose grid also .For you requirement i recommend using  Masonry from 'react-virtualized';

below is the sample for displaying

```<code>import React from 'react';
import {
  CellMeasurer,
  CellMeasurerCache,
  createMasonryCellPositioner,
  Masonry
} from 'react-virtualized';

import 'react-virtualized/styles.css';

var images = [];
const columnWidth = 250;
const defaultHeight = 260;
const defaultWidth = columnWidth;

const cache = new CellMeasurerCache({
  defaultHeight,
  defaultWidth,
  fixedWidth: true
})

// Our masonry layout will use 3 columns with a 10px gutter between
const cellPositioner = createMasonryCellPositioner({
  cellMeasurerCache: cache,
  columnCount: 4,
  columnWidth,
  spacer: 27
})

function cellRenderer ({ index, key, parent, style }) {
  const datum = images[index]

  const height = columnWidth  ||  defaultHeight ;

  return (
    <CellMeasurer
      cache={cache}
      index={index}
      key={key}
      parent={parent}
    >
      <div style={style}>
        <img
          src={datum}
          style={{
            height: height,
            width: columnWidth,
            display: "block"
          }}
          alt="info"
        />

      </div>
    </CellMeasurer>
  )
}

class Grid extends React.Component{

  importAll(r) {
    return r.keys().map(r);
  }
  componentWillMount() {
    images = this.importAll(require.context('../imageFolder/', false, /\.(png|jpe?g|svg)$/));
  }
  render(){
    return(
      <div  id="container">
          <div id="viewport">

             <Masonry
            cellCount={images.length}
            cellMeasurerCache={cache}
            cellPositioner={cellPositioner}
            cellRenderer={cellRenderer}
            height={400}
            width={1320}

        />
          </div>

      </div>
    )
  }
}

export default Grid;
</code>```

I hope this will resolve your issue

Body:
Whats my requirement: i have some images in my external folder and i need to import to component and display it and also have to use Virtual Scroll here i have to display 1 row in div and in that 1 row have to show 5-6 images

What i did : i consumed images using context from external folder and showed images in 1 rows in div and 5-6 images but i am facing issue unable to set it to Virtual scrolling

as i checked react-virtualized & react-window plugin but i am not sure how my data is used in that format

After using the react-tiny-virtual-list images are getting stacked

below is my code

class App extends React.Component{

  state={
    Response:[],

  }
  importAll(r) {
    return r.keys().map(r);
  }
  componentWillMount() {
    let data = this.importAll(require.context('./imageFolder/', false, /\.(png|jpe?g|svg)$/));
    this.setState({ Response:data})
  }

  render(){
    return(

              {this.state.Response.map((image, index) =>          )} }

    )
  }

 .container {
      padding: 0% 6%;
      height: 400px;
    }
    .viewport {
      height: -webkit-fill-available;
      width: 100%;
      border: 1px solid black;
      overflow: scroll;
    }

img {
  height: 250px;
  width: 150px;
  padding: 35px;
}

After implementing React-tiny-list

      <VirtualList
    height='400px'
    width='100%'
    itemCount={this.state.items.length}
    itemSize={20} // Also supports variable heights (array or function getter)
    style={{padding:'20px'}}
    renderItem={({index, style}) =>

    }
  />

Body:
you can also use the https://github.com/bvaughn/react-virtualized plugin in this if you want to display this as table you can choose list or you can choose grid also .For you requirement i recommend using  Masonry from 'react-virtualized';

below is the sample for displaying

import React from 'react';
import {
  CellMeasurer,
  CellMeasurerCache,
  createMasonryCellPositioner,
  Masonry
} from 'react-virtualized';

import 'react-virtualized/styles.css';

var images = [];
const columnWidth = 250;
const defaultHeight = 260;
const defaultWidth = columnWidth;

const cache = new CellMeasurerCache({
  defaultHeight,
  defaultWidth,
  fixedWidth: true
})

// Our masonry layout will use 3 columns with a 10px gutter between
const cellPositioner = createMasonryCellPositioner({
  cellMeasurerCache: cache,
  columnCount: 4,
  columnWidth,
  spacer: 27
})

function cellRenderer ({ index, key, parent, style }) {
  const datum = images[index]

  const height = columnWidth  ||  defaultHeight ;

  return (
    <CellMeasurer
      cache={cache}
      index={index}
      key={key}
      parent={parent}
    >
      <div style={style}>
        <img
          src={datum}
          style={{
            height: height,
            width: columnWidth,
            display: "block"
          }}
          alt="info"
        />

      </div>
    </CellMeasurer>
  )
}

class Grid extends React.Component{

  importAll(r) {
    return r.keys().map(r);
  }
  componentWillMount() {
    images = this.importAll(require.context('../imageFolder/', false, /\.(png|jpe?g|svg)$/));
  }
  render(){
    return(
      <div  id="container">
          <div id="viewport">

             <Masonry
            cellCount={images.length}
            cellMeasurerCache={cache}
            cellPositioner={cellPositioner}
            cellRenderer={cellRenderer}
            height={400}
            width={1320}

        />
          </div>

      </div>
    )
  }
}

export default Grid;

I hope this will resolve your issue


问:
converting CURL to postman
I'm trying to import the below cUrl command in "Paste Raw Text" option. Its getting Error - invalid format.

```<code>curl --insecure https://splunkbox.whc/en-US/splunkd/__raw/service -d username=suraj -d password=afjfkdf
</code>```

the option "--insecure" is the problem. How can I pass this from the postman?

答:
Just remove --insecure from your raw text when you paste it.
You can set the insecure mode by File->Settings (General Tab)
Uncheck the "SSL Certificate verification"

Title: converting CURL to postman

Body:
I'm trying to import the below cUrl command in "Paste Raw Text" option. Its getting Error - invalid format.

curl --insecure https://splunkbox.whc/en-US/splunkd/__raw/service -d username=suraj -d password=afjfkdf

the option "--insecure" is the problem. How can I pass this from the postman?


问:
Mount S3 bucket as filesystem on AWS ECS container
I am trying to mount S3 as a volume on AWS ECS docker container using rexray/s3fs driver.

I am able to do this on my local machine, where I installed plugin

```<code>$docker plugin install rexray/s3fs
</code>```

and mounted S3 bucket on docker container.

```<code>$docker plugin ls

ID                  NAME                 DESCRIPTION                                   ENABLED

3a0e14cadc17        rexray/s3fs:latest   REX-Ray FUSE Driver for Amazon Simple Storage   true

$docker run -ti --volume-driver=rexray/s3fs -v s3-bucket:/data img
</code>```

I am trying replicate this on AWS ECS.

Tried follow below document:
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-volumes.html

If I give Driver value then task is not able to run and giving
"was unable to place a task because no container instance met all of its requirements." error.

I am using t2.medium instance and giving of it requirement for task so it should not be H/W requirement issue.

If I remove the Driver config from Job definition task gets executed.

It seems I am miss configuring something.

Is anyone trying/tried same thing, please share the knowledge.

Thanks!!

答:
Your approach of using the rexray/s3fs driver is correct.

These are the steps I followed to get things working on Amazon Linux 1.

First you will need to install s3fs.

```<code>yum install -y gcc libstdc+-devel gcc-c+ fuse fuse-devel curl-devel libxml2-devel mailcap automake openssl-devel git gcc-c++
git clone https://github.com/s3fs-fuse/s3fs-fuse
cd s3fs-fuse/
./autogen.sh
./configure --prefix=/usr --with-openssl
make
make install
</code>```

Now install the driver.  There are some options here you might want to modify such as using an IAM role instead of Access Key and AWS region.

```<code>docker plugin install rexray/s3fs:latest S3FS_REGION=ap-southeast-2 S3FS_OPTIONS="allow_other,iam_role=auto,umask=000" LIBSTORAGE_INTEGRATION_VOLUME_OPERATIONS_MOUNT_ROOTPATH=/ --grant-all-permissions
</code>```

Now the very important step of restarting the ECS agent.  I also update for good measure.

```<code>yum update -y ecs-init
service docker restart && start ecs
</code>```

You should now be ready to create your task definition.  The important part is your volume configuration which is shown below.

```<code>"volumes": [
  {
    "name": "name-of-your-s3-bucket",
    "host": null,
    "dockerVolumeConfiguration": {
      "autoprovision": false,
      "labels": null,
      "scope": "shared",
      "driver": "rexray/s3fs",
      "driverOpts": null
    }
  }
]
</code>```

Now you just need to specify the mount point in the container definition:

```<code>"mountPoints": [
  {
    "readOnly": null,
    "containerPath": "/where/ever/you/want",
    "sourceVolume": "name-of-your-s3-bucket"
  }
]
</code>```

Now as long as you have appropriate IAM permissions for accessing the s3 bucket your container should start and you can get on with using s3 as a volume.

If you get an error running the task that says "ATTRIBUTE" double check that the plugin has been successfully installed on the ec2 instance and the ecs agent has been restarted.  Also double check your driver name is "rexray/s3fs".

Body:
I am trying to mount S3 as a volume on AWS ECS docker container using rexray/s3fs driver.

I am able to do this on my local machine, where I installed plugin

$docker plugin install rexray/s3fs

and mounted S3 bucket on docker container.

$docker plugin ls

ID                  NAME                 DESCRIPTION                                   ENABLED

3a0e14cadc17        rexray/s3fs:latest   REX-Ray FUSE Driver for Amazon Simple Storage   true

$docker run -ti --volume-driver=rexray/s3fs -v s3-bucket:/data img

I am trying replicate this on AWS ECS.

Tried follow below document:
https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-volumes.html

If I give Driver value then task is not able to run and giving
"was unable to place a task because no container instance met all of its requirements." error.

I am using t2.medium instance and giving of it requirement for task so it should not be H/W requirement issue.

If I remove the Driver config from Job definition task gets executed.

It seems I am miss configuring something.

Is anyone trying/tried same thing, please share the knowledge.

Thanks!!

Body:
Your approach of using the rexray/s3fs driver is correct.

These are the steps I followed to get things working on Amazon Linux 1.

First you will need to install s3fs.

yum install -y gcc libstdc+-devel gcc-c+ fuse fuse-devel curl-devel libxml2-devel mailcap automake openssl-devel git gcc-c++
git clone https://github.com/s3fs-fuse/s3fs-fuse
cd s3fs-fuse/
./autogen.sh
./configure --prefix=/usr --with-openssl
make
make install

Now install the driver.  There are some options here you might want to modify such as using an IAM role instead of Access Key and AWS region.

docker plugin install rexray/s3fs:latest S3FS_REGION=ap-southeast-2 S3FS_OPTIONS="allow_other,iam_role=auto,umask=000" LIBSTORAGE_INTEGRATION_VOLUME_OPERATIONS_MOUNT_ROOTPATH=/ --grant-all-permissions

Now the very important step of restarting the ECS agent.  I also update for good measure.

yum update -y ecs-init
service docker restart && start ecs

You should now be ready to create your task definition.  The important part is your volume configuration which is shown below.

"volumes": [
  {
    "name": "name-of-your-s3-bucket",
    "host": null,
    "dockerVolumeConfiguration": {
      "autoprovision": false,
      "labels": null,
      "scope": "shared",
      "driver": "rexray/s3fs",
      "driverOpts": null
    }
  }
]

Now you just need to specify the mount point in the container definition:

"mountPoints": [
  {
    "readOnly": null,
    "containerPath": "/where/ever/you/want",
    "sourceVolume": "name-of-your-s3-bucket"
  }
]

Now as long as you have appropriate IAM permissions for accessing the s3 bucket your container should start and you can get on with using s3 as a volume.

If you get an error running the task that says "ATTRIBUTE" double check that the plugin has been successfully installed on the ec2 instance and the ecs agent has been restarted.  Also double check your driver name is "rexray/s3fs".


问:
Platform specific gems for autotest with bundler
In the rails project I'm working on I inserted support for rspec, cucumber and autotest with this Gemfile (partial)

```<code>gem 'rspec-rails'
gem 'cucumber-rails'
gem 'autotest-standalone'
gem 'autotest-rails-pure'
gem 'zentest-without-autotest'
</code>```

however in order to run tests with autotest i need to execute bundle exec autotest otherwise it fails with this message

```<code>$ autotest
loading autotest/cucumber_rails_rspec_rspec2
Error loading Autotest style autotest/cucumber_rails_rspec_rspec2 (no such file to load -- autotest/cucumber_rails_rspec_rspec2). Aborting.
</code>```

Now I'm developing on a Mac and I'd like to enable autotest-growl and autotest-fsevents gem, but if I insert those lines in my ~/.autotest

```<code>require 'autotest/growl'
require 'autotest/fsevent'
</code>```

then I need to insert the corresponding gems in the Gemfile and everything works, but it breaks builds on my CI server (which is on Linux)

How to solve this without maintaining a different Gemfile for local and CI environments?

EDIT:

For the moment I solved with these lines in Gemfile

```<code>if RUBY_PLATFORM.downcase.include?("darwin") # I'm on Mac
  gem 'autotest-fsevent'
  gem 'autotest-growl'
end
</code>```

It works both locally and on the CI server, I don't know if it mess something, for the moment it seems to work flawlessly.

Any cleaner way to do that is still welcome.

EDIT2:

I switched to groups solutions. While the previous monkeypatch works pretty well both in development and for continuous integration, it will gives you an error in production if you use capistrano bundler tasks for deployments or if you use bundle install --deployment option (which is advised in production)

When using the if RUBY_PLATFORM.downcase.include?("darwin") line you'll get this error on deploy.

```<code># bundle install --deployment --without development test
You are trying to install in deployment mode after changing
your Gemfile. Run `bundle install` elsewhere and add the
updated Gemfile.lock to version control.

You have deleted from the Gemfile:
* autotest-fsevent
* autotest-growl
</code>```

So my final solution to this problem is to include platform specific gems in a given group, say osx, and then in production and on CI server exclude it using bundle.

If you use capistrano to deploy put this in your config.rb

```<code>set :bundle_without,  [:development, :test, :osx]
# capistrano bundler task
require "bundler/capistrano"
</code>```

答:
You might want to use groups in your gemfile, something like:

```<code>group :development do
  gem "autotest-growl"
  gem "autotest-fsevents"
end</code>```

and on the server you use: $ bundle install --without development

Body:
In the rails project I'm working on I inserted support for rspec, cucumber and autotest with this Gemfile (partial)

gem 'rspec-rails'
gem 'cucumber-rails'
gem 'autotest-standalone'
gem 'autotest-rails-pure'
gem 'zentest-without-autotest'

however in order to run tests with autotest i need to execute bundle exec autotest otherwise it fails with this message

$ autotest
loading autotest/cucumber_rails_rspec_rspec2
Error loading Autotest style autotest/cucumber_rails_rspec_rspec2 (no such file to load -- autotest/cucumber_rails_rspec_rspec2). Aborting.

Now I'm developing on a Mac and I'd like to enable autotest-growl and autotest-fsevents gem, but if I insert those lines in my ~/.autotest

require 'autotest/growl'
require 'autotest/fsevent'

then I need to insert the corresponding gems in the Gemfile and everything works, but it breaks builds on my CI server (which is on Linux)

How to solve this without maintaining a different Gemfile for local and CI environments?

EDIT:

For the moment I solved with these lines in Gemfile

if RUBY_PLATFORM.downcase.include?("darwin") # I'm on Mac
  gem 'autotest-fsevent'
  gem 'autotest-growl'
end

It works both locally and on the CI server, I don't know if it mess something, for the moment it seems to work flawlessly.

Any cleaner way to do that is still welcome.

EDIT2:

I switched to groups solutions. While the previous monkeypatch works pretty well both in development and for continuous integration, it will gives you an error in production if you use capistrano bundler tasks for deployments or if you use bundle install --deployment option (which is advised in production)

When using the if RUBY_PLATFORM.downcase.include?("darwin") line you'll get this error on deploy.

# bundle install --deployment --without development test
You are trying to install in deployment mode after changing
your Gemfile. Run `bundle install` elsewhere and add the
updated Gemfile.lock to version control.

You have deleted from the Gemfile:
* autotest-fsevent
* autotest-growl

So my final solution to this problem is to include platform specific gems in a given group, say osx, and then in production and on CI server exclude it using bundle.

If you use capistrano to deploy put this in your config.rb

set :bundle_without,  [:development, :test, :osx]
# capistrano bundler task
require "bundler/capistrano"

Body:
You might want to use groups in your gemfile, something like:

group :development do
  gem "autotest-growl"
  gem "autotest-fsevents"
end

and on the server you use: $ bundle install --without development


问:
create multidimensional json array from a json in php
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.

Here is my data any code. Thanks in advance

My json data

```<code>$val = [
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p1'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p2'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p3'
    },
    {
     'city':'xx',
     'zone':'ww',
     'person_on_zone':'p1'
    },
  ]
</code>```

My expectation is

```<code>[
 {
  'city':'xx',
  'zone':'yy',
  'person_info':{
                  'person_on_zone':'p1',
                  'person_on_zone':'p2',
                  'person_on_zone':'p3',
                }
 },
 {
  'city':'xx',
  'zone':'ww',
  'person_info':{
                  'person_on_zone':'p1'
                }
 },
]
</code>```

Here I tried

```<code>foreach ($val as $v) {
    $new_array['city'] = $v['city'];
    $new_array['zone'] = $v['zone'];
    foreach ($val as $v2) {
        $new_array['person_info'] = $v['person_on_zone'];
    }
}
json_encode($new_array);
</code>```

答:
try this:

first decode json array then use foreach loop with key

```<code>$val = json_decode($val);
foreach ($val as $v){
         $new_array['city'] = $v->city;
         $new_array['zone'] = $v->zone;
         foreach ($val as $key=>$v2){
         $new_array[$key]['person_info'] = $v->person_on_zone;
                    }
                }
 print_r($new_array);
</code>```

Body:
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.

Here is my data any code. Thanks in advance

My json data

$val = [
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p1'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p2'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p3'
    },
    {
     'city':'xx',
     'zone':'ww',
     'person_on_zone':'p1'
    },
  ]

My expectation is

[
 {
  'city':'xx',
  'zone':'yy',
  'person_info':{
                  'person_on_zone':'p1',
                  'person_on_zone':'p2',
                  'person_on_zone':'p3',
                }
 },
 {
  'city':'xx',
  'zone':'ww',
  'person_info':{
                  'person_on_zone':'p1'
                }
 },
]

Here I tried

foreach ($val as $v) {
    $new_array['city'] = $v['city'];
    $new_array['zone'] = $v['zone'];
    foreach ($val as $v2) {
        $new_array['person_info'] = $v['person_on_zone'];
    }
}
json_encode($new_array);

Body:
try this:

first decode json array then use foreach loop with key

$val = json_decode($val);
foreach ($val as $v){
         $new_array['city'] = $v->city;
         $new_array['zone'] = $v->zone;
         foreach ($val as $key=>$v2){
         $new_array[$key]['person_info'] = $v->person_on_zone;
                    }
                }
 print_r($new_array);


问:
Can't build for Android with error "Failed resolution of R$color" after build JAR
While I run the project with an implementation project(path: ':rocket_library') then the resource (Ex: R.color.color_rocket_web) file works fine. But after building the JAR file and include the JAR with project resource not found. Is it possible to attach the resource files in a JAR?

The color not found from the project:

Library code:
On runtime also not found from Libray.

```<code>import infix.imrankst1221.rocket.library.R

fun getThemePrimaryColor(mContext : Context): Int {
    return PreferenceUtils.getInstance().getIntegerValue(Constants.KEY_COLOR_PRIMARY, ContextCompat.getColor(mContext, R.color.my_color))
}
</code>```

Runtime exception:

```<code>java.lang.NoClassDefFoundError: Failed resolution of: Linfix/imrankst1221/rocket/library/R$color;
            at infix.imrankst1221.rocket.library.utility.UtilMethods.getThemePrimaryColor(UtilMethods.kt:65)
            at infix.imrankst1221.codecanyon.ui.splash.SplashActivity.onCreate(SplashActivity.kt:30)
Caused by: java.lang.ClassNotFoundException: Didn't find class "infix.imrankst1221.rocket.library.R$color" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/infix.imrankst1221.rocket.web-_mlMdyx2A0UqLZig9zkW5Q==/base.apk"],nativeLibraryDirectories=[/data/app/infix.imrankst1221.rocket.web-_mlMdyx2A0UqLZig9zkW5Q==/lib/x86, /system/lib]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
</code>```

Library Build.Gradle:

```<code>apply plugin: 'com.android.library'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    sourceSets {
        main {
            res.srcDirs = ['src/main/res']
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.browser:browser:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha06'

    implementation 'com.google.code.gson:gson:2.8.5'

}
task createJar(type: Copy) {
    from('build/intermediates/packaged-classes/release/')
    into('libs/')
    include('classes.jar')
    rename('classes.jar', 'rocket_web.jar')
}
</code>```

答:
This must be a comment!!
I dont have musch privilege to  comment

Did you tried these..?

Clean Project and Rebuild.(Build -> Clean Project and rebuild)

Invalidate Cache and Restart (Files -> Invalidate Caches /Restart)

Body:
While I run the project with an implementation project(path: ':rocket_library') then the resource (Ex: R.color.color_rocket_web) file works fine. But after building the JAR file and include the JAR with project resource not found. Is it possible to attach the resource files in a JAR?

The color not found from the project:

Library code:
On runtime also not found from Libray.

import infix.imrankst1221.rocket.library.R

fun getThemePrimaryColor(mContext : Context): Int {
    return PreferenceUtils.getInstance().getIntegerValue(Constants.KEY_COLOR_PRIMARY, ContextCompat.getColor(mContext, R.color.my_color))
}

Runtime exception:

java.lang.NoClassDefFoundError: Failed resolution of: Linfix/imrankst1221/rocket/library/R$color;
            at infix.imrankst1221.rocket.library.utility.UtilMethods.getThemePrimaryColor(UtilMethods.kt:65)
            at infix.imrankst1221.codecanyon.ui.splash.SplashActivity.onCreate(SplashActivity.kt:30)
Caused by: java.lang.ClassNotFoundException: Didn't find class "infix.imrankst1221.rocket.library.R$color" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/infix.imrankst1221.rocket.web-_mlMdyx2A0UqLZig9zkW5Q==/base.apk"],nativeLibraryDirectories=[/data/app/infix.imrankst1221.rocket.web-_mlMdyx2A0UqLZig9zkW5Q==/lib/x86, /system/lib]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:125)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:379)

Library Build.Gradle:

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'

    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    sourceSets {
        main {
            res.srcDirs = ['src/main/res']
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.android.support:appcompat-v7:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.browser:browser:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha06'

    implementation 'com.google.code.gson:gson:2.8.5'

}
task createJar(type: Copy) {
    from('build/intermediates/packaged-classes/release/')
    into('libs/')
    include('classes.jar')
    rename('classes.jar', 'rocket_web.jar')
}


问:
Can we pass the created Stateful widget to another dart file and add that widget as body along with setState?
Can we pass the stateful widget created in one dart file to another dart file along with the setState changes and render that widget as the body in another stateful dart file.
Actually i am able to get the body but my setState is not working.

i want to pass the stateful widget(ie widget with dropdownbutton) to another page and my setState should work and i should be able to capture the data.

答:
When you want to call the parent method, you can use state up. (Give call back to parent).
and if you want to call child method from a parent you can use GlobalKey.


问:
Why the message doesn't to be redelivered?
The Acknowledgment Deadline is 10 seconds. When I use asynchronous-pull way to process the message, I don't call message.ack() and message.nack(), wait for the message ack deadline and expect Pub/Sub redeliver this message.

After waiting over 10 seconds, the subscriber doesn't receive the message again. Here is my code:

subscriber:

import { pubsubClient, IMessage, parseMessageData } from '../../googlePubsub';
import { logger } from '../../utils';

const topicName = 'asynchronous-pull-test';
const subName = 'asynchronous-pull-test';
const subscription = pubsubClient.topic(topicName).subscription(subName);
const onMessage = (message: IMessage) => {
  const { data, ...rest } = message;
  const jsonData = parseMessageData(data);
  logger.debug('received message', { arguments: { ...rest, data: jsonData } });

  const publishTime = new Date(message.publishTime).getTime();
  const republishTimestamp = Date.now() - 5 * 1000;

  if (publishTime < republishTimestamp) {
    logger.info('message acked');
    message.ack();
  } else {
    logger.info('push message back to MQ');
  }
};
logger.info('subscribe the MQ');
subscription.on('message', onMessage).on('error', (err: Error) => logger.error(err));

```

<p><code>publisher</code>:</p>

<pre class="lang-js prettyprint-override"><code>const topicName = 'asynchronous-pull-test';

async function main() {
  const messagePayload = { email: faker.internet.email(), campaignId: '1' };
  await pub(topicName, messagePayload);
}

main();
</code>```

I am using "@google-cloud/pubsub": "^0.19.0",

I expect the subscriber will receive the message again at the ack deadline 10 seconds later. Which means my subscriber receives and processes the message every 10 seconds. Am I wrong?

答: You should nack the message to tell Pub/Sub to redeliver it. Documentation</p>

Body:
The Acknowledgment Deadline is 10 seconds. When I use asynchronous-pull way to process the message, I don't call message.ack() and message.nack(), wait for the message ack deadline and expect Pub/Sub redeliver this message.

After waiting over 10 seconds, the subscriber doesn't receive the message again. Here is my code:

subscriber:

import { pubsubClient, IMessage, parseMessageData } from '../../googlePubsub';
import { logger } from '../../utils';

const topicName = 'asynchronous-pull-test';
const subName = 'asynchronous-pull-test';
const subscription = pubsubClient.topic(topicName).subscription(subName);
const onMessage = (message: IMessage) => {
  const { data, ...rest } = message;
  const jsonData = parseMessageData(data);
  logger.debug('received message', { arguments: { ...rest, data: jsonData } });

  const publishTime = new Date(message.publishTime).getTime();
  const republishTimestamp = Date.now() - 5 * 1000;

  if (publishTime < republishTimestamp) {
    logger.info('message acked');
    message.ack();
  } else {
    logger.info('push message back to MQ');
  }
};
logger.info('subscribe the MQ');
subscription.on('message', onMessage).on('error', (err: Error) => logger.error(err));

publisher:

const topicName = 'asynchronous-pull-test';

async function main() {
  const messagePayload = { email: faker.internet.email(), campaignId: '1' };
  await pub(topicName, messagePayload);
}

main();

I am using "@google-cloud/pubsub": "^0.19.0",

I expect the subscriber will receive the message again at the ack deadline 10 seconds later. Which means my subscriber receives and processes the message every 10 seconds. Am I wrong?


问:
Convert SQL query to use Laravel query builder
I am trying to convert this SQL code to use Laravel's query builder.</p>

```<code>SELECT b.name
FROM brands b
INNER JOIN products p
    ON b.id = p.brand_id
INNER JOIN transaction_sell_lines tr
    ON p.brand_id=tr.product_id
</code>```

答:
Assuming you have the following modal

Brand

Product

TransactionSellLines

For Brand.php [i.e Brand Modal]

```<code>public function products(){
  return $this->hasMany(Product::class,'brand_id','id');
}
</code>```

For Product.php Modal

```<code>public function transactionSellLines(){
  return $this->hasMany(TransactionSellLines::class,'product_id','id');
}
</code>```

Then your Laravel Eloquent query will be like this:

```<code>Brand::with('products.transactionSellLines')->get();
</code>```

Body:
I am trying to convert this SQL code to use Laravel's query builder.

SELECT b.name
FROM brands b
INNER JOIN products p
    ON b.id = p.brand_id
INNER JOIN transaction_sell_lines tr
    ON p.brand_id=tr.product_id

Body:
Assuming you have the following modal

Brand

Product

TransactionSellLines

For Brand.php [i.e Brand Modal]

public function products(){
  return $this->hasMany(Product::class,'brand_id','id');
}

For Product.php Modal

public function transactionSellLines(){
  return $this->hasMany(TransactionSellLines::class,'product_id','id');
}

Then your Laravel Eloquent query will be like this:

Brand::with('products.transactionSellLines')->get();


问:
Why would you select ATX or SETEXT markdown headers style?
I'm creating a simple Markdown editor (WYSIWYG style, the user doesn't see the Markdown). What are the consequences in terms of git management when you use Atx or Setext, any recommendation?</p>

答:
In term of Git management: very little consequence since it remains a simple text file.

The choice is more about your Markdown engine support (compared here) that you will end up using when reading that converted markdown file.


问:
Does Beacon Notification Can wake up terminated app
I have project need to add notifications with Beacons。I have some questions wanna to make sure.

does os can receive beacon notification without APP running?

Can we show different showing content depend on different beacon notification?

can we open terminated app by beacon notification?

can the app do different behavior depend by the beacon notification content after start up?

Thanks。

答:
1- How beacon works

The Android Beacon Library can launch your app into the background to
  start looking for beacons after the phone boots. This will happen
  transparently with no visible user interface, while the rest of your
  app remains idle.

Once the desired beacon is detected, a callback method fires where you
  can push a custom notification message. You can further configure the
  notification so it launches a specific part of your app when pressed.

2- different notification

Yes ! each beacon has its id and you can handle showing different notification depending on the id and also different content

3- lunching app

Yes !  you can add your logic in the services that handle beacon notification method to start the preferred activity.

WARNING: launching a UI without any user interaction is a very very bad practice for most of the applications!

[...] Interrupting what the user is currently doing is considered bad
  design form, especially from something that is supposed to be
  operating in the background. Therefore, you should consider using a
  Notification [...] to launch the desired Activity when the user
  decides it is time to investigate. [...]

4- App behavior

Yes ! all you have to do is setting your pendingIntent accordingly to the notification


问:
logical problem for finding the probability
hi to all

 I want to know how to find the solution for this problem. consider in a Jar there are 10 papers numbered 1 to 10. we have to take 2 papers from that. what is the probability that 2 numbers are consecutive numbers.

答:
The probability of getting 2-8 is 8/10. Once we have a given number in that range, the probability of getting one of the two adjacent numbers is 2/9. 8/10 * 2/9 = 16/90.

The probability of getting either a 1 or a 10 is 2/10. If we have one of those two endpoint numbers, the probability of getting the one adjacent number is 1/9. 2/10 * 1/9 = 2/90.

Adding these together, we have a total probability of 18/90 or 1/5.


问:
How to specify a default value for argument list processed by click?
I have this line of code that is expected to grab all the file names passed to my Python script:

```<code>@click.argument("logs", nargs=-1, type=click.File('r'), required=1)
</code>```

When no file names are passed, I want to default to -, that is, the standard input.  So, if I try:

```<code>@click.argument("logs", nargs=-1, type=click.File('r'), required=1, default="-")
</code>```

click becomes unhappy and throws this error:

TypeError: nargs=-1 in combination with a default value is not supported.

Is there a workaround for this? I tried setting nargs=0 but that throws a different error:

IndexError: tuple index out of range

答:
To default to stdin for a potentially empty list of files, you can define a custom argument class like:

Custom Class:

```<code>class FilesDefaultToStdin(click.Argument):
    def __init__(self, *args, **kwargs):
        kwargs['nargs'] = -1
        kwargs['type'] = click.File('r')
        super().__init__(*args, **kwargs)

    def full_process_value(self, ctx, value):
        return super().process_value(ctx, value or ('-', ))
</code>```

Defining this behavior as a class provides for easy reuse.

To use the Custom Class:

```<code>@click.command()
@click.argument("logs", cls=FilesDefaultToStdin)
def main(logs):
    ...
</code>```

How does this work?

This works because click is a well designed OO framework. The @click.argument() decorator usually instantiates a click.Argument object but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Argument in our own class and over-ride the desired methods.

In this case, we override click.Argument.full_process_value().  In our full_process_value() we look for an empty argument list, and if empty, we add the - (stdin) argument to the list.

In addition, we auto assign the nargs=-1 and the type=click.File('r') arguments.

Body:
I have this line of code that is expected to grab all the file names passed to my Python script:

@click.argument("logs", nargs=-1, type=click.File('r'), required=1)

When no file names are passed, I want to default to -, that is, the standard input.  So, if I try:

@click.argument("logs", nargs=-1, type=click.File('r'), required=1, default="-")

click becomes unhappy and throws this error:

TypeError: nargs=-1 in combination with a default value is not supported.

Is there a workaround for this? I tried setting nargs=0 but that throws a different error:

IndexError: tuple index out of range

Body:
To default to stdin for a potentially empty list of files, you can define a custom argument class like:

Custom Class:

class FilesDefaultToStdin(click.Argument):
    def __init__(self, *args, **kwargs):
        kwargs['nargs'] = -1
        kwargs['type'] = click.File('r')
        super().__init__(*args, **kwargs)

    def full_process_value(self, ctx, value):
        return super().process_value(ctx, value or ('-', ))

Defining this behavior as a class provides for easy reuse.

To use the Custom Class:

@click.command()
@click.argument("logs", cls=FilesDefaultToStdin)
def main(logs):
    ...

How does this work?

This works because click is a well designed OO framework. The @click.argument() decorator usually instantiates a click.Argument object but allows this behavior to be over ridden with the cls parameter. So it is a relatively easy matter to inherit from click.Argument in our own class and over-ride the desired methods.

In this case, we override click.Argument.full_process_value().  In our full_process_value() we look for an empty argument list, and if empty, we add the - (stdin) argument to the list.

In addition, we auto assign the nargs=-1 and the type=click.File('r') arguments.


问:
in WP_Query get_current_user_id( ) is not returning data for custom post type
i want to fetch data from my custom post type (note) so that's why i'm using WP_Query() , it's working fine but when i want to fetch data only related to the user logged in so i'm using author => get_current_user_id() now my web page showing nothing

```<code><?php

    $args = array(
    'author'  => get_current_user_id(), // before using this it was working fine
    'posts_per_page' => -1,
    'post_type' => 'note',
     );

$userNotes = new WP_Query( $args );
if ($userNotes->have_posts()): while ($userNotes->have_posts()) : $userNotes->the_post(); ?>

   <li>
      <input class="note-title-field" value="<?php echo esc_attr(get_the_title()); ?>">
      <span class="edit-note"><i class="fa fa-pencil" aria-hidden="true"></i> Edit</span>
      <span class="delete-note"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</span>
      <textarea class="note-body-field"><?php echo esc_attr(get_the_content()); ?></textarea>
     </li>

<?php
endwhile; endif;
wp_reset_postdata();
wp_reset_query();

        ?>
</code>```

it's showing nothing (blank)

my note custom post type

// Note Post Type

```<code>register_post_type('note',[
'show_in_rest' => true,
'supports' => ['title','editor'],
'public'    => false,
'show_ui'   =>true,
'labels'    => [
    'name'=>'Notes',
    'add_new_item' =>'Add New Note',
    'edit_item' => 'Edit Note',
    'all_items' =>'All Notes',
    'singular_name' =>'Note'
],
'menu_icon' => 'dashicons-welcome-write-blog'
</code>```

]);

```<code><?php

  if (!is_user_logged_in()) {
    wp_redirect(esc_url(site_url('/')));
    exit;
  }
  get_header();

    pageBanner();
     ?>

    <div class="container container--narrow page-section">
      <ul class="min-list link-list" id="my-notes">
        <?php

    $args = array(
        'posts_per_page' => '-1',
        'post_type' => 'note',
        'author' => get_current_user_id()
    );

    $userNotes = new WP_Query($args);
    while($userNotes->have_posts()) : $userNotes->the_post();
    ?>
     <li>
              <input class="note-title-field" value="<?php echo esc_attr(get_the_title()); ?>">
              <span class="edit-note"><i class="fa fa-pencil" aria-hidden="true"></i> Edit</span>
              <span class="delete-note"><i class="fa fa-trash-o" aria-hidden="true"></i> Delete</span>
              <textarea class="note-body-field"><?php echo esc_attr(get_the_content()); ?></textarea>
            </li>

    <?php

    endwhile;

wp_reset_postdata();

        ?>
      </ul>
    </div>

  <?php

  get_footer();

?>
</code>```

答:
Try the following code.</p>

```<code>if ( is_user_logged_in() ):

    global $current_user;
    get_currentuserinfo();
    $author_query = array('posts_per_page' => '-1','post_type' => 'note','author' => $current_user->ID);
    $author_posts = new WP_Query($author_query);
    while($author_posts->have_posts()) : $author_posts->the_post();
    ?>
        <a href="<?php the_permalink(); ?>" title="<?php get_title(); ?>"></a>
    <?php
    endwhile;

endif;
</code>```

Body:
i want to fetch data from my custom post type (note) so that's why i'm using WP_Query() , it's working fine but when i want to fetch data only related to the user logged in so i'm using author => get_current_user_id() now my web page showing nothing

<?php

    $args = array(
    'author'  => get_current_user_id(), // before using this it was working fine
    'posts_per_page' => -1,
    'post_type' => 'note',
     );

$userNotes = new WP_Query( $args );
if ($userNotes->have_posts()): while ($userNotes->have_posts()) : $userNotes->the_post(); ?>

      <input class="note-title-field" value="<?php echo esc_attr(get_the_title()); ?>">
       Edit
       Delete
      <textarea class="note-body-field"><?php echo esc_attr(get_the_content()); ?></textarea>

<?php
endwhile; endif;
wp_reset_postdata();
wp_reset_query();

        ?>

it's showing nothing (blank)

my note custom post type

// Note Post Type

register_post_type('note',[
'show_in_rest' => true,
'supports' => ['title','editor'],
'public'    => false,
'show_ui'   =>true,
'labels'    => [
    'name'=>'Notes',
    'add_new_item' =>'Add New Note',
    'edit_item' => 'Edit Note',
    'all_items' =>'All Notes',
    'singular_name' =>'Note'
],
'menu_icon' => 'dashicons-welcome-write-blog'

]);

<?php

  if (!is_user_logged_in()) {
    wp_redirect(esc_url(site_url('/')));
    exit;
  }
  get_header();

    pageBanner();
     ?>

        <?php

    $args = array(
        'posts_per_page' => '-1',
        'post_type' => 'note',
        'author' => get_current_user_id()
    );

    $userNotes = new WP_Query($args);
    while($userNotes->have_posts()) : $userNotes->the_post();
    ?>

              <input class="note-title-field" value="<?php echo esc_attr(get_the_title()); ?>">
               Edit
               Delete
              <textarea class="note-body-field"><?php echo esc_attr(get_the_content()); ?></textarea>

    <?php

    endwhile;

wp_reset_postdata();

        ?>

  <?php

  get_footer();

?>

Body:
Try the following code.

if ( is_user_logged_in() ):

    global $current_user;
    get_currentuserinfo();
    $author_query = array('posts_per_page' => '-1','post_type' => 'note','author' => $current_user->ID);
    $author_posts = new WP_Query($author_query);
    while($author_posts->have_posts()) : $author_posts->the_post();
    ?>
        <a href="<?php the_permalink(); ?>" title="<?php get_title(); ?>"></a>
    <?php
    endwhile;

endif;


问:
How to replace all newlines after reading a file
How can I replace a newline in a string with a ','? I have a string that is read from a file:

```<code>const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);
</code>```

It takes a string from a file:

```<code>a,b,c,d,e,f
,,,,,
g,h,i,j,k,l
</code>```

I'm able to detect the newline with this:

```<code>if (char === '\n')
</code>```

But replacing \n like this doesn't work

```<code>str = csvString.replace('/\n/g');
</code>```

I want to get the string to look like this:

```<code>a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,
</code>```

答:
Try replacing the pattern $ with ,, comma:

var input = 'a,b,c,d,e,f';
input = input.replace(/$/mg, ",");
console.log(input);```

Since you intend to retain the newlines/carriage returns, we can just take advantage of $ to represent the end of each line.

Body:
How can I replace a newline in a string with a ','? I have a string that is read from a file:

const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);

It takes a string from a file:

a,b,c,d,e,f
,,,,,
g,h,i,j,k,l

I'm able to detect the newline with this:

if (char === '\n')

But replacing \n like this doesn't work

str = csvString.replace('/\n/g');

I want to get the string to look like this:

a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,

Body:
Try replacing the pattern $ with ,, comma:

var input = 'a,b,c,d,e,f';
input = input.replace(/$/mg, ",");
console.log(input);

Since you intend to retain the newlines/carriage returns, we can just take advantage of $ to represent the end of each line.


问:
Handle exceptions caused by parsing nullable parameters in controller action
I have an endpoint

```<code>[HttpGet]
public async Task<ActionResult> GetNodes([FromQuery] Guid? parentId)
</code>```

And call it like that
GET .../api/nodes?parentId=null

Asp.net throws an exception when parsing parameter "The value 'null' is not valid."

How to override that behaviour to make it parse nullable types to null if an exception occurs?

I expect:

GET .../api/nodes?parentId=null should call action with parentId == null

GET .../api/nodes?parentId=50d21ddd-6a95-46db-bff9-c943cf5b0df1 should call action with parentId = "50d21ddd-6a95-46db-bff9-c943cf5b0df1"

GET .../api/nodes?parentId=something_not_parsable_to_guid should call action with parentId = null

答:
The solution from @Karan is the way you should go. But if you are not willing to change your client-side script, you still have the option as follows :</p>

```<code>[HttpGet]
public async Task<ActionResult> GetNodes() {
     var parentId = Request.QueryString["parentId"].ToString();
     Guid guid;
     if (Guid.TryParse(parentId , out guid))
     {
       // use guid here
     }

}
</code>```

Body:
I have an endpoint

[HttpGet]
public async Task<ActionResult> GetNodes([FromQuery] Guid? parentId)

And call it like that
GET .../api/nodes?parentId=null

Asp.net throws an exception when parsing parameter "The value 'null' is not valid."

How to override that behaviour to make it parse nullable types to null if an exception occurs?

I expect:

GET .../api/nodes?parentId=null should call action with parentId == null

GET .../api/nodes?parentId=50d21ddd-6a95-46db-bff9-c943cf5b0df1 should call action with parentId = "50d21ddd-6a95-46db-bff9-c943cf5b0df1"

GET .../api/nodes?parentId=something_not_parsable_to_guid should call action with parentId = null

Body:
The solution from @Karan is the way you should go. But if you are not willing to change your client-side script, you still have the option as follows :

[HttpGet]
public async Task<ActionResult> GetNodes() {
     var parentId = Request.QueryString["parentId"].ToString();
     Guid guid;
     if (Guid.TryParse(parentId , out guid))
     {
       // use guid here
     }

}


问:
react native push notification doesn't work in Android 8.1 (API level 27)
In my react native app, I tried to handle Scheduled locale Notifications using this library react-native-push-notification , it work's fine in devices that runs android API's under 25, so the problem occurs in android Oreo version, I have tried a lot of solutions, like using channels and add a notification to that channel, but without result, Help please!!!

My react native version :

react-native-cli: 2.0.1

react-native: 0.58.5

From android Project :

```<code>    buildToolsVersion = "28.0.2"
    minSdkVersion = 16
    compileSdkVersion = 28
    targetSdkVersion = 27
    supportLibVersion = "28.0.0"
</code>```

答:
react native push notification doesn't work in >=o because of battery optimization...

Add channel in MAinActivity.java

```<code>public void onResume() {
        super.onResume();
        NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;

            NotificationChannel notificationChannel = new NotificationChannel("channelID", "channelName", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            nMgr.createNotificationChannel(notificationChannel);
        }

        nMgr.cancelAll();
    }
</code>```

Body:
In my react native app, I tried to handle Scheduled locale Notifications using this library react-native-push-notification , it work's fine in devices that runs android API's under 25, so the problem occurs in android Oreo version, I have tried a lot of solutions, like using channels and add a notification to that channel, but without result, Help please!!!

My react native version :

react-native-cli: 2.0.1

react-native: 0.58.5

From android Project :

    buildToolsVersion = "28.0.2"
    minSdkVersion = 16
    compileSdkVersion = 28
    targetSdkVersion = 27
    supportLibVersion = "28.0.0"

Body:
react native push notification doesn't work in >=o because of battery optimization...

Add channel in MAinActivity.java

public void onResume() {
        super.onResume();
        NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;

            NotificationChannel notificationChannel = new NotificationChannel("channelID", "channelName", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            nMgr.createNotificationChannel(notificationChannel);
        }

        nMgr.cancelAll();
    }