问:
Python 2.7 - If statement evaluates incorrectly when using .lower string modifier
New to Python and coding in general. I've tried to implement a simple code that will evaluate user input as either Y or N. If the answer is N, then the script should stop running. Otherwise, it should continue (in this case, printing a statement). Seems to work fine when I enter the exact string that is called for in the if statement. However, if I try to evaluate the answer using the .lower modifier, it just seems to ignore the input and proceed no matter what. Any assistance would be welcome. See code below. Thank you!</p>

```<code>answer = str(raw_input("Enter Y or N: "))
if answer.lower == 'n':
    quit()
else:
    print "Cool! Next question."
</code>```

答:
You're not calling .lower, you're comparing the function .lower to the string 'n'.  That will never be true.

Try this code snippet instead:

```<code>if answer.lower() == 'n':
</code>```

Body:
New to Python and coding in general. I've tried to implement a simple code that will evaluate user input as either Y or N. If the answer is N, then the script should stop running. Otherwise, it should continue (in this case, printing a statement). Seems to work fine when I enter the exact string that is called for in the if statement. However, if I try to evaluate the answer using the .lower modifier, it just seems to ignore the input and proceed no matter what. Any assistance would be welcome. See code below. Thank you!

answer = str(raw_input("Enter Y or N: "))
if answer.lower == 'n':
    quit()
else:
    print "Cool! Next question."

Body:
You're not calling .lower, you're comparing the function .lower to the string 'n'.  That will never be true.

Try this code snippet instead:

if answer.lower() == 'n':


来源: stackexchange

问:
How to write generic methods in coded ui which can used with any type of control irrespective of its property same or changed?
I am using coded ui automation in Visual Studio 2012. So I have a  requirement where I have to write some generic/common methods which can be used with any type of UI control.

I an new to coded ui. How to write such methods so that i can reuse it in code.

Basically, for example I want common methods for verifying certain control/Tiles/TAB/Objects is visible or not on UI.

答:
I implemented a generic search function as such:

```<code>public static ControlType IdentifyControlByIdentifierEqualsValue<ControlType>(UITestControl parent, ControlIdentifier identifierTypeAndValue) where ControlType : UITestControl
    {
        var control = (ControlType)Activator.CreateInstance(typeof(ControlType), new UITestControl[] { parent });
        control.SearchProperties.Add(identifierTypeAndValue.Type, identifierTypeAndValue.Value);
        var wasFound = control.TryFind();
        if (!wasFound)
            throw new UITestControlNotFoundException("The control of type " + control.GetType().ToString() + " with the identifier type of " + identifierTypeAndValue.Type + " and the identifying attribute of " + identifierTypeAndValue.Value + " was not able to be found");
        return control;
    }
</code>```

With the supporting class

```<code>public class ControlIdentifier
    {
        public ControlIdentifier(string type, string id)
        {
            Type = type;
            Value = id;
        }
        public string Type { get; set; }
        public string Value { get; set; }
    }
</code>```

Called as such:

```<code>IdentifyControlByIdentifierEqualsValue<WpfTabList>(workWindow,
    new ControlIdentifer(WpfButton.PropertyNames.Name, "OK");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I implemented a generic search function as such:

public static ControlType IdentifyControlByIdentifierEqualsValue<ControlType>(UITestControl parent, ControlIdentifier identifierTypeAndValue) where ControlType : UITestControl
    {
        var control = (ControlType)Activator.CreateInstance(typeof(ControlType), new UITestControl[] { parent });
        control.SearchProperties.Add(identifierTypeAndValue.Type, identifierTypeAndValue.Value);
        var wasFound = control.TryFind();
        if (!wasFound)
            throw new UITestControlNotFoundException("The control of type " + control.GetType().ToString() + " with the identifier type of " + identifierTypeAndValue.Type + " and the identifying attribute of " + identifierTypeAndValue.Value + " was not able to be found");
        return control;
    }

With the supporting class

public class ControlIdentifier
    {
        public ControlIdentifier(string type, string id)
        {
            Type = type;
            Value = id;
        }
        public string Type { get; set; }
        public string Value { get; set; }
    }

Called as such:

IdentifyControlByIdentifierEqualsValue<WpfTabList>(workWindow,
    new ControlIdentifer(WpfButton.PropertyNames.Name, "OK");


问:
Javascript iframe elements are not lookable?
In browser console I can't find element inside iframe(after page reload) until I make some clicks in it. After clicks it works perfectly. Does anybody know how to deal with it?

Thanks in advance for any help.

答:
If you need to access the iframe elements :

```<code>window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')
</code>```

As mentioned here Access iframe elements in JavaScript, be careful that the src of the iframe is in the same domain as the parent page.

You may need to wait for the iframe to fully load.
 Check out this post on how to use the iframe onload event :
 Capture iframe load complete event.

If you just want to access them from the console, inspect one of the iframe's elements, then the browser will append the whole iframe content on the current page.

I hope this could help you.

Body:
If you need to access the iframe elements :

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

As mentioned here Access iframe elements in JavaScript, be careful that the src of the iframe is in the same domain as the parent page.

You may need to wait for the iframe to fully load.
 Check out this post on how to use the iframe onload event :
 Capture iframe load complete event.

If you just want to access them from the console, inspect one of the iframe's elements, then the browser will append the whole iframe content on the current page.

I hope this could help you.


问:
Actor accessing things out of scope
I'm using the Akka libraries.

What happens when multiple actors call a function on an object? Would this block other actors from accessing the object?

The reason I ask this is because I want to use JBCrypt with akka actors. And since we can encrypt multiple strings concurrently I have each actor calling JBcrypt.hash(...). Not sure how it works since I think, in scala, objects exist in one place, and I feel like multiple actors using the same object (library) might block the concurrency from actually happening.

答: It depends on how the function is implemented. If the function accessed some internal mutable state and tries to synchronize in order to achieve thread safety then there is a problem. If it's a pure function and does not access any external state, then it is safe. If the function has the mutable state at least it must contain the mutable state to itself.</p>

Title: Actor accessing things out of scope


问:
Transaction block in Java?
What is the idiomatic way to perform a transaction in Java? I have some code

```<code>myObject oldVar = myVar.toMyObject();
myVar.mutationAndDBInsertion;
myObject newVar = myVar.toMyObject();
</code>```

I want to wrap this all in a single transaction block, so that I am sure that the myVar object will not mutate unless the database operation is successful, and the oldVar and newVar will be accurate representations of the object state before and after the mutation. How should I approach this?

答:
Committing Transactions

After the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit. The following method, CoffeesTable.updateCoffeeSales, in which con is an active connection, illustrates a transaction:

public void updateCoffeeSales(HashMap salesForWeek)
    throws SQLException {

```<code>PreparedStatement updateSales = null;
PreparedStatement updateTotal = null;

String updateString =
    "update " + dbName + ".COFFEES " +
    "set SALES = ? where COF_NAME = ?";

String updateStatement =
    "update " + dbName + ".COFFEES " +
    "set TOTAL = TOTAL + ? " +
    "where COF_NAME = ?";

try {
    con.setAutoCommit(false);
    updateSales = con.prepareStatement(updateString);
    updateTotal = con.prepareStatement(updateStatement);

    for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
        updateSales.setInt(1, e.getValue().intValue());
        updateSales.setString(2, e.getKey());
        updateSales.executeUpdate();
        updateTotal.setInt(1, e.getValue().intValue());
        updateTotal.setString(2, e.getKey());
        updateTotal.executeUpdate();
        con.commit();
    }
} catch (SQLException e ) {
    JDBCTutorialUtilities.printSQLException(e);
    if (con != null) {
        try {
            System.err.print("Transaction is being rolled back");
            con.rollback();
        } catch(SQLException excep) {
            JDBCTutorialUtilities.printSQLException(excep);
        }
    }
} finally {
    if (updateSales != null) {
        updateSales.close();
    }
    if (updateTotal != null) {
        updateTotal.close();
    }
    con.setAutoCommit(true);
}
</code>```

}

from ORACLE WEB Page

Title: Transaction block in Java?

Body:
What is the idiomatic way to perform a transaction in Java? I have some code

myObject oldVar = myVar.toMyObject();
myVar.mutationAndDBInsertion;
myObject newVar = myVar.toMyObject();

I want to wrap this all in a single transaction block, so that I am sure that the myVar object will not mutate unless the database operation is successful, and the oldVar and newVar will be accurate representations of the object state before and after the mutation. How should I approach this?

Body:
Committing Transactions

After the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit. The following method, CoffeesTable.updateCoffeeSales, in which con is an active connection, illustrates a transaction:

public void updateCoffeeSales(HashMap salesForWeek)
    throws SQLException {

PreparedStatement updateSales = null;
PreparedStatement updateTotal = null;

String updateString =
    "update " + dbName + ".COFFEES " +
    "set SALES = ? where COF_NAME = ?";

String updateStatement =
    "update " + dbName + ".COFFEES " +
    "set TOTAL = TOTAL + ? " +
    "where COF_NAME = ?";

try {
    con.setAutoCommit(false);
    updateSales = con.prepareStatement(updateString);
    updateTotal = con.prepareStatement(updateStatement);

    for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
        updateSales.setInt(1, e.getValue().intValue());
        updateSales.setString(2, e.getKey());
        updateSales.executeUpdate();
        updateTotal.setInt(1, e.getValue().intValue());
        updateTotal.setString(2, e.getKey());
        updateTotal.executeUpdate();
        con.commit();
    }
} catch (SQLException e ) {
    JDBCTutorialUtilities.printSQLException(e);
    if (con != null) {
        try {
            System.err.print("Transaction is being rolled back");
            con.rollback();
        } catch(SQLException excep) {
            JDBCTutorialUtilities.printSQLException(excep);
        }
    }
} finally {
    if (updateSales != null) {
        updateSales.close();
    }
    if (updateTotal != null) {
        updateTotal.close();
    }
    con.setAutoCommit(true);
}

}

from ORACLE WEB Page


问:
Pyodbc update cursor

Hi, I have a script on Python with SQL and I use fecthall() method to extract the elements I want and all great until there, because I want do modify two columns (datetime.date and datetime.time) to another timezone but I read docs and Its seems its not veare easy...

For now I have the next piece of code fetching the table and then trying to covert firts the date to another timezone, I know... Its a date but if in Spain now is 12am from 5/12/2017 in Mexico is 5pm from 04/12/2017 soooo...

BTW Im using pytz

```<code>cursor.execute(cadenaSQL + cadenaSQL_dos)
            su_dict[base+' hagent'] = cursor.fetchall()
            for row in su_dict[base+' hagent']:
                row = list(row)[0]
                print row
                row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico))
</code>```

For now I got this error with that code:

Traceback (most recent call last):   File "cms_V2_30m.py", line 1535,
  in
      main()   File "cms_V2_30m.py", line 1444, in main
      select_hagent()   File "cms_V2_30m.py", line 211, in select_hagent
      row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico)) TypeError: 'datetime.date' object
  is unsubscriptable

EDIT:

I think I´m close, the problem now is with row object, because it is a tuple... so it is inmutble, so I am trying to find a way to change this vale...

The New code:

```<code>    for row in su_dict[base + ' hagent']:
        print row[0]
        #list(row)
        #print my_date[0]
        #print datetime.datetime.combine(my_date[0], hoyUTC.time())
        row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico)
</code>```

The new error:

Traceback (most recent call last):   File "cms_V2_30m.py", line 1538,
  in
      main()   File "cms_V2_30m.py", line 1447, in main
      select_hagent()   File "cms_V2_30m.py", line 214, in select_hagent
      row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico) TypeError: 'tuple' object does not
  support item assignment

答:
It looks like your issue is with overwriting row within the loop. Try this instead?

```<code>for row in su_dict[base + ' hagent']:
    my_date = list(row)[0]
    print my_date
    row[0] = hUTC.localize(datetime.datetime.combine(my_date, hoyUTC.time()).astimezone(hMexico))
</code>```

Title: Pyodbc update cursor

Body:
Hi, I have a script on Python with SQL and I use fecthall() method to extract the elements I want and all great until there, because I want do modify two columns (datetime.date and datetime.time) to another timezone but I read docs and Its seems its not veare easy...

For now I have the next piece of code fetching the table and then trying to covert firts the date to another timezone, I know... Its a date but if in Spain now is 12am from 5/12/2017 in Mexico is 5pm from 04/12/2017 soooo...

BTW Im using pytz

cursor.execute(cadenaSQL + cadenaSQL_dos)
            su_dict[base+' hagent'] = cursor.fetchall()
            for row in su_dict[base+' hagent']:
                row = list(row)[0]
                print row
                row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico))

For now I got this error with that code:

Traceback (most recent call last):   File "cms_V2_30m.py", line 1535,
  in
      main()   File "cms_V2_30m.py", line 1444, in main
      select_hagent()   File "cms_V2_30m.py", line 211, in select_hagent
      row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time()).astimezone(hMexico)) TypeError: 'datetime.date' object
  is unsubscriptable

EDIT:

I think I´m close, the problem now is with row object, because it is a tuple... so it is inmutble, so I am trying to find a way to change this vale...

The New code:

    for row in su_dict[base + ' hagent']:
        print row[0]
        #list(row)
        #print my_date[0]
        #print datetime.datetime.combine(my_date[0], hoyUTC.time())
        row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico)

The new error:

Traceback (most recent call last):   File "cms_V2_30m.py", line 1538,
  in
      main()   File "cms_V2_30m.py", line 1447, in main
      select_hagent()   File "cms_V2_30m.py", line 214, in select_hagent
      row[0] = hUTC.localize(datetime.datetime.combine(row[0], hoyUTC.time())).astimezone(hMexico) TypeError: 'tuple' object does not
  support item assignment

Body:
It looks like your issue is with overwriting row within the loop. Try this instead?

for row in su_dict[base + ' hagent']:
    my_date = list(row)[0]
    print my_date
    row[0] = hUTC.localize(datetime.datetime.combine(my_date, hoyUTC.time()).astimezone(hMexico))


问:
extract same values in a list of dictionaries if it present
I'm trying ti implement a search engine for documents, so i have my index:

```<code>{'term1': [[document_id1, term_frequency], [document_id2, term_frequency]......]},
{'term2': [[document_id3, term_frequency], [document_id2, term_frequency]......]}
</code>```

and so on...

I should ask for some terms and find all documents that have it(have done this part),
but how can I find ALL the doc_ids that present in my list of dictionaries?

In other words, I need all documents which have ALL the words of the query.
I tried this, but it doesn't work

```<code>    def match(query):
        match_docs=[]
        for doc in find_doc(query):
            for k,v in doc.items():
                for j in v:
                    if j[0] in i:
                       match_docs.append(j)
        return match_docs
</code>```

For example

```<code>    terms=[{'rose':[['3',2],['4',4]]},{'trains':[['3',4],['6',5]]}]
</code>```

I need that it returns me '3'

答:
Make a set of documents for each query then find the union.  If query is a list of search terms ["term1", "term2", etc] and find_doc returns a list of all documents that match any of the search terms, then you'll want to match on one at a time:</p>

```<code>def match(query):
    match_docs=[]
    for q in query:
        # generates a list of document IDs for one term at a time
        match_docs.append([doc[0] for doc in find_doc([q])])
    # get the intersection
    # fixed this line in an edit
    s = set(match_docs[0]).intersection(*match_docs)
    return list(s)
</code>```

Body:
I'm trying ti implement a search engine for documents, so i have my index:

{'term1': [[document_id1, term_frequency], [document_id2, term_frequency]......]},
{'term2': [[document_id3, term_frequency], [document_id2, term_frequency]......]}

and so on...

I should ask for some terms and find all documents that have it(have done this part),
but how can I find ALL the doc_ids that present in my list of dictionaries?

In other words, I need all documents which have ALL the words of the query.
I tried this, but it doesn't work

    def match(query):
        match_docs=[]
        for doc in find_doc(query):
            for k,v in doc.items():
                for j in v:
                    if j[0] in i:
                       match_docs.append(j)
        return match_docs

For example

    terms=[{'rose':[['3',2],['4',4]]},{'trains':[['3',4],['6',5]]}]

I need that it returns me '3'

Body:
Make a set of documents for each query then find the union.  If query is a list of search terms ["term1", "term2", etc] and find_doc returns a list of all documents that match any of the search terms, then you'll want to match on one at a time:

def match(query):
    match_docs=[]
    for q in query:
        # generates a list of document IDs for one term at a time
        match_docs.append([doc[0] for doc in find_doc([q])])
    # get the intersection
    # fixed this line in an edit
    s = set(match_docs[0]).intersection(*match_docs)
    return list(s)


问:
Ribbon shape using for loop in C++
I've been trying all day creating different for loop combinations in c++ and I can't seem to get the right one.

I want my output to look like this:

Ribbon

How can you display this without using arrays?

EDIT: I tried like this but I can't replicate it on the opposite end. This has been so far the closest output I've got.

```<code>for(int i = 0; i < 6; i++)
{
    cout<<"*";

    for(int j = 5; j > i; j--)
    {
        cout<<" ";
    }

    for(int k = 0; k <= i; k++)
    {
        cout<<"*";
    }

    cout<<endl;

}
</code>```

OUTPUT:

Fail ribbon

Title: Ribbon shape using for loop in C++

Body:
I've been trying all day creating different for loop combinations in c++ and I can't seem to get the right one.

I want my output to look like this:

Ribbon

How can you display this without using arrays?

EDIT: I tried like this but I can't replicate it on the opposite end. This has been so far the closest output I've got.

for(int i = 0; i < 6; i++)
{
    cout<<"*";

    for(int j = 5; j > i; j--)
    {
        cout<<" ";
    }

    for(int k = 0; k <= i; k++)
    {
        cout<<"*";
    }

    cout<<endl;

}

OUTPUT:

Fail ribbon

Body:
You have nine lines; let's number them 0 to 8. Line number n contains:

1 + (4 - abs(4 - n)) asterisks (1, 2, 3, 4, 5, 4, 3, 2, 1)

2 * abs (4 - n) spaces (8, 6, 4, 2, 0, 2, 4, 6, 8)

1 + (4 - abs(4 - n)) asterisks (1, 2, 3, 4, 5, 4, 3, 2, 1)


问:
Use R to reduce a dataset to only rows that have matching data in two separate columns
I am trying to reduce a massive data set to only the rows that match in the "FIRSTNAME" column and also the "SSN" column. In order to help clarify I made a small set.

Very small sample

```<code>CUSTNUM FIRSTNAME SSN
 1234     Matt    111
 4321     Mark    222
 5678     Mike    333
 9875     Matt    444
 1092     Matt    111
</code>```

I want it to return

```<code>CUSTNUM FIRSTNAME SSN
 1234     Matt    111
 1092     Matt    111
</code>```

Because they match in both columns.

My dataset has over 2 million rows of customer data in it so I need a way to id possible duplicate records.

答:
There's a handy function for this in base r:  </p>

```<code># suppose you have a dataframe, df, and you want to know which rows
# have duplicate values in both the FIRSTNAME and SSN columns together:
df$dup <- duplicated(df[,c('name','SSN')],fromLast=FALSE)
df$dup <- ifelse(duplicated(df[,c('name','SSN')],fromLast=TRUE),yes=TRUE,no=df$dup)

# return dups
df.answer <- df[which(df$dup),]
</code>```

Body:
I am trying to reduce a massive data set to only the rows that match in the "FIRSTNAME" column and also the "SSN" column. In order to help clarify I made a small set.

Very small sample

CUSTNUM FIRSTNAME SSN
 1234     Matt    111
 4321     Mark    222
 5678     Mike    333
 9875     Matt    444
 1092     Matt    111

I want it to return

CUSTNUM FIRSTNAME SSN
 1234     Matt    111
 1092     Matt    111

Because they match in both columns.

My dataset has over 2 million rows of customer data in it so I need a way to id possible duplicate records.

Body:
There's a handy function for this in base r:

# suppose you have a dataframe, df, and you want to know which rows
# have duplicate values in both the FIRSTNAME and SSN columns together:
df$dup <- duplicated(df[,c('name','SSN')],fromLast=FALSE)
df$dup <- ifelse(duplicated(df[,c('name','SSN')],fromLast=TRUE),yes=TRUE,no=df$dup)

# return dups
df.answer <- df[which(df$dup),]


答:
```<code># Sample data
df <- read.table(text =
   "CUSTNUM FIRSTNAME SSN
    1234     Matt    111
    4321     Mark    222
    5678     Mike    333
    9875     Matt    444
    1092     Matt    111", sep = "", header = T);
</code>```

subsetting based on the pasted columns:

```<code>subset(df, duplicated(paste(FIRSTNAME, SSN)) | duplicated(paste(FIRSTNAME, SSN), fromLast = T))
#1    1234      Matt 111
#5    1092      Matt 111
</code>```

Title: Use R to reduce a dataset to only rows that have matching data in two separate columns

Body:
# Sample data
df <- read.table(text =
   "CUSTNUM FIRSTNAME SSN
    1234     Matt    111
    4321     Mark    222
    5678     Mike    333
    9875     Matt    444
    1092     Matt    111", sep = "", header = T);

subsetting based on the pasted columns:

subset(df, duplicated(paste(FIRSTNAME, SSN)) | duplicated(paste(FIRSTNAME, SSN), fromLast = T))
#1    1234      Matt 111
#5    1092      Matt 111


问:
Android Studio Error: E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable'
I was working on a project and this error suddenly appeared:

```<code>E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
</code>```

I reverted the app to a previous version which was working, and the error persisted. i created a new project, with an empty activity and ran it on my device, the error persisted. how can i fix this?

答:
There is nothing to fix. This is merely mentioning that your code (e.g., a library) has a reference to a class (android.graphics.drawable.RippleDrawable) that is not available on your device. Most likely, your device is running Android 4.4 or older, as this class was introduced in Android 5.0.

This particular message comes up all the time, as our code (e.g., appcompat-v7) often refers to classes that we would like to use on newer devices but can avoid on older devices.

So, just ignore it.

Body:
I was working on a project and this error suddenly appeared:

E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering

I reverted the app to a previous version which was working, and the error persisted. i created a new project, with an empty activity and ran it on my device, the error persisted. how can i fix this?


问:
I'm using a virtualenv. Where should Zipline's extension.py be?
I'm a newbie to zipline and I'm trying to
reproduce this example loosely. It calls for
 modifying a file .zipline/extension.py. Fat luck,
I do not have this file.

Now, I can do (from inside the virtualenv):

```<code>(Mony_games) me@me-ThinkPad-T470p:~/$ ipython
import zipline
zipline.utils.paths.default_extension()
</code>```

But this points to

```<code>'/home/me/.zipline/extension.py'
</code>```

which doesn't exist. Do I have to create it? If so, where: I'm a bit confused because I'm using a virtualenv, so:

```<code>import inspect
inspect.getfile(zipline)
'/home/me/virtualenvs/Mony_games/lib/python3.5/site-packages/zipline/__init__.py'
</code>```

答:
it's okay. virtualenv or not, this file should be where

```<code>import zipline
zipline.utils.paths.default_extension()
</code>```

points to, which in my case is:

```<code>'/home/me/.zipline/extension.py'
</code>```

Body:
I'm a newbie to zipline and I'm trying to
reproduce this example loosely. It calls for
 modifying a file .zipline/extension.py. Fat luck,
I do not have this file.

Now, I can do (from inside the virtualenv):

(Mony_games) me@me-ThinkPad-T470p:~/$ ipython
import zipline
zipline.utils.paths.default_extension()

But this points to

'/home/me/.zipline/extension.py'

which doesn't exist. Do I have to create it? If so, where: I'm a bit confused because I'm using a virtualenv, so:

import inspect
inspect.getfile(zipline)
'/home/me/virtualenvs/Mony_games/lib/python3.5/site-packages/zipline/__init__.py'

Body:
it's okay. virtualenv or not, this file should be where

import zipline
zipline.utils.paths.default_extension()

points to, which in my case is:

'/home/me/.zipline/extension.py'


问:
Cannot convert 'QJsonObject' to 'int' in return
So I have:

QJsonArray nodeCollection;

nodeCollection.push_back(ListElements(program, "title", "lang"));
```

<p>And my <code>ListElements</code> method declares <code>QJsonObject</code>, fills it with things that I need, and should return the object so that it can be pushed to <code>nodeCollection</code> array variable:</p>

<pre class="lang-cpp prettyprint-override"><code>ListElements (QDomElement root, QString tagname, QString attribute)
{

         auto nodeData = QJsonObject(
            {
            qMakePair(QString(itemElement.tagName()), QJsonValue(itemElement.text())),
            qMakePair(QString("lang"),QJsonValue(itemElement.attribute("lang"))),
            });

            return nodeData;  // <-- error
        }
    }
}
</code>```

The error that I get is:

error: cannot convert 'QJsonObject' to 'int' in return

I'm obviously new to C++ and I've googled this issue with some success, but no concrete examples how to address this issue.

What am I doing wrong? How can I tell the method it should return QJsonObject instead of int?

答:
If you write a function like this:

```<code>MyFunc(double, float) {
   ...
}
</code>```

Then it is assumed to have a return type of int because no return type has been specified. If you want it to return something else you need to specify the return type:

```<code>QJsonObject MyFunc(double, float) {
   ...
}
</code>```

Body:
So I have:

QJsonArray nodeCollection;

nodeCollection.push_back(ListElements(program, "title", "lang"));

And my ListElements method declares QJsonObject, fills it with things that I need, and should return the object so that it can be pushed to nodeCollection array variable:

ListElements (QDomElement root, QString tagname, QString attribute)
{

         auto nodeData = QJsonObject(
            {
            qMakePair(QString(itemElement.tagName()), QJsonValue(itemElement.text())),
            qMakePair(QString("lang"),QJsonValue(itemElement.attribute("lang"))),
            });

            return nodeData;  // <-- error
        }
    }
}

The error that I get is:

error: cannot convert 'QJsonObject' to 'int' in return

I'm obviously new to C++ and I've googled this issue with some success, but no concrete examples how to address this issue.

What am I doing wrong? How can I tell the method it should return QJsonObject instead of int?

Body:
If you write a function like this:

MyFunc(double, float) {
   ...
}

Then it is assumed to have a return type of int because no return type has been specified. If you want it to return something else you need to specify the return type:

QJsonObject MyFunc(double, float) {
   ...
}


问:
Apache-Beam add sequence number to a PCollection

I'm trying to build an ETL to load a Dimension table. I'm ussign Apache Bea, with Python and DataFlow, and BigQuery.

I need to assign a sequence number to each element of a pcollection in order to load its into BigQuery, but I cant find any way to do this.

I think I need DataFlow to make the previous aggregation and joins to get my final pcollection to add the sequence number, but in this moment I need to stop parallel processing and cast my pcollection to a list (as in Spark when you use .collect()) and then make an easy loop to assign the sequence number. is it right?

This is the pipeline I've coded:

```<code>p | ReadFromAvro(known_args.input) | beam.Map(adapt) | beam.GroupByKey() | beam.Map(adaptGroupBy)
</code>```

I've read there is no way to get a list from pcollection:
How to get a list of elements out of a PCollection in Google Dataflow and use it in the pipeline to loop Write Transforms?

How can I achieve it? Any help?

答:
If what you want is to get a list with each of the elements in a PCollection, you can use a side input. Keep in mind that this will remove all parallelism from your results, and your pipeline may become slow.

If you still want to do this, then:

```<code>side_input_coll = beam.pvalue.AsIterable(my_collection)

(p
 | beam.Create([0])
 | beam.FlatMap(lambda _, my_seq: [(elem, i) for i, elem in enumerate(my_seq)],
               my_seq=side_input_coll))
</code>```

But don't forget that to preserve parallelism, it may be best to simply generate a random ID. Remember that PCollections are intrinsically unordered.

To learn more about side inputs, see the Beam Programming Guide on Side Inputs

Body:
I'm trying to build an ETL to load a Dimension table. I'm ussign Apache Bea, with Python and DataFlow, and BigQuery.

I need to assign a sequence number to each element of a pcollection in order to load its into BigQuery, but I cant find any way to do this.

I think I need DataFlow to make the previous aggregation and joins to get my final pcollection to add the sequence number, but in this moment I need to stop parallel processing and cast my pcollection to a list (as in Spark when you use .collect()) and then make an easy loop to assign the sequence number. is it right?

This is the pipeline I've coded:

p | ReadFromAvro(known_args.input) | beam.Map(adapt) | beam.GroupByKey() | beam.Map(adaptGroupBy)

I've read there is no way to get a list from pcollection:
How to get a list of elements out of a PCollection in Google Dataflow and use it in the pipeline to loop Write Transforms?

How can I achieve it? Any help?

Body:
If what you want is to get a list with each of the elements in a PCollection, you can use a side input. Keep in mind that this will remove all parallelism from your results, and your pipeline may become slow.

If you still want to do this, then:

side_input_coll = beam.pvalue.AsIterable(my_collection)

(p
 | beam.Create([0])
 | beam.FlatMap(lambda _, my_seq: [(elem, i) for i, elem in enumerate(my_seq)],
               my_seq=side_input_coll))

But don't forget that to preserve parallelism, it may be best to simply generate a random ID. Remember that PCollections are intrinsically unordered.

To learn more about side inputs, see the Beam Programming Guide on Side Inputs


问:
Coding Client socket on Flash AS3.0?
Now I have server code on C++ program. But I don't know how to coding client socket on Flash AS3.0.

Can you give me some example code ??

答:
you need the Socket class if you're going to send binary data.

there's also XMLSocket for xml

ContentLicense: CC BY-SA 2.5

Title: Coding Client socket on Flash AS3.0?


答:
You have to add the return type to the beginning of the function prototype:

```<code>QJsonObject ListElements (QDomElement root, QString tagname, QString attribute)
</code>```

If you don't specify a return type, the default assumed return type is int, that's why you got this error.

Title: Cannot convert 'QJsonObject' to 'int' in return

Body:
You have to add the return type to the beginning of the function prototype:

QJsonObject ListElements (QDomElement root, QString tagname, QString attribute)

If you don't specify a return type, the default assumed return type is int, that's why you got this error.


问:
Given the user's identity id, how to get the user's details from cognito user pool?

The user uploads an image to his/her subfolder on S3. The only way this can be enforced with policy is by using identity id:

```<code>arn:aws:s3:::thebucket/${cognito-identity.amazonaws.com:sub}/avatar.jpg
</code>```

A lambda that transforms that image, is triggered, and saves the transformations to a different S3.

But now, with the identity id on disposal, that lambda needs to update the user's db record with the references to the avatar transformations. This is where the issue is evident, I only have the identity id, and from it, I need to get to the cognito user's details so i can look for the user in my users table which has user:sub as identifier.

How do I correlate those two? Is there an api in cognito that would give me the sub based on the identity id?

Is there maybe a more reasonable way?

答:
I have not been able to find a way to do this. Also, you should only get a Cognito Identity Id passed to Lambda if you are using the Mobile SDK, which you can access using 'context.identity.cognitoIdentityId'. Although one user user at least seems to be defying the AWS documention set by getting it to work with Javascript.

It looks like you are using the sub in your s3 object key, so have you thought about taking it form there? You get loads of information passed about the s3 object in your event, including the key, which in your case includes your sub.

Your S3 event should look something like this

```<code>{
   "Records":[
      {
         "eventVersion":"2.0",
         "eventSource":"aws:s3",
         "awsRegion":"us-east-1",
         "eventTime":"1970-01-01T00:00:00.000Z",
         "eventName":"ObjectCreated:Put",
         "userIdentity":{
            "principalId":"AIDAJDPLRKLG7UEXAMPLE"
         },
         "requestParameters":{
            "sourceIPAddress":"127.0.0.1"
         },
         "responseElements":{
            "x-amz-request-id":"C3D13FE58DE4C810",
            "x-amz-id-2":"FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD"
         },
         "s3":{
            "s3SchemaVersion":"1.0",
            "configurationId":"testConfigRule",
            "bucket":{
               "name":"mybucket",
               "ownerIdentity":{
                  "principalId":"A3NL1KOZZKExample"
               },
               "arn":"arn:aws:s3:::mybucket"
            },
            "object":{
               "key":"HappyFace.jpg",
               "size":1024,
               "eTag":"d41d8cd98f00b204e9800998ecf8427e",
               "versionId":"096fKKXTRTtl3on89fVO.nfljtsv6qko",
               "sequencer":"0055AED6DCD90281E5"
            }
         }
      }
   ]
}
</code>```

You could parse the S3 object key, which should have your sub in it.

EDIT: After sharing some comments I think your situation is this:

You have a user who has logged into using an external identity (e.g. google)

This user also has a user pool identity

The identities have not been linked using admin-link-provider-for-user

You want to lookup the user pool identity from the external identity after some action

Im assuming the thing that links these accounts is an email address? One option is to link the accounts when they signup, using a cognito pre-signup trigger and the admin-link-provider-for-user function.

The other thing you could do is take the current (externally provided) identity email, then do ListUsers based on that email. You will get a list of UserType back, then choose the one where the provider is Cognito, which should give you the sub you want.

Is that the sort of thing your after?

EDIT: Another idea we discussed in the comments was calling your Lambda function directly from your application, rather than relying on the S3 event. The benefit of this approach is that you could include any information you like in the call, like the correct user sub.

Body:
The user uploads an image to his/her subfolder on S3. The only way this can be enforced with policy is by using identity id:

arn:aws:s3:::thebucket/${cognito-identity.amazonaws.com:sub}/avatar.jpg

A lambda that transforms that image, is triggered, and saves the transformations to a different S3.

But now, with the identity id on disposal, that lambda needs to update the user's db record with the references to the avatar transformations. This is where the issue is evident, I only have the identity id, and from it, I need to get to the cognito user's details so i can look for the user in my users table which has user:sub as identifier.

How do I correlate those two? Is there an api in cognito that would give me the sub based on the identity id?

Is there maybe a more reasonable way?

Body:
I have not been able to find a way to do this. Also, you should only get a Cognito Identity Id passed to Lambda if you are using the Mobile SDK, which you can access using 'context.identity.cognitoIdentityId'. Although one user user at least seems to be defying the AWS documention set by getting it to work with Javascript.

It looks like you are using the sub in your s3 object key, so have you thought about taking it form there? You get loads of information passed about the s3 object in your event, including the key, which in your case includes your sub.

Your S3 event should look something like this

{
   "Records":[
      {
         "eventVersion":"2.0",
         "eventSource":"aws:s3",
         "awsRegion":"us-east-1",
         "eventTime":"1970-01-01T00:00:00.000Z",
         "eventName":"ObjectCreated:Put",
         "userIdentity":{
            "principalId":"AIDAJDPLRKLG7UEXAMPLE"
         },
         "requestParameters":{
            "sourceIPAddress":"127.0.0.1"
         },
         "responseElements":{
            "x-amz-request-id":"C3D13FE58DE4C810",
            "x-amz-id-2":"FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD"
         },
         "s3":{
            "s3SchemaVersion":"1.0",
            "configurationId":"testConfigRule",
            "bucket":{
               "name":"mybucket",
               "ownerIdentity":{
                  "principalId":"A3NL1KOZZKExample"
               },
               "arn":"arn:aws:s3:::mybucket"
            },
            "object":{
               "key":"HappyFace.jpg",
               "size":1024,
               "eTag":"d41d8cd98f00b204e9800998ecf8427e",
               "versionId":"096fKKXTRTtl3on89fVO.nfljtsv6qko",
               "sequencer":"0055AED6DCD90281E5"
            }
         }
      }
   ]
}

You could parse the S3 object key, which should have your sub in it.

EDIT: After sharing some comments I think your situation is this:

You have a user who has logged into using an external identity (e.g. google)

This user also has a user pool identity

The identities have not been linked using admin-link-provider-for-user

You want to lookup the user pool identity from the external identity after some action

Im assuming the thing that links these accounts is an email address? One option is to link the accounts when they signup, using a cognito pre-signup trigger and the admin-link-provider-for-user function.

The other thing you could do is take the current (externally provided) identity email, then do ListUsers based on that email. You will get a list of UserType back, then choose the one where the provider is Cognito, which should give you the sub you want.

Is that the sort of thing your after?

EDIT: Another idea we discussed in the comments was calling your Lambda function directly from your application, rather than relying on the S3 event. The benefit of this approach is that you could include any information you like in the call, like the correct user sub.


问:
Android Application Keyboard Enter/Send Key
While using messaging services built inside different applications, I noticed that the Enter key on some applications is replaced by a send key. As an example, the attached 5 screenshots are from Facebook Messenger, Instagram, Snapchat, Twitter and my own application.

As you can see, Snapchat and Instagram have the bottom-right key of the keyboard set as send with the special icon. Rest of them, including mine, do not have that. I tried to look around but could not find any documentation or suggestions on how to achieve this.

Where do I even start to achieve something like this?

Footnote 1: I am using a Google Pixel 2 XL with Google Keyboard, but I have seen similar functionality on other devices.

Footnote 2: I have seen a question on overwriting the enter key's input to call a function but am looking for more traditional/sophisticated method (preferably with custom send icon).

Footnote 3: Order of images: My application, Snapchat, Messenger, Twitter, Instagram.

Footnote 4: I am not specifically looking to make an entire custom keyboard. I want to keep rest of the multimedia functions brought by Google Keyboard.

答: Use android:imeOptions="actionSend" on your EditText widget.


问:
Best way to automatically detect private variables in cached .net classes?
Using private variables in cached .net classes is a recipe for strange and often hard to debug problems.

See for instance: http://code-smart.org.uk/information/beware-asp-net-mvc-actionfilterattributes-are-cached-between-requests/

This can leed to session mixups/swapping! Usually these problems are blamed on not setting the output cache correctly.

Can (should?) Resharper detect these problems? Or is there another way?

答:
It sounds like something nDepend might be able to do, it has a feature to be pretty much write linq to analyse code.

Here's some details about CLinq: https://www.ndepend.com/default-rules/webframe.html

It can be also used as part of your gated build pipeline:
https://www.ndepend.com/docs/ndepend-console


问:
In Leaflet, how to make a style the default style from now on
I have geoJson map regions rendered on a map with an initial opacity.  I have a slider to change that opacity on the fly.

Here is the bit where I set the opacity on the fly (typescript), which I perform on the input change event within my custom leaflet control:

```<code>this.layers.forEach((r: L.GeoJSON<any>) => {
      r.eachLayer((layer: any) => {
             layer.setStyle({ fillOpacity: vm.mapOptions.heatmapOpacity });
      });
});
setTimeout(() => this.map.invalidateSize());
</code>```

I also have the ability to hover over the regions, in which case I lower the opacity and put a border on the active region when they hover.

When they leave the region, it currently uses resetStyles on that region to reset it back to the previous style. I set this up in the options onFeature callback. The region is highlighted in the mouseover event, and reset in the mouseout event, as seen below.

```<code>options = {
            style: { stroke: false,
                     fillColor: regionColor,
                     fillOpacity: mapOptions.heatmapOpacity },
            onEachFeature: (feature, layer) => {
                layer.on({
                    mouseover: (e)=> {
                         const lr = e.target;
                         lr.setStyle({
                            weight: 5,
                            color: "#666",
                            dashArray: "",
                            fillOpacity: 0.7,
                           stroke: true
                         });
                        if (!L.Browser.ie && !L.Browser.opera12 && !L.Browser.edge) {
                           lr.bringToFront();
                        }
                    },
                    mouseout: (e) => {
                       prop.featureGeoJson.resetStyle(e.target);
                    }
                });
            }
        };
</code>```

The problem is, if I have used setStyle to set the opacity to a different value, then I go into a region, then I leave the region again, calling resetStyle resets the style back to the original default style, before the change to the opacity was made.

Is it possible to set the default style on the layer, so that calling resetStyle will set the styles to my value with the new opacity, and not to the original opacity set when the region was created? How would I do that?

答:
Use L.Util.setOptions

so instead of

```<code>layer.setStyle({ fillOpacity: vm.mapOptions.heatmapOpacity });
</code>```

use

```<code>L.Util.setOptions(layer, { style: { fillOpacity: vm.mapOptions.heatmapOpacity } });
</code>```

Body:
I have geoJson map regions rendered on a map with an initial opacity.  I have a slider to change that opacity on the fly.

Here is the bit where I set the opacity on the fly (typescript), which I perform on the input change event within my custom leaflet control:

this.layers.forEach((r: L.GeoJSON<any>) => {
      r.eachLayer((layer: any) => {
             layer.setStyle({ fillOpacity: vm.mapOptions.heatmapOpacity });
      });
});
setTimeout(() => this.map.invalidateSize());

I also have the ability to hover over the regions, in which case I lower the opacity and put a border on the active region when they hover.

When they leave the region, it currently uses resetStyles on that region to reset it back to the previous style. I set this up in the options onFeature callback. The region is highlighted in the mouseover event, and reset in the mouseout event, as seen below.

options = {
            style: { stroke: false,
                     fillColor: regionColor,
                     fillOpacity: mapOptions.heatmapOpacity },
            onEachFeature: (feature, layer) => {
                layer.on({
                    mouseover: (e)=> {
                         const lr = e.target;
                         lr.setStyle({
                            weight: 5,
                            color: "#666",
                            dashArray: "",
                            fillOpacity: 0.7,
                           stroke: true
                         });
                        if (!L.Browser.ie && !L.Browser.opera12 && !L.Browser.edge) {
                           lr.bringToFront();
                        }
                    },
                    mouseout: (e) => {
                       prop.featureGeoJson.resetStyle(e.target);
                    }
                });
            }
        };

The problem is, if I have used setStyle to set the opacity to a different value, then I go into a region, then I leave the region again, calling resetStyle resets the style back to the original default style, before the change to the opacity was made.

Is it possible to set the default style on the layer, so that calling resetStyle will set the styles to my value with the new opacity, and not to the original opacity set when the region was created? How would I do that?

Body:
Use L.Util.setOptions

so instead of

layer.setStyle({ fillOpacity: vm.mapOptions.heatmapOpacity });

use

L.Util.setOptions(layer, { style: { fillOpacity: vm.mapOptions.heatmapOpacity } });


问:
Create bear like div-containers
I am trying to create a website where the main design is inspired from the following image

I am trying to create three div containers resembling the three bear shapes in the image above. Inside these div containers I am placing my content for the site.

My main problem is adding the head and bottom of the bears, I do not want nor need any content in these parts.

     content = document.getElementById("content");
content.style.paddingTop = content.offsetWidth/2 + "px";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #00ADEF;
    font-family: arial, sans-serif;
}

#content {
    width: 60%;
    margin: auto;
    text-align: left;
    background-color: #F7F3E9;
}</code>```

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
        voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
        voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
        voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
        voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.

```

My main problem is that I do not know how to append a half circle to the top of a div. Any suggestions?

答:
You may try using pseudo element and some background like this :

body {
margin:0;
background:#f2f2f2;
}

.panda {
  margin: 100px 20px;
  width: 150px;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
  display:inline-block;
  vertical-align:top;
}

.panda:before {
  content: "";
  position: absolute;
  height: 50px;
  width: 20px;
  top: -50px;
  left: 10px;
  border-radius: 10px;
  transform: rotate(-40deg);
  z-index: -100;
}

.panda:after {
  content: "";
  position: absolute;
  height: 50px;
  width: 20px;
  top: -50px;
  right: 10px;
  border-radius: 10px;
  transform: rotate(40deg);
  z-index: -100;
}

.content:before,
.content:after {
  content: "";
  width: 150px;
  height: 100px;
  position: absolute;
  bottom: -50px;
  right: 0;
  border-radius: 50%;
  z-index: -99;
}

.content:after {
  top: -50px;
  bottom: auto;
}

.eyes:before {
    content: "";
    position: absolute;
    height: 20px;
    width: 25px;
    top: -15px;
    left: 20px;
    background: black;
    border-radius: 50%;
    transform: rotate(-30deg);
}

.eyes:after {
    content: "";
    position: absolute;
    height: 20px;
    width: 25px;
    top: -15px;
    right: 20px;
    background: black;
    border-radius: 50%;
    transform: rotate(30deg);
}

.pink,
.pink:before,
.pink:after,
.pink .content:before,
.pink .content:after {
  background: pink;
}
.blue,
.blue:before,
.blue:after,
.blue .content:before,
.blue .content:after {
  background: blue;
  color:white;
}

.black {
  background:linear-gradient(to bottom,white 20%,black 0%, black 50%, white 45%);
  color:red;
}
.black .content:after {
  background: white;
}
.black:before,
.black:after,
.black .content:before{
  background: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="panda pink">
  <div class="content">
    lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum
  </div>
</div>
<div class="panda blue">
  <div class="content">
    lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum  ipsum lorem ipsum  ipsum lorem ipsum
  </div>
</div>

<div class="panda black">
  <span class="eyes"></span>
  <div class="content">
    lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
  </div>
</div></code>```

Title: Create bear like div-containers

Body:
I am trying to create a website where the main design is inspired from the following image

I am trying to create three div containers resembling the three bear shapes in the image above. Inside these div containers I am placing my content for the site.

My main problem is adding the head and bottom of the bears, I do not want nor need any content in these parts.

     content = document.getElementById("content");
content.style.paddingTop = content.offsetWidth/2 + "px";

* {
    margin: 0;
    padding: 0;
}

body {
    background-color: #00ADEF;
    font-family: arial, sans-serif;
}

#content {
    width: 60%;
    margin: auto;
    text-align: left;
    background-color: #F7F3E9;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
        voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
        voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
        voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
        eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
        minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat. Duis aute irure dolor in reprehenderit in
        voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
        mollit anim id est laborum.

My main problem is that I do not know how to append a half circle to the top of a div. Any suggestions?

Body:
You may try using pseudo element and some background like this :

body {
margin:0;
background:#f2f2f2;
}

.panda {
  margin: 100px 20px;
  width: 150px;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
  display:inline-block;
  vertical-align:top;
}

.panda:before {
  content: "";
  position: absolute;
  height: 50px;
  width: 20px;
  top: -50px;
  left: 10px;
  border-radius: 10px;
  transform: rotate(-40deg);
  z-index: -100;
}

.panda:after {
  content: "";
  position: absolute;
  height: 50px;
  width: 20px;
  top: -50px;
  right: 10px;
  border-radius: 10px;
  transform: rotate(40deg);
  z-index: -100;
}

.content:before,
.content:after {
  content: "";
  width: 150px;
  height: 100px;
  position: absolute;
  bottom: -50px;
  right: 0;
  border-radius: 50%;
  z-index: -99;
}

.content:after {
  top: -50px;
  bottom: auto;
}

.eyes:before {
    content: "";
    position: absolute;
    height: 20px;
    width: 25px;
    top: -15px;
    left: 20px;
    background: black;
    border-radius: 50%;
    transform: rotate(-30deg);
}

.eyes:after {
    content: "";
    position: absolute;
    height: 20px;
    width: 25px;
    top: -15px;
    right: 20px;
    background: black;
    border-radius: 50%;
    transform: rotate(30deg);
}

.pink,
.pink:before,
.pink:after,
.pink .content:before,
.pink .content:after {
  background: pink;
}
.blue,
.blue:before,
.blue:after,
.blue .content:before,
.blue .content:after {
  background: blue;
  color:white;
}

.black {
  background:linear-gradient(to bottom,white 20%,black 0%, black 50%, white 45%);
  color:red;
}
.black .content:after {
  background: white;
}
.black:before,
.black:after,
.black .content:before{
  background: black;
}

<div class="panda pink">
  <div class="content">
    lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum
  </div>
</div>
<div class="panda blue">
  <div class="content">
    lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsumlorem ipsum lorem ipsum lorem ipsum lorem ipsum  ipsum lorem ipsum  ipsum lorem ipsum
  </div>
</div>

<div class="panda black">
  <span class="eyes"></span>
  <div class="content">
    lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
  </div>
</div>


问:
How to make SeekBar interface with code?
I've created a few SeekBars in a fragment and an OnSeekBarChangeListener in my java file, but there seems to be an unexplained disconnect between the xml layout and the java file.

java class

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_preferences, container, false);
    final SeekBar s1 = (SeekBar) root.findViewById(R.id.s1Bar);
    final TextView spicinessText = (TextView) root.findViewById(R.id.spicinessTxt);
    s1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            Toast.makeText(getContext(), String.valueOf(i), Toast.LENGTH_SHORT).show();
            spicinessText.setText("Spiciness " + String.valueOf(i));
        }

        @Override

        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    return inflater.inflate(R.layout.fragment_preferences, container, false);
}
</code>```

xml layout

```<code><FrameLayout>

<!-- TODO: Update blank fragment layout -->

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Spiciness"
    android:id="@+id/spicinessTxt"/>

<SeekBar
    android:id="@+id/s1Bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Sourness"/>

<SeekBar
    android:id="@+id/seekBar4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Sweet"
    android:id="@+id/sweet"/>

<SeekBar
    android:id="@+id/seekBar5"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Salty"/>

<SeekBar
    android:id="@+id/seekBar6"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text=""/>
</code>```

I launched the app on an external device and the actual layout simply doesn't communicate with the java code, even though I'm pretty sure I've done it all correctly. If anyone can see whatever critical error I've made here it would be much appreciated.

答:
Here is solution for your query:

```<code> public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
 {
      // Inflate the layout for this fragment
      View root = inflater.inflate(R.layout.fragment_preferences, container, false);
      final SeekBar s1 = (SeekBar) root.findViewById(R.id.s1Bar);
      final TextView spicinessText = (TextView) root.findViewById(R.id.spicinessTxt);
      s1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
      {
           @Override
           public void onProgressChanged(SeekBar seekBar, int i, boolean b)
           {
                 Toast.makeText(getContext(), String.valueOf(i), Toast.LENGTH_SHORT).show();
                spicinessText.setText("Spiciness " + String.valueOf(i));
           }
           @Override
           public void onStartTrackingTouch(SeekBar seekBar)
           { }
           @Override
           public void onStopTrackingTouch(SeekBar seekBar)
          { }
      });
     return root;
  }
</code>```

Thanks and happy coding.

Body:
I've created a few SeekBars in a fragment and an OnSeekBarChangeListener in my java file, but there seems to be an unexplained disconnect between the xml layout and the java file.

java class

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_preferences, container, false);
    final SeekBar s1 = (SeekBar) root.findViewById(R.id.s1Bar);
    final TextView spicinessText = (TextView) root.findViewById(R.id.spicinessTxt);
    s1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            Toast.makeText(getContext(), String.valueOf(i), Toast.LENGTH_SHORT).show();
            spicinessText.setText("Spiciness " + String.valueOf(i));
        }

        @Override

        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    return inflater.inflate(R.layout.fragment_preferences, container, false);
}

xml layout

<FrameLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Spiciness"
    android:id="@+id/spicinessTxt"/>

<SeekBar
    android:id="@+id/s1Bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Sourness"/>

<SeekBar
    android:id="@+id/seekBar4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Sweet"
    android:id="@+id/sweet"/>

<SeekBar
    android:id="@+id/seekBar5"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Salty"/>

<SeekBar
    android:id="@+id/seekBar6"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text=""/>

I launched the app on an external device and the actual layout simply doesn't communicate with the java code, even though I'm pretty sure I've done it all correctly. If anyone can see whatever critical error I've made here it would be much appreciated.

Body:
Here is solution for your query:

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
 {
      // Inflate the layout for this fragment
      View root = inflater.inflate(R.layout.fragment_preferences, container, false);
      final SeekBar s1 = (SeekBar) root.findViewById(R.id.s1Bar);
      final TextView spicinessText = (TextView) root.findViewById(R.id.spicinessTxt);
      s1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
      {
           @Override
           public void onProgressChanged(SeekBar seekBar, int i, boolean b)
           {
                 Toast.makeText(getContext(), String.valueOf(i), Toast.LENGTH_SHORT).show();
                spicinessText.setText("Spiciness " + String.valueOf(i));
           }
           @Override
           public void onStartTrackingTouch(SeekBar seekBar)
           { }
           @Override
           public void onStopTrackingTouch(SeekBar seekBar)
          { }
      });
     return root;
  }

Thanks and happy coding.


问:
Python, Pandas, inverted expanding window
Lets consider the following Series:

```<code>s=pd.Series(data=[100, 110, 120, 150, 110, 90, 80, 70, 90, 95])
</code>```

I iterate over each item and perform the following operation:

```<code>for i in range(len(s)):
    m=max(s[i]-s[i:])
</code>```

Basically comparing each item with all items that follow, and retrieving the max.

I can do that with:

```<code>r=[]
for i in range(len(s)):
    m=max(s[i]-s[i:])
    r.append(m)

result=pd.Series(r)
</code>```

But I had the feeling that this would be something that a rolling window could do? I am trying to make my code a bit cleaner and was just starting reading and exploring about the rolling function, but i cannot yet but my finger on it. This idea seems like a inverted expanding function (i.e. it takes less and less data as it goes down the data)?

If someone has ideas about how to reformat the code using rolling / expanding windows, please let me know.

答:
You can use numpy.minimum.accumulate on s reversed and then subtract it from s:

```<code>import numpy as np
s - np.minimum.accumulate(s[::-1])[::-1]

#0    30
#1    40
#2    50
#3    80
#4    40
#5    20
#6    10
#7     0
#8     0
#9     0
#dtype: int64
</code>```

Body:
Lets consider the following Series:

s=pd.Series(data=[100, 110, 120, 150, 110, 90, 80, 70, 90, 95])

I iterate over each item and perform the following operation:

for i in range(len(s)):
    m=max(s[i]-s[i:])

Basically comparing each item with all items that follow, and retrieving the max.

I can do that with:

r=[]
for i in range(len(s)):
    m=max(s[i]-s[i:])
    r.append(m)

result=pd.Series(r)

But I had the feeling that this would be something that a rolling window could do? I am trying to make my code a bit cleaner and was just starting reading and exploring about the rolling function, but i cannot yet but my finger on it. This idea seems like a inverted expanding function (i.e. it takes less and less data as it goes down the data)?

If someone has ideas about how to reformat the code using rolling / expanding windows, please let me know.

Body:
You can use numpy.minimum.accumulate on s reversed and then subtract it from s:

import numpy as np
s - np.minimum.accumulate(s[::-1])[::-1]

#0    30
#1    40
#2    50
#3    80
#4    40
#5    20
#6    10
#7     0
#8     0
#9     0
#dtype: int64


问:
SQL query to return top line manager by area

We are trying to populate our User table with the top manager of the Site (consider its like a department or cost centre) to help define an Owner of the Site.

EG:

in the example above, we would want to return employee "1002" to update "Owner" within all records where site = '123'

the difficulty we have is there are 90,000 employee records with a giant number of management structures within the Site.  It could be 1 level of management, it could be 5...

I am a novice when it comes to SQL, and I am baffled.  I'm not even sure it is possible.

Any suggestions?

答:
Here's some test data I used to create my answer (I slightly renamed a few columns for ease of reading, added another record to demonstrate functionality):

```<code>CREATE TABLE #test (EmployeeID INT, SiteID INT, LineManagerID INT, OwnerID INT)
INSERT INTO #test
    (
        EmployeeID
        ,SiteID
        ,LineManagerID
        ,OwnerID
    )
VALUES
    (
        1234  -- EmployeeID
        ,123 -- SiteID
        ,2345 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        2345  -- EmployeeID
        ,123 -- SiteID
        ,3456 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        3456  -- EmployeeID
        ,123 -- SiteID
        ,5678 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        5678  -- EmployeeID
        ,123 -- SiteID
        ,1002 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        1002  -- EmployeeID
        ,567 -- SiteID
        ,1103 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        1103  -- EmployeeID
        ,568 -- SiteID
        ,6669 -- LineManagerID
        ,NULL -- OwnerID
    )
</code>```

Then your UPDATE will use a recursive CTE to figure out the top LineManagerID for each SiteID.

```<code>;WITH UserCTE
     AS (SELECT EmployeeID,
                SiteID,
                LineManagerID,
                0 AS [Level],
                NULL AS mgrEmpID
         FROM   #test

         UNION ALL

         SELECT usr.EmployeeID,
                usr.SiteID,
                usr.LineManagerID,
                mgr.[Level] + 1,
                mgr.EmployeeID AS mgrEmpID
         FROM   #test AS usr
         INNER JOIN UserCTE AS mgr ON usr.LineManagerID = mgr.EmployeeID AND usr.SiteID <> mgr.SiteID
         WHERE  usr.LineManagerID IS NOT NULL
         )
UPDATE t
SET t.OwnerID = u.mgrEmpID
FROM #test t
LEFT JOIN UserCTE u ON t.SiteID = u.SiteID AND u.[Level] = 1
</code>```

And here's what the table looks like after the UPDATE:

```<code>EmployeeID  SiteID  LineManagerID   OwnerID
1234        123     2345            1002
2345        123     3456            1002
3456        123     5678            1002
5678        123     1002            1002
1002        567     1103            1103
1103        568     6669            NULL
</code>```

Body:
Here's some test data I used to create my answer (I slightly renamed a few columns for ease of reading, added another record to demonstrate functionality):

CREATE TABLE #test (EmployeeID INT, SiteID INT, LineManagerID INT, OwnerID INT)
INSERT INTO #test
    (
        EmployeeID
        ,SiteID
        ,LineManagerID
        ,OwnerID
    )
VALUES
    (
        1234  -- EmployeeID
        ,123 -- SiteID
        ,2345 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        2345  -- EmployeeID
        ,123 -- SiteID
        ,3456 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        3456  -- EmployeeID
        ,123 -- SiteID
        ,5678 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        5678  -- EmployeeID
        ,123 -- SiteID
        ,1002 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        1002  -- EmployeeID
        ,567 -- SiteID
        ,1103 -- LineManagerID
        ,NULL -- OwnerID
    ),
    (
        1103  -- EmployeeID
        ,568 -- SiteID
        ,6669 -- LineManagerID
        ,NULL -- OwnerID
    )

Then your UPDATE will use a recursive CTE to figure out the top LineManagerID for each SiteID.

;WITH UserCTE
     AS (SELECT EmployeeID,
                SiteID,
                LineManagerID,
                0 AS [Level],
                NULL AS mgrEmpID
         FROM   #test

         UNION ALL

         SELECT usr.EmployeeID,
                usr.SiteID,
                usr.LineManagerID,
                mgr.[Level] + 1,
                mgr.EmployeeID AS mgrEmpID
         FROM   #test AS usr
         INNER JOIN UserCTE AS mgr ON usr.LineManagerID = mgr.EmployeeID AND usr.SiteID <> mgr.SiteID
         WHERE  usr.LineManagerID IS NOT NULL
         )
UPDATE t
SET t.OwnerID = u.mgrEmpID
FROM #test t
LEFT JOIN UserCTE u ON t.SiteID = u.SiteID AND u.[Level] = 1

And here's what the table looks like after the UPDATE:

EmployeeID  SiteID  LineManagerID   OwnerID
1234        123     2345            1002
2345        123     3456            1002
3456        123     5678            1002
5678        123     1002            1002
1002        567     1103            1103
1103        568     6669            NULL


问:
Always get previous state in React app
In relation to my previous question, I'm doing this to store the right state:

```<code>if (value === 'checkpoint')
{
  if (checked1)
  {
    this.setState({checked1 : false})
    localStorage.setObject('checked1', false)
  }
  else
  {
    this.setState({checked1 : true})
    localStorage.setObject('checked1', true)
  }
}
</code>```

Now I have multiple checkboxes (let's say I have four). One for ALL checkboxes, and the other 3 for categories. I want my app to detect when the three category checkboxes are checked, and check the ALL checkbox automatically. When any of the category checkboxes are unchecked, the ALL checkbox will uncheck itself.

I tried this code:

```<code>  if (checked1 && checked2 && checked3) {
    this.setState({checkedAll: true})
  } else {
    this.setState({checkedAll: false})
  }
</code>```

But the other 3 checkbox (checked1, checked2, checked3) will always get a previous state.

How do I get the right state so that my checkedAll functions correctly?

答:
You should rather avoid using setState() in componentDidUpdate() as it sometimes leads to bugs in your code and is considered not a good practice (e.g. https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md so if you use airbnb rules to configure your eslint you'll also run into some linting warnings).

Can't you make all four checkboxes controlled inputs like so:

```<code>      <input
        type="checkbox"
        id="ch1"
        value="1"
        checked={this.state.ch1}
        onChange={this.onCheckboxChange}
      /> Ch1

      <input
        type="checkbox"
        id="ch2"
        value="1"
        checked={this.state.ch2}
        onChange={this.onCheckboxChange}
      /> Ch2

      <input
        type="checkbox"
        id="ch3"
        value="1"
        checked={this.state.ch3}
        onChange={this.onCheckboxChange}
      /> Ch3

      <input
        type="checkbox"
        id="chall"
        value="1"
        checked={
          this.state.ch1
          && this.state.ch2
          && this.state.ch3
        }
        onChange={this.onCheckboxChange}
      /> Ch all
</code>```

And then in the onCheckboxChange (or whatever the name is) just do something like:

```<code>const { id } = e.target;

if (id === 'chall') {
  if (e.target.checked) {
    this.setState({
      ch1: true,
      ch2: true,
      ch3: true,
    });
    return;
  }

  this.setState({
    ch1: false,
    ch2: false,
    ch3: false,
  });
}

this.setState({
  [id]: e.target.checked,
});
</code>```

Title: Always get previous state in React app

Body:
In relation to my previous question, I'm doing this to store the right state:

if (value === 'checkpoint')
{
  if (checked1)
  {
    this.setState({checked1 : false})
    localStorage.setObject('checked1', false)
  }
  else
  {
    this.setState({checked1 : true})
    localStorage.setObject('checked1', true)
  }
}

Now I have multiple checkboxes (let's say I have four). One for ALL checkboxes, and the other 3 for categories. I want my app to detect when the three category checkboxes are checked, and check the ALL checkbox automatically. When any of the category checkboxes are unchecked, the ALL checkbox will uncheck itself.

I tried this code:

  if (checked1 && checked2 && checked3) {
    this.setState({checkedAll: true})
  } else {
    this.setState({checkedAll: false})
  }

But the other 3 checkbox (checked1, checked2, checked3) will always get a previous state.

How do I get the right state so that my checkedAll functions correctly?

Body:
You should rather avoid using setState() in componentDidUpdate() as it sometimes leads to bugs in your code and is considered not a good practice (e.g. https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-did-update-set-state.md so if you use airbnb rules to configure your eslint you'll also run into some linting warnings).

Can't you make all four checkboxes controlled inputs like so:

      <input
        type="checkbox"
        id="ch1"
        value="1"
        checked={this.state.ch1}
        onChange={this.onCheckboxChange}
      /> Ch1

      <input
        type="checkbox"
        id="ch2"
        value="1"
        checked={this.state.ch2}
        onChange={this.onCheckboxChange}
      /> Ch2

      <input
        type="checkbox"
        id="ch3"
        value="1"
        checked={this.state.ch3}
        onChange={this.onCheckboxChange}
      /> Ch3

      <input
        type="checkbox"
        id="chall"
        value="1"
        checked={
          this.state.ch1
          && this.state.ch2
          && this.state.ch3
        }
        onChange={this.onCheckboxChange}
      /> Ch all

And then in the onCheckboxChange (or whatever the name is) just do something like:

const { id } = e.target;

if (id === 'chall') {
  if (e.target.checked) {
    this.setState({
      ch1: true,
      ch2: true,
      ch3: true,
    });
    return;
  }

  this.setState({
    ch1: false,
    ch2: false,
    ch3: false,
  });
}

this.setState({
  [id]: e.target.checked,
});


问:
sending text messages through twilio
i have an application that allows the user to send a text message by entering a phone number into the input field. but the text message is set to just say "hello". how can i allow the user to enter what they want the text message to say. heres the code

JS

```<code>app.get("/:data", function(req, resp){

var accountSid = '*******************'
var authToken = '*********************'

const client = require('twilio')(accountSid, authToken);

client.messages.create({

to: req.params.data,
from: '**********',
body: "Hello"
}, function(err, message) {
if(err) {
console.log(err);
} else {
console.log(message.sid);
}

});
</code>```

HTML

```<code><input type="text" placeholder="Enter your number" id="inputNum" />

<button id="submitNum">Enter</button>

<script>

submitNum.addEventListener("click", function(){

var inputNum = document.getElementById("inputNum");
var submitNum = document.getElementById("submitNum");

var phoneNumber = inputNum.value;

fetch(" https://*******************.com/"
+ phoneNumber).then((resp)=>{
console.log(resp);
});
});
</code>```

答:
Twilio developer evangelist here.

To allow your user to enter the message too, you need to add an extra field to your HTML form and then add that field to the API request too. I would also suggest not adding the phone number to the path of the URL, but to query parameters instead. So, taking your HTML first, I'd change it to this:

```<code><input type="text" placeholder="Enter your number" id="inputNum" />
<textarea name="inputMessage" id="inputMessage"></textarea>

<button id="submitNum">Enter</button>

<script>
var inputNum = document.getElementById("inputNum");
var inputMessage = document.getElementById("inputMessage");
var submitNum = document.getElementById("submitNum");

submitNum.addEventListener("click", function(){
  var phoneNumber = inputNum.value;
  var message = inputMessage.value;

  var query = "phoneNumnber=" + encodeURIComponent(phoneNumber);
  query += "&message=" + encodeURIComponent(message);
  fetch(" https://*******************.com/sendMessage?" + query).then((resp)=>{
    console.log(resp);
  });
});
</script>
</code>```

Then, you'll need to update your server to use the message variable and the sendMessage endpoint. I also suggest you send a response back, so that your front end isn't left hanging. Like this:

```<code>app.get("/sendMessage", function(req, resp){
  var accountSid = '*******************'
  var authToken = '*********************'

  const client = require('twilio')(accountSid, authToken);

  client.messages.create({
    to: req.params.data,
    from: '**********',
    body: req.params.message
  }, function(err, message) {
    if(err) {
      console.log(err);
      resp.setStatus(200).send();
    } else {
      console.log(message.sid);
      resp.setStatus(500).send();
    }
  });
});
</code>```

Let me know if that helps at all.

Title: sending text messages through twilio

Body:
i have an application that allows the user to send a text message by entering a phone number into the input field. but the text message is set to just say "hello". how can i allow the user to enter what they want the text message to say. heres the code

JS

app.get("/:data", function(req, resp){

var accountSid = '*******************'
var authToken = '*********************'

const client = require('twilio')(accountSid, authToken);

client.messages.create({

to: req.params.data,
from: '**********',
body: "Hello"
}, function(err, message) {
if(err) {
console.log(err);
} else {
console.log(message.sid);
}

});

HTML

<input type="text" placeholder="Enter your number" id="inputNum" />

<button id="submitNum">Enter</button>

Body:
Twilio developer evangelist here.

To allow your user to enter the message too, you need to add an extra field to your HTML form and then add that field to the API request too. I would also suggest not adding the phone number to the path of the URL, but to query parameters instead. So, taking your HTML first, I'd change it to this:

<input type="text" placeholder="Enter your number" id="inputNum" />
<textarea name="inputMessage" id="inputMessage"></textarea>

<button id="submitNum">Enter</button>

<script>
var inputNum = document.getElementById("inputNum");
var inputMessage = document.getElementById("inputMessage");
var submitNum = document.getElementById("submitNum");

submitNum.addEventListener("click", function(){
  var phoneNumber = inputNum.value;
  var message = inputMessage.value;

  var query = "phoneNumnber=" + encodeURIComponent(phoneNumber);
  query += "&message=" + encodeURIComponent(message);
  fetch(" https://*******************.com/sendMessage?" + query).then((resp)=>{
    console.log(resp);
  });
});
</script>

Then, you'll need to update your server to use the message variable and the sendMessage endpoint. I also suggest you send a response back, so that your front end isn't left hanging. Like this:

app.get("/sendMessage", function(req, resp){
  var accountSid = '*******************'
  var authToken = '*********************'

  const client = require('twilio')(accountSid, authToken);

  client.messages.create({
    to: req.params.data,
    from: '**********',
    body: req.params.message
  }, function(err, message) {
    if(err) {
      console.log(err);
      resp.setStatus(200).send();
    } else {
      console.log(message.sid);
      resp.setStatus(500).send();
    }
  });
});

Let me know if that helps at all.


问:
Gps Location tracking on Google Map
I want to use Google Map in my j2me application for GPS location.

I want to track the location of other mobile phone from my mobile phone and can able to see in my mobile as Google Map.

答:
This Forum Nokia wiki gives an example of how to use Google Maps in Java ME, but beware:

Usage of this code with the free Google Maps API Key breaks Google's Terms and Conditions (section 10.8).

You'll need some way of getting access to the other handset's location, presumably with the other user's consent.  I guess you'll create another app which sends its location to a server, which your maps app will presumably also be talking to, to find the other user's location.

ContentLicense: CC BY-SA 4.0

Title: Gps Location tracking on Google Map


问:
How to 'synchronize' master and development branches?
Someone merged our development branch next into our master branch. Now next is one commit behind master.

Our feature branches come from next, and we merge back to next from them.

I'm concerned that next will diverge from master if I merge feature1 into next. There are multiple feature branches.

How do I 'synchronize' next and master, so that I can merge feature1 into next and 'synchronize' feature2 to next afterwards?

I'm using 'synchronize' to signify merge, rebase, etc.

UPDATE:

What is confusing me is that normal is behind master. The files are the same. It appears to be a commit created for the pull request merge. My concern is that next and master will have a mixed divergence

```<code>master: A <--B
              \
next:   D <--- C
</code>```

A is the merge commit. D is a commit on next after the merge commit. So, then master and next have commits not on the other. Does that matter?

答:
This is a normal git flow, and is nothing to be worried about.

Feature branches should branch off of develop (in your case next), and merge into master at some point (usually on each new release or version). It's common for develop and master to diverge; develop should almost always be ahead of master. You should only ever be pushing to master when there's a new release or a hotfix.

Branch your feature branches off of develop, and once you are happy with the changes, merge the feature branches back to develop. Once you are ready for release, and have ensured that none of the feature branches have conflicts with each other, you can merge develop back to master. This will bring all of the changes from each feature branch into master.

Your two branches currently look like the following:

```<code>next     ------ A -
                    \
master   ------ A -- B
</code>```

As you merge feature branches into next:

```<code>feature2 -----------------
                           \
feature1 --------------     \
                       \     \
next     ------ A -  -- C --- E -- G -
                    \                  \
master   ------ A -- B --- D --- F ---- H
</code>```

Hopefully the above ASCII diagram helps illustrate this, though a number of helpful picture diagrams illustrating git flow can be found at GitHub.

Hope this helps! :)

Body:
Someone merged our development branch next into our master branch. Now next is one commit behind master.

Our feature branches come from next, and we merge back to next from them.

I'm concerned that next will diverge from master if I merge feature1 into next. There are multiple feature branches.

How do I 'synchronize' next and master, so that I can merge feature1 into next and 'synchronize' feature2 to next afterwards?

I'm using 'synchronize' to signify merge, rebase, etc.

UPDATE:

What is confusing me is that normal is behind master. The files are the same. It appears to be a commit created for the pull request merge. My concern is that next and master will have a mixed divergence

master: A <--B
              \
next:   D <--- C

A is the merge commit. D is a commit on next after the merge commit. So, then master and next have commits not on the other. Does that matter?

Body:
This is a normal git flow, and is nothing to be worried about.

Feature branches should branch off of develop (in your case next), and merge into master at some point (usually on each new release or version). It's common for develop and master to diverge; develop should almost always be ahead of master. You should only ever be pushing to master when there's a new release or a hotfix.

Branch your feature branches off of develop, and once you are happy with the changes, merge the feature branches back to develop. Once you are ready for release, and have ensured that none of the feature branches have conflicts with each other, you can merge develop back to master. This will bring all of the changes from each feature branch into master.

Your two branches currently look like the following:

next     ------ A -
                    \
master   ------ A -- B

As you merge feature branches into next:

feature2 -----------------
                           \
feature1 --------------     \
                       \     \
next     ------ A -  -- C --- E -- G -
                    \                  \
master   ------ A -- B --- D --- F ---- H

Hopefully the above ASCII diagram helps illustrate this, though a number of helpful picture diagrams illustrating git flow can be found at GitHub.

Hope this helps! :)


问:
Android add listener while preserving original one
I want to make something happen on text selection, which is OnLongClickListener, but inside of that I need to get selected text, which is handled by default OnLongClickListener (at least I think it is).
Actual result, by adding just my listener, is that my method is called, I'm trying to get indices of selection bounds, but these are 0. I can also see in debugger, that no text is selected in that momment.

Code:

```<code>textView.setTextIsSelectable(true);
textView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            int start = textView.getSelectionStart();
            int end = textView.getSelectionEnd();
            // the rest of code
        }
    }
}
</code>```

Question: How can I preserve default listener, which will be called first and make selection and then call my function.

答:
I think you misunderstand how listeners work.  They don't replace standard behavior, so there is no default listener to invoke to make sure something happens.

In this case, most likely your OnLongClick listener is simply being called before the TextView has actually updated its selection. In which case, you can try having your listener delay its processing until after the selection is set. Look at using Handler.postDelayed() or AsyncTask for that purpose. For example:

```<code>textView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            new Handler().post(() -> {/*your code here*/});
        }
    }
}
</code>```

But, that being said, OnLongClickListener is not the correct listener to use for text selection changes.  You need an ActionMode Callback instead:

How to set up a listener on the selected text in TextView

Body:
I want to make something happen on text selection, which is OnLongClickListener, but inside of that I need to get selected text, which is handled by default OnLongClickListener (at least I think it is).
Actual result, by adding just my listener, is that my method is called, I'm trying to get indices of selection bounds, but these are 0. I can also see in debugger, that no text is selected in that momment.

Code:

textView.setTextIsSelectable(true);
textView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            int start = textView.getSelectionStart();
            int end = textView.getSelectionEnd();
            // the rest of code
        }
    }
}

Question: How can I preserve default listener, which will be called first and make selection and then call my function.

Body:
I think you misunderstand how listeners work.  They don't replace standard behavior, so there is no default listener to invoke to make sure something happens.

In this case, most likely your OnLongClick listener is simply being called before the TextView has actually updated its selection. In which case, you can try having your listener delay its processing until after the selection is set. Look at using Handler.postDelayed() or AsyncTask for that purpose. For example:

textView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            new Handler().post(() -> {/*your code here*/});
        }
    }
}

But, that being said, OnLongClickListener is not the correct listener to use for text selection changes.  You need an ActionMode Callback instead:

How to set up a listener on the selected text in TextView


问:
HTML, flex, two divs in a row, force one div to have size of smaller
Subj.

I have two divs (left and right). And I want to make left div something like main one, and force right div to have the same height as a left one, even if it will have more content (and do overflow: hidden). I will appreciate if there is a way to make it with css and html without js.

Here is a little snippet, how my markup is looking:

.parent {
  display: flex;
  flex-direction: row;
  align-items: stretch;
}

.children-1 {
  width: 66.6%;
  background: green;
}

.children-2 {
  width: 33.4%;
  background: yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="children-1">
    <p>My content</p>
  </div>

  <div class="children-2">
    <p>a lot of content<p>
    <p>a lot of content</p>
  </div>
</div></code>```

答:
Yes of course! Just use CSS grid!!

```<code>.parent {
  display: grid;
  grid-template-columns: 2fr 1fr;
}
.children-1 {
  background: green;
}
.children-2 {
  background: yellow;
  overflow-y: hidden;
  max-height: 200px; // Limit the height
}
</code>```

https://codepen.io/Konrad001/pen/MOxzEe

Body:
Subj.

I have two divs (left and right). And I want to make left div something like main one, and force right div to have the same height as a left one, even if it will have more content (and do overflow: hidden). I will appreciate if there is a way to make it with css and html without js.

Here is a little snippet, how my markup is looking:

.parent {
  display: flex;
  flex-direction: row;
  align-items: stretch;
}

.children-1 {
  width: 66.6%;
  background: green;
}

.children-2 {
  width: 33.4%;
  background: yellow;
}

My content

a lot of content

a lot of content

Body:
Yes of course! Just use CSS grid!!

.parent {
  display: grid;
  grid-template-columns: 2fr 1fr;
}
.children-1 {
  background: green;
}
.children-2 {
  background: yellow;
  overflow-y: hidden;
  max-height: 200px; // Limit the height
}

https://codepen.io/Konrad001/pen/MOxzEe


问:
Serverless framework does not deploy internal folders to aws
I have a folder structure for lambda as follows created using

serverless create --template aws-python --path base_folder

base_folder

 - serverless.yml

 - src

    - src/handler.py

    - src/another_folder

        - src/another_folder/file.json

When I run serverless deploy, I do not see the another_folder in the lambda management console on aws.

答:
You'll have to specify this particular folder inside serverless.yml if it's not specified or referenced from your code files:

```<code>service: your_project_name
# your serverless code...
package:
  include:
    src/another_folder/**
# more serverless code...
</code>```

See the docs on serverless packaging here.

Thanks @dege for pointing out I missed the /** to note the contents of the actual folder

Body:
You'll have to specify this particular folder inside serverless.yml if it's not specified or referenced from your code files:

service: your_project_name
# your serverless code...
package:
  include:
    src/another_folder/**
# more serverless code...

See the docs on serverless packaging here.

Thanks @dege for pointing out I missed the /** to note the contents of the actual folder