问:
How does a json formatted response from a SQL Server work?
I have a stored procedure that returns query results as json and I want to understand how this query will get to my code behind in an ASP.NET app.

Stored procedure:

```<code>Select
       SUBJECT AS [subject],
       STARTDATE AS [start]
       ENDDATE AS [end],
       ID AS [id]
FROM
       SOME_TABLE
FOR JSON PATH
</code>```

Json format from stored procedure:

```<code>[
 {
  "subject": _,
  "start": _,
  "end":_,
  "id":_
 },
 ...]
</code>```

aspx.cs codebehind

(snippet from a function)

```<code>  try
        {
            if (sqlcon.State == ConnectionState.Closed)
            {
                sqlcon.Open();
            }

            SqlCommand sccmd = new SqlCommand("MY_STORED_PROCEDURE", sqlcon);
            sccmd.CommandType = CommandType.StoredProcedure;
            sccmd.Parameters.AddWithValue("@value1", valueID);
            sccmd.Parameters.AddWithValue("@value2", valueID);
            SqlDataReader sdrreader = sccmd.ExecuteReader();

            while (sdrreader.Read())
            {
                // lost on what to do here
            }

            sdrreader.Close();
        }
        catch (Exception ex){}
        finally { sqlcon.Close(); }
</code>```

I want to store this json response in my code behind, but I don't know how. Before making the response json I was using SqlDataReader with Read() to walk through each record, but how would this work if the response is now json; is there another class that will specifically handle a json response?

Clarification please!

答:
Install JSON.NET via NuGet.

Create a code model to mirror your json.

```<code>public class JsonModel {
    public int id {get;set;}
    public DateTime start {get;set;}
    public DateTime end {get;set;}
    public string subject {get;set;}
}
</code>```

Grab your json encoded data from the database

```<code>string json = String.Empty;
using (SqlConnection connection = new SqlConnection("... your connection string ...") {
    connection.Open();
    using (SqlCommand command = new SqlCommand("SELECT FROM... FOR JSON PATH", connection) {
        json = command.ExecuteScalar();
    }
}
</code>```

Deserialize it to your model

```<code>var JsonModel model = JsonConvert.DeserializeObject<JsonModel>(json);
</code>```

Drink tequila and eat fajitas!

Body:
I have a stored procedure that returns query results as json and I want to understand how this query will get to my code behind in an ASP.NET app.

Stored procedure:

Select
       SUBJECT AS [subject],
       STARTDATE AS [start]
       ENDDATE AS [end],
       ID AS [id]
FROM
       SOME_TABLE
FOR JSON PATH

Json format from stored procedure:

[
 {
  "subject": _,
  "start": _,
  "end":_,
  "id":_
 },
 ...]

aspx.cs codebehind

(snippet from a function)

  try
        {
            if (sqlcon.State == ConnectionState.Closed)
            {
                sqlcon.Open();
            }

            SqlCommand sccmd = new SqlCommand("MY_STORED_PROCEDURE", sqlcon);
            sccmd.CommandType = CommandType.StoredProcedure;
            sccmd.Parameters.AddWithValue("@value1", valueID);
            sccmd.Parameters.AddWithValue("@value2", valueID);
            SqlDataReader sdrreader = sccmd.ExecuteReader();

            while (sdrreader.Read())
            {
                // lost on what to do here
            }

            sdrreader.Close();
        }
        catch (Exception ex){}
        finally { sqlcon.Close(); }

I want to store this json response in my code behind, but I don't know how. Before making the response json I was using SqlDataReader with Read() to walk through each record, but how would this work if the response is now json; is there another class that will specifically handle a json response?

Clarification please!

Body:
Install JSON.NET via NuGet.

Create a code model to mirror your json.

public class JsonModel {
    public int id {get;set;}
    public DateTime start {get;set;}
    public DateTime end {get;set;}
    public string subject {get;set;}
}

Grab your json encoded data from the database

string json = String.Empty;
using (SqlConnection connection = new SqlConnection("... your connection string ...") {
    connection.Open();
    using (SqlCommand command = new SqlCommand("SELECT FROM... FOR JSON PATH", connection) {
        json = command.ExecuteScalar();
    }
}

Deserialize it to your model

var JsonModel model = JsonConvert.DeserializeObject<JsonModel>(json);

Drink tequila and eat fajitas!


来源: stackexchange

问:
Dynamic EventKey not working React-Bootstrap
I am dynamically rendering my tabs in React-Bootstrap, but somehow the eventKey doesn't recognise the values and the tabs aren't clickable.
Here's the code.

```<code>var tabButtons = tabsList.map(function(text, index){
                        if(text.enabled==1)
                        {
                        return <NavItem eventKey={index} key={index}><center> {text.value}</center></NavItem>; }
                      });
</code>```

Here tabList is an array which contains information about whether the button is enabled. If yes, then display the button information.

The code where I am calling these tabs.

```<code>render() {

        return (
            <div>
                <Tab.Container id="tab" defaultActiveKey="0">
                <Row className="show-grid">
                  <Col sm={12}>
                    <Nav bsStyle="tabs" justified>
                      {tabButtons}
                    </Nav>
                  </Col>

                  <Col sm={12}>
                    <Tab.Content animation>
                      <Tab.Pane eventKey="0">
                       <FirstTabContent />
                      </Tab.Pane>
                      <Tab.Pane eventKey="1">
                       Second
                      </Tab.Pane>
                      <Tab.Pane eventKey="2">
                         <ThirdTabContent />
                      </Tab.Pane>

                    </Tab.Content>
                  </Col>
                </Row>
                </Tab.Container>
            </div>
            );
</code>```

I have no idea, why aren't the eventKey able to use the index values.
Anything I am missing? Another approach perhaps?

答:
Apparently after some hit and tries, got it working.

The problem was indeed in eventKey.

Replaced eventKey="0" with eventKey={0}

Though I have no idea what difference it makes. Anyone?

ContentLicense: CC BY-SA 3.0

Body:
I am dynamically rendering my tabs in React-Bootstrap, but somehow the eventKey doesn't recognise the values and the tabs aren't clickable.
Here's the code.

var tabButtons = tabsList.map(function(text, index){
                        if(text.enabled==1)
                        {
                        return <NavItem eventKey={index} key={index}> {text.value}</NavItem>; }
                      });

Here tabList is an array which contains information about whether the button is enabled. If yes, then display the button information.

The code where I am calling these tabs.

render() {

        return (

                <Tab.Container id="tab" defaultActiveKey="0">
                <Row className="show-grid">
                  <Col sm={12}>

                      {tabButtons}

                  </Col>

                  <Col sm={12}>
                    <Tab.Content animation>
                      <Tab.Pane eventKey="0">
                       <FirstTabContent />
                      </Tab.Pane>
                      <Tab.Pane eventKey="1">
                       Second
                      </Tab.Pane>
                      <Tab.Pane eventKey="2">
                         <ThirdTabContent />
                      </Tab.Pane>

                    </Tab.Content>
                  </Col>
                </Row>
                </Tab.Container>

            );

I have no idea, why aren't the eventKey able to use the index values.
Anything I am missing? Another approach perhaps?


问:
Python 3.5 multiprocessing pools && 'numpy.int64 has no attribute .loc'
I'm trying to learn about multiprocessing and pools to process some tweets I've got in a MySQL DB. Here is the code and error messages.

```<code>import multiprocessing
import sqlalchemy
import pandas as pd
import config
from nltk import tokenize as token

q = multiprocessing.Queue()
engine = sqlalchemy.create_engine(config.sqlConnectionString)

def getRow(pandasSeries):
    df = pd.DataFrame()
    tweetTokenizer = token.TweetTokenizer()
    print(pandasSeries.loc['BODY'], "\n", type(pandasSeries.loc['BODY']))
    for tokens in tweetTokenizer.tokenize(pandasSeries.loc['BODY']):
        df = df.append(pd.Series(data=[pandasSeries.loc['ID'], tokens, pandasSeries.loc['AUTHOR'],
                                  pandasSeries.loc['RETWEET_COUNT'], pandasSeries.loc['FAVORITE_COUNT'],
                                  pandasSeries.loc['FOLLOWERS_COUNT'], pandasSeries.loc['FRIENDS_COUNT'],
                                  pandasSeries.loc['PUBLISHED_AT']],
                                 index=['id', 'tweet', 'author', 'retweet', 'fav', 'followers', 'friends',
                                        'published_at']), ignore_index=True)
    df.to_sql(name="tweet_tokens", con=engine, if_exists='append')

if __name__ == '__main__':
    ##LOADING SQL INTO DATAFRAME##
    databaseData = pd.read_sql_table(config.tweetTableName, engine)

    pool = multiprocessing.Pool(6)
    for row in databaseData.iterrows():
        print(row)
        pool.map(getRow, row)
    pool.close()
    q.close()
    q.join_thread()

"""
            OUPUT

C:\Users\Def\Anaconda3\python.exe C:/Users/Def/Dropbox/Dissertation/testThreadCopy.py
(0, ID                                                              3247
AUTHOR                                             b'Elon Musk News'
RETWEET_COUNT                                                      0
FAVORITE_COUNT                                                     0
FOLLOWERS_COUNT                                                20467
FRIENDS_COUNT                                                  14313
BODY               Elon Musk Takes an Adorable 5th Grader's Idea ...
PUBLISHED_AT                                     2017-03-03 00:00:01
Name: 0, dtype: object)
Elon Musk Takes an Adorable 5th Grader's
 <class 'str'>
multiprocessing.pool.RemoteTraceback:

Traceback (most recent call last):
  File "C:\Users\Def\Anaconda3\lib\multiprocessing\pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "C:\Users\Def\Anaconda3\lib\multiprocessing\pool.py", line 44, in mapstar
    return list(map(*args))
  File "C:\Users\Def\Dropbox\Dissertation\testThreadCopy.py", line 16, in getRow
    print(pandasSeries.loc['BODY'], "\n", type(pandasSeries.loc['BODY']))
AttributeError: 'numpy.int64' object has no attribute 'loc'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:/Users/Def/Dropbox/Dissertation/testThreadCopy.py", line 34, in <module>
    pool.map(getRow, row)
  File "C:\Users\Def\Anaconda3\lib\multiprocessing\pool.py", line 260, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "C:\Users\Def\Anaconda3\lib\multiprocessing\pool.py", line 608, in get
    raise self._value
AttributeError: 'numpy.int64' object has no attribute 'loc'

Process finished with exit code 1
"""
</code>```

What I don't understand is why it prints out the first Series and then crashes? And why does it say that pandasSeries.loc['BODY'] is of type numpy.int64 when the print out it says that it is of type string? I'm sure I've gone wrong in a number of other places if you can see where please can you point it out.
Thanks.

答:
When I construct a simple dataframe:

```<code>frame
   0  1   2   3
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
</code>```

and iterate twice I get:

```<code>for row in databaseData.iterrows():
    for i in row:
        print(i, type(i))
</code>```

That inner loop produces 2 items, a row index/label, and a Series with the values.

```<code>0 <class 'numpy.int64'>
0    0
1    1
2    2
3    3
Name: 0, dtype: int32 <class 'pandas.core.series.Series'>
</code>```

Your map does the same, sending a numeric index to one process (which produces the error), and a series to another.

If I use pool.map without the for row:

```<code>pool.map(getRow, databaseData.iterrows())
</code>```

then getRow receives a 2 element tuple.

```<code>def getRow(aTuple):
    rowlbl, rowSeries = aTuple
    print(rowSeries)
    ...
</code>```

Your print(row) shows this tuple; it's just harder to see because the Series part is multiline.  If I add a \n it might be clearer

```<code>(0,                                   # row label
ID                               3247       # multiline Series
AUTHOR                           b'Elon Musk News'
RETWEET_COUNT                    0
....
Name: 0, dtype: object)
</code>```

Body:
I'm trying to learn about multiprocessing and pools to process some tweets I've got in a MySQL DB. Here is the code and error messages.

import multiprocessing
import sqlalchemy
import pandas as pd
import config
from nltk import tokenize as token

q = multiprocessing.Queue()
engine = sqlalchemy.create_engine(config.sqlConnectionString)

def getRow(pandasSeries):
    df = pd.DataFrame()
    tweetTokenizer = token.TweetTokenizer()
    print(pandasSeries.loc['BODY'], "\n", type(pandasSeries.loc['BODY']))
    for tokens in tweetTokenizer.tokenize(pandasSeries.loc['BODY']):
        df = df.append(pd.Series(data=[pandasSeries.loc['ID'], tokens, pandasSeries.loc['AUTHOR'],
                                  pandasSeries.loc['RETWEET_COUNT'], pandasSeries.loc['FAVORITE_COUNT'],
                                  pandasSeries.loc['FOLLOWERS_COUNT'], pandasSeries.loc['FRIENDS_COUNT'],
                                  pandasSeries.loc['PUBLISHED_AT']],
                                 index=['id', 'tweet', 'author', 'retweet', 'fav', 'followers', 'friends',
                                        'published_at']), ignore_index=True)
    df.to_sql(name="tweet_tokens", con=engine, if_exists='append')

if __name__ == '__main__':
    ##LOADING SQL INTO DATAFRAME##
    databaseData = pd.read_sql_table(config.tweetTableName, engine)

    pool = multiprocessing.Pool(6)
    for row in databaseData.iterrows():
        print(row)
        pool.map(getRow, row)
    pool.close()
    q.close()
    q.join_thread()

"""
            OUPUT

C:\Users\Def\Anaconda3\python.exe C:/Users/Def/Dropbox/Dissertation/testThreadCopy.py
(0, ID                                                              3247
AUTHOR                                             b'Elon Musk News'
RETWEET_COUNT                                                      0
FAVORITE_COUNT                                                     0
FOLLOWERS_COUNT                                                20467
FRIENDS_COUNT                                                  14313
BODY               Elon Musk Takes an Adorable 5th Grader's Idea ...
PUBLISHED_AT                                     2017-03-03 00:00:01
Name: 0, dtype: object)
Elon Musk Takes an Adorable 5th Grader's
 <class 'str'>
multiprocessing.pool.RemoteTraceback:

Traceback (most recent call last):
  File "C:\Users\Def\Anaconda3\lib\multiprocessing\pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "C:\Users\Def\Anaconda3\lib\multiprocessing\pool.py", line 44, in mapstar
    return list(map(*args))
  File "C:\Users\Def\Dropbox\Dissertation\testThreadCopy.py", line 16, in getRow
    print(pandasSeries.loc['BODY'], "\n", type(pandasSeries.loc['BODY']))
AttributeError: 'numpy.int64' object has no attribute 'loc'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:/Users/Def/Dropbox/Dissertation/testThreadCopy.py", line 34, in <module>
    pool.map(getRow, row)
  File "C:\Users\Def\Anaconda3\lib\multiprocessing\pool.py", line 260, in map
    return self._map_async(func, iterable, mapstar, chunksize).get()
  File "C:\Users\Def\Anaconda3\lib\multiprocessing\pool.py", line 608, in get
    raise self._value
AttributeError: 'numpy.int64' object has no attribute 'loc'

Process finished with exit code 1
"""

What I don't understand is why it prints out the first Series and then crashes? And why does it say that pandasSeries.loc['BODY'] is of type numpy.int64 when the print out it says that it is of type string? I'm sure I've gone wrong in a number of other places if you can see where please can you point it out.
Thanks.

Body:
When I construct a simple dataframe:

frame
   0  1   2   3
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11

and iterate twice I get:

for row in databaseData.iterrows():
    for i in row:
        print(i, type(i))

That inner loop produces 2 items, a row index/label, and a Series with the values.

0 <class 'numpy.int64'>
0    0
1    1
2    2
3    3
Name: 0, dtype: int32 <class 'pandas.core.series.Series'>

Your map does the same, sending a numeric index to one process (which produces the error), and a series to another.

If I use pool.map without the for row:

pool.map(getRow, databaseData.iterrows())

then getRow receives a 2 element tuple.

def getRow(aTuple):
    rowlbl, rowSeries = aTuple
    print(rowSeries)
    ...

Your print(row) shows this tuple; it's just harder to see because the Series part is multiline.  If I add a \n it might be clearer

(0,                                   # row label
ID                               3247       # multiline Series
AUTHOR                           b'Elon Musk News'
RETWEET_COUNT                    0
....
Name: 0, dtype: object)


问:
How to use multi-key words in the MSSQL (ANSISQL)
I know how to do in Oracle as following example code, however how can i do in ANSI SQL like MSSQL to do the same script, please help me to handle this question.

PS: this script is for multi-key words(PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO)

For example

```<code>SELECT * FROM TEST
WHERE (PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO)
IN
(
    SELECT PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO FROM TEST
    WHERE CASENO > 0 AND TO_CHAR(SCRN,'YYYY') = '2017'
)
</code>```

Please let me know if my question isn't very clear

答:
@Gordon Linoff had given you very great example , I just change a little bit ,hopefully it can help you </p>

```<code>SELECT t.*
FROM irbvisit t
WHERE EXISTS (SELECT 1
              FROM irbvisit t2
              WHERE t2.CASENO > 0 AND
                  convert(varchar(4), SCRN, 126)='2017' and
                    t2.PNO = t.PNO AND
                    t2.CASENO = t.CASENO AND
                    t2.SCRN = t.SCRN AND
                    t2.IRBCODE = t.IRBCODE AND
                    t2.ITEMCODE = t.ITEMCODE AND
                    t2.MMHCODE = t.MMHCODE AND
                    t2.ROWNO = t.ROWNO
</code>```

Body:
I know how to do in Oracle as following example code, however how can i do in ANSI SQL like MSSQL to do the same script, please help me to handle this question.

PS: this script is for multi-key words(PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO)

For example

SELECT * FROM TEST
WHERE (PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO)
IN
(
    SELECT PNO,CASENO,SCRN,IRBCODE,ITEMCODE,MMHCODE,ROWNO FROM TEST
    WHERE CASENO > 0 AND TO_CHAR(SCRN,'YYYY') = '2017'
)

Please let me know if my question isn't very clear

Body:
@Gordon Linoff had given you very great example , I just change a little bit ,hopefully it can help you

SELECT t.*
FROM irbvisit t
WHERE EXISTS (SELECT 1
              FROM irbvisit t2
              WHERE t2.CASENO > 0 AND
                  convert(varchar(4), SCRN, 126)='2017' and
                    t2.PNO = t.PNO AND
                    t2.CASENO = t.CASENO AND
                    t2.SCRN = t.SCRN AND
                    t2.IRBCODE = t.IRBCODE AND
                    t2.ITEMCODE = t.ITEMCODE AND
                    t2.MMHCODE = t.MMHCODE AND
                    t2.ROWNO = t.ROWNO


问:
Calling an enum inside a function in Swift
I'm absolutely at a loss on this one. What is my instructor looking for? Any suggestions?

Started something like this, but I'm just off..

```<code>enum Color: String {

case blue = "orange"
case red = "green"
case yellow = "purple"

}

func complement(_ color) -> String {
    case
}
</code>```

Question:
Create a type, Color with the three primary colors and the three secondary colors. Then create a function complement which will return the complementary color for a provided color.

```<code>Red's complement is green
Blue's complement is orange
Yellow's complement is purple

complement(.red) -> .green
complement(.orange) -> .blue
</code>```

updated:

```<code>enum Color: String {
    case red = "red"
    case green = "green"
    case blue = "blue"

    case yellow = "yellow"
    case orange = "orange"
    case purple = "purple"
}

func compliment(_ color: Color) -> Color {
    switch color {
    case .red: return .green
    case .green: return .red
    case .blue: return .orange
    break
    }
}

let red = Color.red
let compliment = compliment(red)
print(compliment)

let green = Color.green
let compliment = compliment(green)
print(compliment)

let blue = Color.blue
let compliment = compliment(blue)
print(compliment)
</code>```

error: variable used within its own initial value

```<code>let compliment = compliment(red)
</code>```

It's doing this for every instance

答:
Since this is homework, I'll give you enough of a pointer to get you started, but won't do it for you.

```<code>enum Color: String {
    case red = "red"
    case green = "green"
    case blue = "blue"

    case yellow = "yellow"
    case orange = "orange"
    case purple = "purple"
}

func complement(_ color: Color) -> Color {
    switch color {
    case .red: return .green
    case .green: return .red
    case .blue: return .orange
    // etc.
    }
}

let red = Color.red
let compliment = complement(red)
print(compliment)
</code>```

And without getting too deep into color theory, the complement of red isn't blue - it's cyan. For green it's magenta. And blue's complement is yellow.

Body:
I'm absolutely at a loss on this one. What is my instructor looking for? Any suggestions?

Started something like this, but I'm just off..

enum Color: String {

case blue = "orange"
case red = "green"
case yellow = "purple"

}

func complement(_ color) -> String {
    case
}

Question:
Create a type, Color with the three primary colors and the three secondary colors. Then create a function complement which will return the complementary color for a provided color.

Red's complement is green
Blue's complement is orange
Yellow's complement is purple

complement(.red) -> .green
complement(.orange) -> .blue

updated:

enum Color: String {
    case red = "red"
    case green = "green"
    case blue = "blue"

    case yellow = "yellow"
    case orange = "orange"
    case purple = "purple"
}

func compliment(_ color: Color) -> Color {
    switch color {
    case .red: return .green
    case .green: return .red
    case .blue: return .orange
    break
    }
}

let red = Color.red
let compliment = compliment(red)
print(compliment)

let green = Color.green
let compliment = compliment(green)
print(compliment)

let blue = Color.blue
let compliment = compliment(blue)
print(compliment)

error: variable used within its own initial value

let compliment = compliment(red)

It's doing this for every instance

Body:
Since this is homework, I'll give you enough of a pointer to get you started, but won't do it for you.

enum Color: String {
    case red = "red"
    case green = "green"
    case blue = "blue"

    case yellow = "yellow"
    case orange = "orange"
    case purple = "purple"
}

func complement(_ color: Color) -> Color {
    switch color {
    case .red: return .green
    case .green: return .red
    case .blue: return .orange
    // etc.
    }
}

let red = Color.red
let compliment = complement(red)
print(compliment)

And without getting too deep into color theory, the complement of red isn't blue - it's cyan. For green it's magenta. And blue's complement is yellow.


问:
How to associate public Ip Address with an existing domain name
i don t understand how DNS works!

I have an public IP address bouaght from AZURE and Now my website already has a domain name (myWebsite.com) that is tied to my old server.

Now I have bought a new VM in AZURE ( it is a Ubuntu).

Now, how can i change that my domain name (myWebsite.com) to point now to the new Public IP ADDRESS of my VM at azure.

Do i have to do it in the command line or not?
??

答: Go to your DNS Server, where you created your domain name, click on +Record Set and create a A record using your new IP address, wait for the TTL time, and you should be able to connect</p>


问:
Google Sheet API V4 Java, Get Column Letter from Column Number
Hello: Using Google Spreadsheet API V4 on Java, I want to to get the column letter given the column number. Example: the column letter for column number 2 is B.

Is there some way already provisioned in Google spreadsheet API OR is there any other simple way to go do this OR do i need to write my own conversion?

答:
Though the Question still is: Is there a native way in Google Spreadsheet API V4 to get the column letter given the column number?

However, for future reference i am providing below a collation in case someone needs to implement his own conversion.

Case 1: Get Column Letter Given the Column Number

```<code>public void ColumnNumberToLetter() {
    int inputColumnNumber = 49;
    String outputColumnName = "";
    int Base = 26;
    String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    int TempNumber = inputColumnNumber;
    while (TempNumber > 0) {
       int position = TempNumber % Base;
       outputColumnName = (position == 0 ? 'Z' : chars.charAt(position > 0 ? position - 1 : 0)) + outputColumnName;
       TempNumber = (TempNumber - 1) / Base;
    }
    System.out.println("ColumnNumberToLetter :" + inputColumnNumber + " = " +  outputColumnName);
}
</code>```

Case 2: Get Column Number Given the Column Letter

```<code>public void ColumnLetterToNumber() {
    String inputColumnName = "AW";
    int outputColumnNumber = 0;

    if (inputColumnName == null || inputColumnName.length() == 0) {
        throw new IllegalArgumentException("Input is not valid!");
    }

    int i = inputColumnName.length() - 1;
    int t = 0;
    while (i >= 0) {
        char curr = inputColumnName.charAt(i);
        outputColumnNumber = outputColumnNumber + (int) Math.pow(26, t) * (curr - 'A' + 1);
        t++;
        i--;
    }
    System.out.println("ColumnLetterToNumber : " + inputColumnName + " = " +  outputColumnNumber);
}
</code>```

Body:
Though the Question still is: Is there a native way in Google Spreadsheet API V4 to get the column letter given the column number?

However, for future reference i am providing below a collation in case someone needs to implement his own conversion.

Case 1: Get Column Letter Given the Column Number

public void ColumnNumberToLetter() {
    int inputColumnNumber = 49;
    String outputColumnName = "";
    int Base = 26;
    String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    int TempNumber = inputColumnNumber;
    while (TempNumber > 0) {
       int position = TempNumber % Base;
       outputColumnName = (position == 0 ? 'Z' : chars.charAt(position > 0 ? position - 1 : 0)) + outputColumnName;
       TempNumber = (TempNumber - 1) / Base;
    }
    System.out.println("ColumnNumberToLetter :" + inputColumnNumber + " = " +  outputColumnName);
}

Case 2: Get Column Number Given the Column Letter

public void ColumnLetterToNumber() {
    String inputColumnName = "AW";
    int outputColumnNumber = 0;

    if (inputColumnName == null || inputColumnName.length() == 0) {
        throw new IllegalArgumentException("Input is not valid!");
    }

    int i = inputColumnName.length() - 1;
    int t = 0;
    while (i >= 0) {
        char curr = inputColumnName.charAt(i);
        outputColumnNumber = outputColumnNumber + (int) Math.pow(26, t) * (curr - 'A' + 1);
        t++;
        i--;
    }
    System.out.println("ColumnLetterToNumber : " + inputColumnName + " = " +  outputColumnNumber);
}


问:
C++ std::ifstream std::ios::in versus std::ios::in | std::ios::binary, why do I get junk data?
I'm curious when I call read on an std::ifstream object, why I get junk data if I open the file as std::ios::in, whereas I don't get junk data with std::ios::in | std::ios::binary?

I included screenshots of some messy code I've been trying stuff out with. I'm just confused why I get junk data with the first picture, when the second picture produces the correct data with the std::ios::binary flag set.

Junk data, but correct file length:

No junk data, same file length:

答:
In text mode, file positions aren't the number of bytes you can read.

So when you seek to the end, and see the file position is 24, that doesn't mean you can read 24 bytes. In fact you only read 20 bytes, but your loop ran 24 times, printing the 20 read bytes and another 4 garbage bytes from whatever was already in memory.

To find out the actual number of bytes that were read, you can call file_data.gcount() after calling file_data.read.


问:
Find minimum value in multiple column range with criteria
How can I find the minimum value in columns B:C in the table below if the volume is <= 10.

The expected result is in yellow.

Regards,
Elio Fernandes

答:
You can use this formula to get the minimum value (Which according to me should be 20 in your data set)

```<code>=MIN(1/AGGREGATE(14,6,1/((A2:A9<=10)*B2:B9),1),1/AGGREGATE(14,6,1/((A2:A9<=10)*C2:C9),1))
</code>```

for each additional column(say D) you will have to add the formula 1/AGGREGATE(14,6,1/((A2:A9<=10)*D2:D9),1) inside the MIN() formula.

Looking for a better way to do this.

EDIT:

Alternatively you could add a new row below your data. for each column you add the below formula to get the min for that column

```<code>=1/AGGREGATE(14,6,1/(($A$2:$A$9<=10)*B2:B9),1)
</code>```

Now you can drag this formula to as many columns you want. Take the MIN() of this row to get the overall minimum.

Body:
You can use this formula to get the minimum value (Which according to me should be 20 in your data set)

=MIN(1/AGGREGATE(14,6,1/((A2:A9<=10)*B2:B9),1),1/AGGREGATE(14,6,1/((A2:A9<=10)*C2:C9),1))

for each additional column(say D) you will have to add the formula 1/AGGREGATE(14,6,1/((A2:A9<=10)*D2:D9),1) inside the MIN() formula.

Looking for a better way to do this.

EDIT:

Alternatively you could add a new row below your data. for each column you add the below formula to get the min for that column

=1/AGGREGATE(14,6,1/(($A$2:$A$9<=10)*B2:B9),1)

Now you can drag this formula to as many columns you want. Take the MIN() of this row to get the overall minimum.


问:
How to get base url with jquery or javascript?
In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.

The base path may be any of the following example:

```<code>http://www.example.com/
http://localhost/example
http://www.example.com/sub/example
</code>```

The example may also change.

答:
Put this in your header, so it will be available whenever you need it.

```<code>var base_url = "<?php echo base_url();?>";
</code>```

You will get http://localhost:81/your-path-file or http://localhost/your-path-file.

Body:
In joomla php there I can use $this->baseurl to get the base path, but I wanted to get the base path in jquery.

The base path may be any of the following example:

http://www.example.com/
http://localhost/example
http://www.example.com/sub/example

The example may also change.

Body:
Put this in your header, so it will be available whenever you need it.

var base_url = "<?php echo base_url();?>";

You will get http://localhost:81/your-path-file or http://localhost/your-path-file.


问:
Extracting nested values in a Javascript object
I have the following object:

```<code>var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];
</code>```

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

```<code>[ '89304', '102524', '9' ]
</code>```

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.

答: You can write a recursive function the returns the values as a list. Just iterate through the keys with a forEach and if value is an object call itself. </p>

Body:
I have the following object:

var result = [{
"id": 89304,
"employeeDetails": {
    "id": 102524,
    "version": 9
}
}];

This is a snippet from a larger object that I'm trying to push into a MySQL table.
What I'm trying to achieve is extract just the values into their own array, which would return this:

[ '89304', '102524', '9' ]

This way, I can easily push the values to the DB.

I have tried doing the following which works fine without nesting:

obKeys = Object.keys(result);
console.log(obKeys);

However, with the nesting, the result I am getting is the following:

[ '0' ]

Can anyone let me know where I am going wrong, or suggest an alternative (better) way of doing this?

Thanks.


问:
how type in command adb -kill server?

when i type in cmd adb kill server it give me that adb not recognized. i cannot find the adb location in windows . what should i do to type in cmd to kill the adb

public class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.listView);
    TextView textView =(TextView) findViewById(R.id.txt);

    String[] item = getResources().getStringArray(R.array.index);

    ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.activity_second,R.id.txt,item);
      listView.setAdapter(adapter);
    Typeface typeface = Typeface.createFromAsset(getAssets(),"font.ttf");
    textView.setTypeface(typeface);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(MainActivity.this,Second.class);
            intent.putExtra("page",i);
            startActivity(intent);
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
</code>```

}

答:
Go to Task Managerusing Ctrl+Shift+Esc

then

click on processes find adb.exe

Right-Click on adb.exe

and click on End Task

Title: how type in command adb -kill server?

Body:
when i type in cmd adb kill server it give me that adb not recognized. i cannot find the adb location in windows . what should i do to type in cmd to kill the adb

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.listView);
    TextView textView =(TextView) findViewById(R.id.txt);

    String[] item = getResources().getStringArray(R.array.index);

    ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.activity_second,R.id.txt,item);
      listView.setAdapter(adapter);
    Typeface typeface = Typeface.createFromAsset(getAssets(),"font.ttf");
    textView.setTypeface(typeface);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(MainActivity.this,Second.class);
            intent.putExtra("page",i);
            startActivity(intent);
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}


问:
Input Hex into argv[1]
I have a program that takes input from argv[1] so I run it like

```<code>./myProgram Hello
</code>```

But I need to input hexadecimals instead of decimal/text so something like

```<code>./myProgram \x48\x65\x6c\x6c\x6f
</code>```

but the program takes that in as text instead of hexadecimals that form the word Hello.

I can't

```<code>python -c "print '\x48\x65\x6c\x6c\x6f'" | ./myProgram
</code>```

because the program takes the data in as argv[1]

How do I solve the problem? (I cannot modify the program)

答:
Continuing from the comment, not knowing exactly what was in ./myProgram made it a bit difficult to guess, but there are several logical things to try given what you reported.

As you point out, you need to take the hex input as the first argument to ./myProgram rather than passing it to the program on stdin. You correctly note that python -c "print '\x48\x65\x6c\x6c\x6f'" | ./myProgram fails for that reason. As you know, piping to a program redirects stdout of the initial process to stdin of the subsequent process, rather than as an argument to it.

That is where process substitution can help. When placing a process within $(...) (or the older format within backticks '...'), the output of the program is returned. Therefore, you can provide the output of python -c "print '\x48\x65\x6c\x6c\x6f'" as an argument by:

```<code>./myProgram $(python -c "print '\x48\x65\x6c\x6c\x6f'")
</code>```

Lastly, if myProgram is simply looking for hexadecimal input in string format, then there is no reason for multiple escapes. Simply providing a string representation of the hex number may be enough. Something like the following:

```<code>./myProgram 0x48656c6c6f
</code>```

I'm glad one of the suggestions was the "silver-bullet" you needed. Good luck with your shell use. Let us know if you have any further questions.

Title: Input Hex into argv[1]

Body:
I have a program that takes input from argv[1] so I run it like

./myProgram Hello

But I need to input hexadecimals instead of decimal/text so something like

./myProgram \x48\x65\x6c\x6c\x6f

but the program takes that in as text instead of hexadecimals that form the word Hello.

I can't

python -c "print '\x48\x65\x6c\x6c\x6f'" | ./myProgram

because the program takes the data in as argv[1]

How do I solve the problem? (I cannot modify the program)

Body:
Continuing from the comment, not knowing exactly what was in ./myProgram made it a bit difficult to guess, but there are several logical things to try given what you reported.

As you point out, you need to take the hex input as the first argument to ./myProgram rather than passing it to the program on stdin. You correctly note that python -c "print '\x48\x65\x6c\x6c\x6f'" | ./myProgram fails for that reason. As you know, piping to a program redirects stdout of the initial process to stdin of the subsequent process, rather than as an argument to it.

That is where process substitution can help. When placing a process within $(...) (or the older format within backticks '...'), the output of the program is returned. Therefore, you can provide the output of python -c "print '\x48\x65\x6c\x6c\x6f'" as an argument by:

./myProgram $(python -c "print '\x48\x65\x6c\x6c\x6f'")

Lastly, if myProgram is simply looking for hexadecimal input in string format, then there is no reason for multiple escapes. Simply providing a string representation of the hex number may be enough. Something like the following:

./myProgram 0x48656c6c6f

I'm glad one of the suggestions was the "silver-bullet" you needed. Good luck with your shell use. Let us know if you have any further questions.


问:
hiding a div with a value/ output from a php and css stament
I am going to use a button to set a value to a variable, I want to be able to hide a
 using the result from a PHP / CSS statement.

$day and $time would be set using the CSS set_date() function. Example below:

```<code>//Check if $day is within a business week/day
if ($day > 5) {
    //Hide the div
    //Check $time is within business hours and day
} else if ($time>=9 && $time<17) {
    //Show the div
    //Otherwise
} else {
   //Make div invisible
}
</code>```

That's how I want to do it but it isn't working as expected, any help would be much appreciated!

If necessary, here's the button resource:

答:
```<code>if ($day > 5) {
           $div='';
        }

        //check if it is within business hours and day
        //if yes show div
        elseif ($time>=9 && $time<17) {
          $div='<div> whatever inside</div>';
        }
        //if not make div not visable
        else {
          $div='';
        }

//if you use $div="<div>i am a div with a " inside </div>";
//then do this $div="<div>i am a div with a \" inside</div>"; the \allows the php to know it must not use the next character as code
</code>```

in your html

```<code><?php echo $div;?>
</code>```

Body:
I am going to use a button to set a value to a variable, I want to be able to hide a
 using the result from a PHP / CSS statement.

$day and $time would be set using the CSS set_date() function. Example below:

//Check if $day is within a business week/day
if ($day > 5) {
    //Hide the div
    //Check $time is within business hours and day
} else if ($time>=9 && $time<17) {
    //Show the div
    //Otherwise
} else {
   //Make div invisible
}

That's how I want to do it but it isn't working as expected, any help would be much appreciated!

If necessary, here's the button resource:

Body:
if ($day > 5) {
           $div='';
        }

        //check if it is within business hours and day
        //if yes show div
        elseif ($time>=9 && $time<17) {
          $div='<div> whatever inside</div>';
        }
        //if not make div not visable
        else {
          $div='';
        }

//if you use $div="<div>i am a div with a " inside </div>";
//then do this $div="<div>i am a div with a \" inside</div>"; the \allows the php to know it must not use the next character as code

in your html

<?php echo $div;?>


问:
How to Access DIV element inside Repeater using JQuery
So I have an ASP.NET repeater control with a textbox and a div with validation text that's hidden. I'm trying to display this div based on if special characters are entered in the textbox. I've managed to apply the jquery regex across all textboxes, but I'm trying to figure out how to apply the validation error to the textbox row where the input is being entered by the User, as I want the error div to display the message on this particular row. I can get it to work on the first row but since the repeater creates it's own control ID's in the HTML, I was wondering how to go about this. Here's my code:

```<code>$(function(){

$('[id*=txtbox1]').keyup(function()
{
    var Input = $(this).val();
    re = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi;
    var SplChar = re.test(Input);
    if(SplChar)
    {
        var replchar = Input.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
        $(this).val(replchar);
                    $('#ErrorDiv').show();
    }
});});

<asp:Repeater ID="rptItems" runat="server">
<ItemTemplate>
            <asp:textbox ID="txtbox1" runat="server" Text='<%# Eval("Questions") %>' />
            <div id="ErrorDiv" style="display: none;">No special characters</div>
</ItemTemplate>
</code>```

Any Suggestions ? Appreciate the help.

答: The problem which you are facing is because textbox-id's are unique. so only solution is to Select elements using getElementsByName or by their class name.

Body:
So I have an ASP.NET repeater control with a textbox and a div with validation text that's hidden. I'm trying to display this div based on if special characters are entered in the textbox. I've managed to apply the jquery regex across all textboxes, but I'm trying to figure out how to apply the validation error to the textbox row where the input is being entered by the User, as I want the error div to display the message on this particular row. I can get it to work on the first row but since the repeater creates it's own control ID's in the HTML, I was wondering how to go about this. Here's my code:

$(function(){

$('[id*=txtbox1]').keyup(function()
{
    var Input = $(this).val();
    re = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi;
    var SplChar = re.test(Input);
    if(SplChar)
    {
        var replchar = Input.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
        $(this).val(replchar);
                    $('#ErrorDiv').show();
    }
});});

<asp:Repeater ID="rptItems" runat="server">
<ItemTemplate>
            <asp:textbox ID="txtbox1" runat="server" Text='<%# Eval("Questions") %>' />

No special characters

</ItemTemplate>

Any Suggestions ? Appreciate the help.


问:
Java Thread Count doesn't work
Why is count 0? </p>

<p>I start the thread 1 then I start thread 2. Count should be 2000. But it shows count to be 0. Someone please explain in simple terms.     </p>

```<code>public class App {
    private int count = 0;

    public static void main(String[] args) {
        App app = new App();
        app.doWork();
    }

    public void doWork(){
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();

        System.out.println("Count is: " + count);
    }
}
</code>```

答:
You need to make the code block which increments the count as synchronized in order to avoid the race condition.

In addition to this there are multiple ways to solve this problem-

1. Hard code Thread.sleep(miliseconds value) in Main thread. [Not recommended]

2. join() the two threads to the main Thread so that the control returns to the main thread only when the execution of the two threads is complete.

```<code>public class App implements Runnable {
    private int count = 0;

    public static void main(String[] args) throws InterruptedException {
        App app = new App();
        app.doWork();
    }

    public void doWork() throws InterruptedException {
        Thread t1 = new Thread(this, "Thread - 1");
        Thread t2 = new Thread(this, "Thread - 2");

        t1.start();
        t2.start();

        //1.
        t1.join();
        t2.join();

        //2.
        //Thread.sleep(1000);

        System.out.println("Count is: " + count); // Count is: 2000
    }

    @Override
    public synchronized void run() {

        for (int i = 0; i < 1000; i++) {
            count++;
        }
    }
}
</code>```

Title: Java Thread Count doesn't work

Body:
Why is count 0?

I start the thread 1 then I start thread 2. Count should be 2000. But it shows count to be 0. Someone please explain in simple terms.

public class App {
    private int count = 0;

    public static void main(String[] args) {
        App app = new App();
        app.doWork();
    }

    public void doWork(){
        Thread t1 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });

        Thread t2 = new Thread(new Runnable(){
            public void run(){
                for(int i = 0;i < 10000;i++){
                    count++;
                }
            }
        });
        t1.start();
        t2.start();

        System.out.println("Count is: " + count);
    }
}

Body:
You need to make the code block which increments the count as synchronized in order to avoid the race condition.

In addition to this there are multiple ways to solve this problem-

1. Hard code Thread.sleep(miliseconds value) in Main thread. [Not recommended]

2. join() the two threads to the main Thread so that the control returns to the main thread only when the execution of the two threads is complete.

public class App implements Runnable {
    private int count = 0;

    public static void main(String[] args) throws InterruptedException {
        App app = new App();
        app.doWork();
    }

    public void doWork() throws InterruptedException {
        Thread t1 = new Thread(this, "Thread - 1");
        Thread t2 = new Thread(this, "Thread - 2");

        t1.start();
        t2.start();

        //1.
        t1.join();
        t2.join();

        //2.
        //Thread.sleep(1000);

        System.out.println("Count is: " + count); // Count is: 2000
    }

    @Override
    public synchronized void run() {

        for (int i = 0; i < 1000; i++) {
            count++;
        }
    }
}


问:
What Actionscript APIs will help to fetch more content at the end of animation
I have my own swf content. Now I want pull some adverts from my server which is to be played at the end. How can I do this without having the original fla file with which the content was created.

Maybe I need to create another swf containing the original swf content and then catching an event which indicates the end of animation of the original swf and then pulling the advert from the server.

But then what is the event that I should catch and which apis will help me request the server and then again start playing with the content from the server. I read some where that loadMovie is to be used, but not sure of the event and the sequence of things that needs to be done to achieve my goal

答:
"Maybe I need to create another swf containing the original swf content and then catching an event which indicates the end of animation of the original swf and then pulling the advert from the server."

Sounds about right, except that your new swf doesn't need to "contain" the first swf, you can simply load it.

You will need to dispatch an event when the first animation is complete. Since you don't have access to the original fla, it will depend on the type of the animation. If it's a frame based animation, it's all good, you'll just have to check for the last frame of the movie, otherwise you may be out of luck... Even if it's a frame based animation , you may still encounter problems, if the animation contains various MovieClips with different animation lengths. It still may be possible to find out when the end occurs but it may be a bit more complex and the solution not that pretty.

"which apis will help me request the server and then again start playing with the content from the server."
That would depend on the server and the type of content...

ContentLicense: CC BY-SA 2.5


问:
How can I use the same style on several TextBlock controls, but have each control using different bindings and triggers?
I'd like to have several TextBlocks generally looking the same, but each needs to react on another trigger and in another way. I've tried to use a common style (MyTextBlockStyle) and add triggers later. But I get allways error meesages like "the property 'style' has been declared twice" or simillar.

To explain what I mean, I've made an example with 3 TextBlocks. 2 of them are bound to each a different CheckBox, and each triggering a different property (displayed text vs. foreground color). A third TextBlock shall change its background color depending of the content of a TextbBox. How can I achieve something like this?

```<code><UserControl.Resources>
        <Style x:Key="MyTextBlockStyle" TargetType="TextBlock">
            <Setter Property="Background" Value="Yellow"/>
            <Setter Property="Foreground" Value="Black"/>
            <Setter Property="Margin" Value="10"/>
            <Setter Property="Padding" Value="5"/>
        </Style>
</UserControl.Resources>

<Grid >
        <StackPanel Margin="10">
            <CheckBox x:Name="CheckBox01" Content="Change Background of TextBlock 1" IsChecked="False" Foreground="White" Margin="5" />
            <CheckBox x:Name="CheckBox02" Content="Change Background of TextBlock 2" IsChecked="False" Foreground="White" Margin="5" />
            <TextBox x:Name="TextBox03" Padding="10" Background="White" Text="Enter Text here ..." Tooltip="Change Background of TextBlock 3"/>
            <TextBlock Style="{StaticResource MyTextBlockStyle}" >
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Setter Property="Text" Value="No" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=CheckBox01, Path=IsChecked}" Value="True">
                                <Setter Property="Text" Value="Yes!" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
            <TextBlock Style="{Static Resource MyTextBlockStyle}" Text="Something different">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Setter Property="Foreground" Value="Red" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=CheckBox02, Path=IsChecked}" Value="True">
                                <Setter Property="Foreground" Value="Green" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
            <TextBlock Style="{Static Resource MyTextBlockStyle}" Text="Anything else">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Setter Property="Background" Value="Yellow" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=TextBox03, Path=Text}" Value="">
                                <Setter Property="Background" Value="Blue" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </StackPanel>
</Grid >
</code>```

答:
You are looking for the BasedOn Property.  It gets me all the time.</p>

```<code><TextBlock>
            <TextBlock.Style>
                <Style TargetType="TextBlock" BasedOn="MyTextBlockStyle">
                    <Setter Property="Text" Value="No" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=CheckBox01, Path=IsChecked}" Value="True">
                            <Setter Property="Text" Value="Yes!" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>
</code>```

Body:
I'd like to have several TextBlocks generally looking the same, but each needs to react on another trigger and in another way. I've tried to use a common style (MyTextBlockStyle) and add triggers later. But I get allways error meesages like "the property 'style' has been declared twice" or simillar.

To explain what I mean, I've made an example with 3 TextBlocks. 2 of them are bound to each a different CheckBox, and each triggering a different property (displayed text vs. foreground color). A third TextBlock shall change its background color depending of the content of a TextbBox. How can I achieve something like this?

<UserControl.Resources>

</UserControl.Resources>

<Grid >
        <StackPanel Margin="10">
            <CheckBox x:Name="CheckBox01" Content="Change Background of TextBlock 1" IsChecked="False" Foreground="White" Margin="5" />
            <CheckBox x:Name="CheckBox02" Content="Change Background of TextBlock 2" IsChecked="False" Foreground="White" Margin="5" />
            <TextBox x:Name="TextBox03" Padding="10" Background="White" Text="Enter Text here ..." Tooltip="Change Background of TextBlock 3"/>
            <TextBlock Style="{StaticResource MyTextBlockStyle}" >
                <TextBlock.Style>

                    </Style>
                </TextBlock.Style>
            </TextBlock>
            <TextBlock Style="{Static Resource MyTextBlockStyle}" Text="Something different">
                <TextBlock.Style>

                    </Style>
                </TextBlock.Style>
            </TextBlock>
            <TextBlock Style="{Static Resource MyTextBlockStyle}" Text="Anything else">
                <TextBlock.Style>

                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </StackPanel>
</Grid >

Body:
You are looking for the BasedOn Property.  It gets me all the time.

<TextBlock>
            <TextBlock.Style>
                <Style TargetType="TextBlock" BasedOn="MyTextBlockStyle">
                    <Setter Property="Text" Value="No" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=CheckBox01, Path=IsChecked}" Value="True">
                            <Setter Property="Text" Value="Yes!" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>


问:
Get(int) asp.net wep api
I really confused with my web api now. Here is my code for Get method:

```<code>public Employee Get(int id)
{
            using (EmployeeDBEntities entities = new EmployeeDBEntities())
            {
                return entities.Employees.FirstOrDefault(e => e.ID==id);
            }
        }
</code>```

And I use jquery ajax to get that:

```<code>$(document).ready(function () {
    $('#btn').click(function () {
        $.ajax({
            url: 'api/employees/1',
            method: 'GET',

            success: function (data) {
                $('#ul').empty();
                $.each(data, function (index, value) {
                    var row = $('<tr><td>' + value.ID + '</td><td>'
                        + value.FirstName + '</td><td>'
                        + value.LastName + '</td><td>'
                        + value.Gender + '</td><td>'
                        + value.Salary + '</td></tr>');
                    $('#ul').append(row);
                });
            }
        });
    });
});
</code>```

when I ran it, it just returned lots of 'undefined'. However when I run "http://localhost:52178/api/employees/1" in browser, I got the right xml I want. Can anyone help me with that?

答: Try updating the URL in your Ajax call to "/api/employees/1" - which has the leading slash</p>

Title: Get(int) asp.net wep api

Body:
I really confused with my web api now. Here is my code for Get method:

public Employee Get(int id)
{
            using (EmployeeDBEntities entities = new EmployeeDBEntities())
            {
                return entities.Employees.FirstOrDefault(e => e.ID==id);
            }
        }

And I use jquery ajax to get that:

$(document).ready(function () {
    $('#btn').click(function () {
        $.ajax({
            url: 'api/employees/1',
            method: 'GET',

            success: function (data) {
                $('#ul').empty();
                $.each(data, function (index, value) {
                    var row = $('
' + value.ID + '	'
                        + value.FirstName + '	'
                        + value.LastName + '	'
                        + value.Gender + '	'
                        + value.Salary + '
');
                    $('#ul').append(row);
                });
            }
        });
    });
});

when I ran it, it just returned lots of 'undefined'. However when I run "http://localhost:52178/api/employees/1" in browser, I got the right xml I want. Can anyone help me with that?


问:
Java Android FCM sending message to user Server returned HTTP response code
I did this :

```<code>public class PushNotifictionHelper {
    public final static String AUTH_KEY_FCM = "AIzaSyD63pfTvnwhe9WVuIe.........";
    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    public static String sendPushNotification(String deviceToken)
            throws IOException, JSONException {
        String result = "";
        URL url = new URL(API_URL_FCM);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
        conn.setRequestProperty("Content-Type", "application/json");

        JSONObject json = new JSONObject();

        json.put("to", deviceToken.trim());
        JSONObject info = new JSONObject();
        info.put("title", "notification title"); // Notification title
        info.put("body", "message body"); // Notification
        // body
        json.put("notification", info);
        try {
            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            result = "OK";
        } catch (Exception e) {
            e.printStackTrace();
            result = "BAD";
        }
        System.out.println("GCM Notification is sent successfully");

        return result;

    }

    public static void main(String [] args){
        try {
            PushNotifictionHelper.sendPushNotification("ep51x3Ckmig:APA91bG4PdoJC7zGlV0JPmCA49jmqJCkeSPH1QzF9byxdH1nRlFOVyAi9ppO2ygoSpp8s44o1oGO8n-HCJDB_oZAZ6WCwFD2a9yAFmKIpKhmPXakeLf-ktqPnzwf-GFziv7_nMdVPIci");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

And when I run this in console I see

```<code>java.io.IOException: Server returned HTTP response code: 401 for URL: https://fcm.googleapis.com/fcm/send
</code>```

an AUTH_KEY_FCM I get from web from this:

```<code>Klucz interfejsu Web API AIzaSyD63pfTvnwhe9WVuIe.........
</code>```

答:
The 401 error refers to an Authentication error. From the docs:

The sender account used to send a message couldn't be authenticated. Possible causes are:

Authorization header missing or with invalid syntax in HTTP request.

Invalid project number sent as key.

Key valid but with FCM service disabled.

Request originated from a server not whitelisted in the Server key IPs.

Check that the token you're sending inside the Authentication header is the correct Server key associated with your project. See Checking the validity of a Server key for details.

When using FCM, you should always make use of the Server Key (not the Web API Key) seen in the Cloud Messaging Tab in your Firebase Console.

Body:
I did this :

public class PushNotifictionHelper {
    public final static String AUTH_KEY_FCM = "AIzaSyD63pfTvnwhe9WVuIe.........";
    public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

    public static String sendPushNotification(String deviceToken)
            throws IOException, JSONException {
        String result = "";
        URL url = new URL(API_URL_FCM);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
        conn.setRequestProperty("Content-Type", "application/json");

        JSONObject json = new JSONObject();

        json.put("to", deviceToken.trim());
        JSONObject info = new JSONObject();
        info.put("title", "notification title"); // Notification title
        info.put("body", "message body"); // Notification
        // body
        json.put("notification", info);
        try {
            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(json.toString());
            wr.flush();

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            result = "OK";
        } catch (Exception e) {
            e.printStackTrace();
            result = "BAD";
        }
        System.out.println("GCM Notification is sent successfully");

        return result;

    }

    public static void main(String [] args){
        try {
            PushNotifictionHelper.sendPushNotification("ep51x3Ckmig:APA91bG4PdoJC7zGlV0JPmCA49jmqJCkeSPH1QzF9byxdH1nRlFOVyAi9ppO2ygoSpp8s44o1oGO8n-HCJDB_oZAZ6WCwFD2a9yAFmKIpKhmPXakeLf-ktqPnzwf-GFziv7_nMdVPIci");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

And when I run this in console I see

java.io.IOException: Server returned HTTP response code: 401 for URL: https://fcm.googleapis.com/fcm/send

an AUTH_KEY_FCM I get from web from this:

Klucz interfejsu Web API AIzaSyD63pfTvnwhe9WVuIe.........


问:
How to handle api version cleanly in url in Play Framework (2.4.x)?
So currently my routes file is a series of routes with a hardcoded version.

```<code>GET    /v1/companies/$id<[-a-zA-Z0-9]+>/etwasX    controllers.Company.etwasX(id:String, q: Option[String])
GET    /v1/companies/$id<[-a-zA-Z0-9]+>/etwasY    controllers.Company.etwasY(id:String, q: Option[String])
</code>```

I have about some 30 routes defined. Now I would like to support different versions. I thought I could simply do this:

```<code>GET    /v<[0-9]+>/companies/$id<[-a-zA-Z0-9]+>/etwasX    controllers.Company.etwasX(id:String, q: Option[String])
</code>```

But it doesn't work, and if I define it with a $

```<code>GET    /v$version<[0-9]+>/companies/$id<[-a-zA-Z0-9]+>/etwasX    controllers.Company.etwasX(id:String, q: Option[String])
</code>```

Then it complains I don't have a version parameter in the controller method. Is there any other way beside specifying the version in every controller method?

If not, is there a way I could somehow automatically generate the routes for all the supported versions (assuming for now that they would have the same definition)?

答:
There is a lot of discussion about if HTTP (REST) APIs should be versioned using the URL or not, using a path prefix like you are doing. But, if you decide that URL versioning is the right answer to your case, you can more easily achieve that by splitting your routes in multiple files.

That way, you would have the following conf/routes file:

```<code># SomeController.index is an endpoint which is not versioned
GET    /      controllers.SomeController.index
->     /v1    api.Routes
</code>```

And also, you would have a conf/api.routes file with the following:

```<code>GET    /companies/$id<[-a-zA-Z0-9]+>/etwasX    controllers.Company.etwasX(id:String, q: Option[String])
GET    /companies/$id<[-a-zA-Z0-9]+>/etwasY    controllers.Company.etwasY(id:String, q: Option[String])
</code>```

What we are doing here is basically creating a path (v1) to the API routes defined in api.routes. Then, when you decide that you need a v2, you just need to edit your sub-routes prefix.

Body:
So currently my routes file is a series of routes with a hardcoded version.

GET    /v1/companies/$id<[-a-zA-Z0-9]+>/etwasX    controllers.Company.etwasX(id:String, q: Option[String])
GET    /v1/companies/$id<[-a-zA-Z0-9]+>/etwasY    controllers.Company.etwasY(id:String, q: Option[String])

I have about some 30 routes defined. Now I would like to support different versions. I thought I could simply do this:

GET    /v<[0-9]+>/companies/$id<[-a-zA-Z0-9]+>/etwasX    controllers.Company.etwasX(id:String, q: Option[String])

But it doesn't work, and if I define it with a $

GET    /v$version<[0-9]+>/companies/$id<[-a-zA-Z0-9]+>/etwasX    controllers.Company.etwasX(id:String, q: Option[String])

Then it complains I don't have a version parameter in the controller method. Is there any other way beside specifying the version in every controller method?

If not, is there a way I could somehow automatically generate the routes for all the supported versions (assuming for now that they would have the same definition)?

Body:
There is a lot of discussion about if HTTP (REST) APIs should be versioned using the URL or not, using a path prefix like you are doing. But, if you decide that URL versioning is the right answer to your case, you can more easily achieve that by splitting your routes in multiple files.

That way, you would have the following conf/routes file:

# SomeController.index is an endpoint which is not versioned
GET    /      controllers.SomeController.index
->     /v1    api.Routes

And also, you would have a conf/api.routes file with the following:

GET    /companies/$id<[-a-zA-Z0-9]+>/etwasX    controllers.Company.etwasX(id:String, q: Option[String])
GET    /companies/$id<[-a-zA-Z0-9]+>/etwasY    controllers.Company.etwasY(id:String, q: Option[String])

What we are doing here is basically creating a path (v1) to the API routes defined in api.routes. Then, when you decide that you need a v2, you just need to edit your sub-routes prefix.


问:
SQL Server PIVOT - Removing Null Values to 0
very quick question, I would like to remove nulls and it seems when I try to add ISNULL(LoanAmount, 0) in @strQuery it gives me an error.  And it is really important for me to remove those null values and replace it with 0,

Here is my code:

```<code>DECLARE @LoanTypeDesc AS NVARCHAR(MAX),
    @strQuery  AS NVARCHAR(MAX),
    @strColumn AS NVARCHAR(MAX)

SELECT @LoanTypeDesc = STUFF((SELECT ',' + QUOTENAME(lt.[Description])
                FROM LoanType lt
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

SET @strQuery = 'SELECT *
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'

EXECUTE (@strQuery)
</code>```

Any help would be appreciated.

答:
This will remove null values. I have created list of Pivoted columns with handling NULL in @SELECT_COLUMNS. And if you want you can append any other columns like EmployeeID  to @SELECT_COLUMNS.

```<code>DECLARE @LoanTypeDesc AS NVARCHAR(MAX),
    @strQuery  AS NVARCHAR(MAX),
    @strColumn AS NVARCHAR(MAX)

--Creating column list with appending ISNULL
DECLARE @SELECT_COLUMNS VARCHAR(MAX)='';
SELECT @SELECT_COLUMNS = @SELECT_COLUMNS+ 'ISNULL( '+ QUOTENAME(lt.[Description])  +',0),'
                FROM LoanType lt
SELECT @SELECT_COLUMNS= SUBSTRING(@SELECT_COLUMNS,1,LEN(@SELECT_COLUMNS)-1);

SELECT @LoanTypeDesc = STUFF((SELECT ',' + QUOTENAME(lt.[Description])
                FROM LoanType lt
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

--Making Select columns from @SELECT_COLUMNS instead of *
SET @strQuery = 'SELECT '+@SELECT_COLUMNS +'
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'

EXECUTE (@strQuery)
</code>```

Body:
very quick question, I would like to remove nulls and it seems when I try to add ISNULL(LoanAmount, 0) in @strQuery it gives me an error.  And it is really important for me to remove those null values and replace it with 0,

Here is my code:

DECLARE @LoanTypeDesc AS NVARCHAR(MAX),
    @strQuery  AS NVARCHAR(MAX),
    @strColumn AS NVARCHAR(MAX)

SELECT @LoanTypeDesc = STUFF((SELECT ',' + QUOTENAME(lt.[Description])
                FROM LoanType lt
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

SET @strQuery = 'SELECT *
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'

EXECUTE (@strQuery)

Any help would be appreciated.

Body:
This will remove null values. I have created list of Pivoted columns with handling NULL in @SELECT_COLUMNS. And if you want you can append any other columns like EmployeeID  to @SELECT_COLUMNS.

DECLARE @LoanTypeDesc AS NVARCHAR(MAX),
    @strQuery  AS NVARCHAR(MAX),
    @strColumn AS NVARCHAR(MAX)

--Creating column list with appending ISNULL
DECLARE @SELECT_COLUMNS VARCHAR(MAX)='';
SELECT @SELECT_COLUMNS = @SELECT_COLUMNS+ 'ISNULL( '+ QUOTENAME(lt.[Description])  +',0),'
                FROM LoanType lt
SELECT @SELECT_COLUMNS= SUBSTRING(@SELECT_COLUMNS,1,LEN(@SELECT_COLUMNS)-1);

SELECT @LoanTypeDesc = STUFF((SELECT ',' + QUOTENAME(lt.[Description])
                FROM LoanType lt
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

--Making Select columns from @SELECT_COLUMNS instead of *
SET @strQuery = 'SELECT '+@SELECT_COLUMNS +'
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'

EXECUTE (@strQuery)


问:
Rails View DRYness - Do you set variables in the view or just make clean methods?
I have a view in which I have the same link 3 times (actual view is large):

```<code>%h1= link_to "Title", model_path(@model, :class => "lightbox")
= link_to "Check it out", model_path(@model, :class => "lightbox")
%footer= link_to "Last time", model_path(@model, :class => "lightbox")
</code>```

That model_path(@model, :class => "lightbox") call, though fairly clean, can be made even leaner wrapping it in this (maybe you had some more options, so doing this was worthwhile):

```<code>def popup_model_path(model)
  model_path(model, :class => "lightbox")
end
</code>```

My question is, I am having to recalculate that path 3 times in a view.  What is the preferred way of a) DRYing this up and b) optimizing performance?

I think setting variables at the top of the view might be a good idea here:

```<code>- path = model_path(@model, :class => "lightbox")
-# ... rest of view
</code>```

It's almost like mustache in the end then.  What are your thoughts?

答:
I really hate putting variables in the view. I would change your helper to

```<code>def popup_model_path(model)
  @model_path ||= {}
  @model_path[model] ||= model_path(model, :class => "lightbox")
end
</code>```

to "memoize" it, and just keep the three function calls.

Body:
I have a view in which I have the same link 3 times (actual view is large):

%h1= link_to "Title", model_path(@model, :class => "lightbox")
= link_to "Check it out", model_path(@model, :class => "lightbox")
%footer= link_to "Last time", model_path(@model, :class => "lightbox")

That model_path(@model, :class => "lightbox") call, though fairly clean, can be made even leaner wrapping it in this (maybe you had some more options, so doing this was worthwhile):

def popup_model_path(model)
  model_path(model, :class => "lightbox")
end

My question is, I am having to recalculate that path 3 times in a view.  What is the preferred way of a) DRYing this up and b) optimizing performance?

I think setting variables at the top of the view might be a good idea here:

- path = model_path(@model, :class => "lightbox")
-# ... rest of view

It's almost like mustache in the end then.  What are your thoughts?

Body:
I really hate putting variables in the view. I would change your helper to

def popup_model_path(model)
  @model_path ||= {}
  @model_path[model] ||= model_path(model, :class => "lightbox")
end

to "memoize" it, and just keep the three function calls.


问:
Render the same template with different text?
I have about 4-5 templates for my Django project. I want to use each template across about 10 pages(with 10 different sets of content/text) each.

I've been using contexts to fill out the relevant content on each page when it is rendered.

However, I'm not sure about any potential performance loss because the content is quite large. Is there a neat and efficient way to render one template with content relevant to a link clicked on a previous page.

what I'm currently doing:

index.html

```<code><div class='well well-sm well-md well-lg'>

<h1> {{variable1}} </h1>

</div>
</code>```

views.py

```<code>def page1(request):

   variable1 = 'Long text for each variable. Many variables on each page so
   lots of long text overall. '

   return render(request, 'index/base.html', {'variable': variable1})

def page2(request):

   variable1 = 'More long text. '

   return render(request, 'index/base.html', {'variable': variable1})
</code>```

Basically I want to know if there is a way of doing the above without having to use contexts. Or will I have to create a template for each page?

答:
You need to solve in 2 steps.

Determine previous page, so that you choose appropriate text.

You can solve this in the view. Just set some context variable to be passed to templates. I believe this is not easy to do in template processing, view is better.

Sample code

```<code>def page(request):
   if previous_page == "some page 1"
       page_type = 1
   elif previous_page == "some page 2"
       page_type = 2
   return render(request, 'index/base.html', {'page_type': page_type})
</code>```

Then in template use {%include%} tag to use appropriate template.

Sample index.html

```<code><div class='well well-sm well-md well-lg'>

{% if page_type == 1 %}
    {%include "page_type1.html"%}
{%else%}
    {%include "page_type2.html"%}
{%endif
</div>
</code>```

You need to write 2 templates page_type1.html and page_type2.html for render required html.

Body:
I have about 4-5 templates for my Django project. I want to use each template across about 10 pages(with 10 different sets of content/text) each.

I've been using contexts to fill out the relevant content on each page when it is rendered.

However, I'm not sure about any potential performance loss because the content is quite large. Is there a neat and efficient way to render one template with content relevant to a link clicked on a previous page.

what I'm currently doing:

index.html

 {{variable1}}

views.py

def page1(request):

   variable1 = 'Long text for each variable. Many variables on each page so
   lots of long text overall. '

   return render(request, 'index/base.html', {'variable': variable1})

def page2(request):

   variable1 = 'More long text. '

   return render(request, 'index/base.html', {'variable': variable1})

Basically I want to know if there is a way of doing the above without having to use contexts. Or will I have to create a template for each page?

Body:
You need to solve in 2 steps.

Determine previous page, so that you choose appropriate text.

You can solve this in the view. Just set some context variable to be passed to templates. I believe this is not easy to do in template processing, view is better.

Sample code

def page(request):
   if previous_page == "some page 1"
       page_type = 1
   elif previous_page == "some page 2"
       page_type = 2
   return render(request, 'index/base.html', {'page_type': page_type})

Then in template use {%include%} tag to use appropriate template.

Sample index.html

<div class='well well-sm well-md well-lg'>

{% if page_type == 1 %}
    {%include "page_type1.html"%}
{%else%}
    {%include "page_type2.html"%}
{%endif
</div>

You need to write 2 templates page_type1.html and page_type2.html for render required html.


问:
How to fix the while loop in this program?
Write a python program that will take 3 lists:

Name    Wage    Hours
Juan    7.50    35
Rae     11.00   41
Ivanna  18.25   26
Lilly   9.25    35
Robert  11.10   45

and use this logic:

An employee gets overtime when they have worked more than 40 hours

Overtime pay is calculated using this formula:

Gross Pay = (35*Wage) + ((Hours-35)*Wage*1.5)

Regular pay is calculated using this formula:

Gross Pay = (Hours*Wage)

Use a loop to process these lists.

Print each employee, their wages, Hours and gross pay.

I'm running this program and I have the for loop. The input works fine, but the while loop that its supposed to have the same output is not giving me any output at all. Here's my code.

```<code>`Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
   GP = 0
   if(Hours[X] > 40):
       GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
   else:
       GP = Hours[X] * Wage[X]
   print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)

Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)`
</code>```

my output is going as

```<code>Name    Wage    Hours   GP
Juan     7.5     35      262.5
Rae      11      41      484.0
Ivanna   18.25   26      474.5
Lilly    9.25    35      323.75
Robert   11.1    45      555.0
Name    Wage    Hours   GP
Juan     7.5     35      555.0
</code>```

I don't know where the error is in the while loop.

答:
Have to follow python code indented and need to give proper while loop condition with (increment/decrement/boolean). As your code need to increment the value of Y.

```<code>Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
    GP = 0
    if(Hours[X] > 40):
        GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
    else:
        GP = Hours[X] * Wage[X]
    print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)

Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y<counter):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
    print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
    Y=Y+1
</code>```

Body:
Write a python program that will take 3 lists:

Name    Wage    Hours
Juan    7.50    35
Rae     11.00   41
Ivanna  18.25   26
Lilly   9.25    35
Robert  11.10   45

and use this logic:

An employee gets overtime when they have worked more than 40 hours

Overtime pay is calculated using this formula:

Gross Pay = (35*Wage) + ((Hours-35)*Wage*1.5)

Regular pay is calculated using this formula:

Gross Pay = (Hours*Wage)

Use a loop to process these lists.

Print each employee, their wages, Hours and gross pay.

I'm running this program and I have the for loop. The input works fine, but the while loop that its supposed to have the same output is not giving me any output at all. Here's my code.

`Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
   GP = 0
   if(Hours[X] > 40):
       GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
   else:
       GP = Hours[X] * Wage[X]
   print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)

Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)`

my output is going as

Name    Wage    Hours   GP
Juan     7.5     35      262.5
Rae      11      41      484.0
Ivanna   18.25   26      474.5
Lilly    9.25    35      323.75
Robert   11.1    45      555.0
Name    Wage    Hours   GP
Juan     7.5     35      555.0

I don't know where the error is in the while loop.

Body:
Have to follow python code indented and need to give proper while loop condition with (increment/decrement/boolean). As your code need to increment the value of Y.

Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
for X in range(5):
    GP = 0
    if(Hours[X] > 40):
        GP = (35*Wage[X]) + ((Hours[X]-35)*Wage[X]*1.5)
    else:
        GP = Hours[X] * Wage[X]
    print (Name[X],"\t", Wage[X],"\t", Hours[X],"\t", GP)

Name = ["Juan","Rae","Ivanna", "Lilly", "Robert"]
Hours = [35,41,26,35,45]
Wage = [7.5,11,18.25,9.25,11.1]
print ("Name\tWage\tHours\tGP")
counter = 5
Y = 0
while (Y<counter):
    if (Hours[Y] > 40):
        GP = (35*Wage[Y]) + ((Hours[Y]-35)*Wage[Y]*1.5)
    else:
        GP = Hours[Y] * Wage[Y]
    print (Name[Y],"\t", Wage[Y],"\t", Hours[Y],"\t", GP)
    Y=Y+1


问:
unresolved variable d3.event.translate and d3.event.scale
I am trying to implement the zoom functionality in d3. It is implemented in angular 2 and D3 version is 3.5.17.

```<code>//This is where I initialize the tree layout
ngOnInit() {
    this.tree = d3.layout.tree().size([this.height, this.width]);
    this.svg = d3.select("#body").append("div")
      .classed("svg-container", true)
      .append("svg")
      .attr("preserveAspectRatio", "xMinYMin meet")
      .attr("viewBox", "0 0 " + this.width + " " + this.height)
      .attr("width", 10 * (this.width + this.margin.right + this.margin.left))
      .attr("height", this.height + this.margin.top + this.margin.bottom)
      .call(d3.behavior.zoom().scaleExtent([-8, 8]).on("zoom", this.zoom))
      .classed("svg-content-responsive", true)
}

//following is the zoom function
public zoom = () => {
    this.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
  };
</code>```

However, I get compilation error 'unresolved variable d3.event.translate and d3.event.scale' for d3.event.translate and d3.event.scale variables. I am wondering why is the error or if I am something missing.

答:
Not sure if this is the answer, but it might be related to the bundler that you are using. There is a "gotcha" listed in the D3v4 documentation (yes, I know you're using v3.x.x, but it might still apply) regarding the d3.event within bundlers:

https://github.com/d3/d3-selection/blob/master/README.md#event

Body:
I am trying to implement the zoom functionality in d3. It is implemented in angular 2 and D3 version is 3.5.17.

//This is where I initialize the tree layout
ngOnInit() {
    this.tree = d3.layout.tree().size([this.height, this.width]);
    this.svg = d3.select("#body").append("div")
      .classed("svg-container", true)
      .append("svg")
      .attr("preserveAspectRatio", "xMinYMin meet")
      .attr("viewBox", "0 0 " + this.width + " " + this.height)
      .attr("width", 10 * (this.width + this.margin.right + this.margin.left))
      .attr("height", this.height + this.margin.top + this.margin.bottom)
      .call(d3.behavior.zoom().scaleExtent([-8, 8]).on("zoom", this.zoom))
      .classed("svg-content-responsive", true)
}

//following is the zoom function
public zoom = () => {
    this.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
  };

However, I get compilation error 'unresolved variable d3.event.translate and d3.event.scale' for d3.event.translate and d3.event.scale variables. I am wondering why is the error or if I am something missing.


问:
Elixir: Trying to Write a Map to CSV, Being Written as Stream Results
I've been scratching my head on this one for a while. I am trying to write a program which outputs the frequency of every word in a given text file to a .csv file. I have succeeded in creating functions that find the frequency of each word and output the result of this as a map, but my tocsv function writes the results as Stream results for some reason and I cannot figure out why, or how to avoid this. Here is my code:

```<code>defmodule WordFrequency do

  def wordCount(readFile) do
     readFile
     |> words
     |> count
     |> tocsv
  end

  defp words(file) do
    file
    |> File.stream!
    |> Stream.map(&String.trim_trailing(&1))
    |> Stream.map(&String.split(&1,~r{[^A-Za-z0-9_]}))
    |> Enum.to_list
    |> List.flatten

  end

  defp count(words) when is_list(words) do
    Enum.reduce(words, %{}, &update_count/2)
  end

  defp update_count(word, acc) do
    Map.update acc, String.to_atom(word), 1, &(&1 + 1)
  end

  defp tocsv(map) do
    file = File.open!("test.csv", [:write, :utf8])
    map
    |> IO.inspect
    |> Enum.map(&CSV.encode(&1))
    |> Enum.each(&IO.inspect(file, &1, []))
  end

end
</code>```

The results of count (it's a test file) are:

```<code>bitterness: 1, fan: 1, respiration: 1, radiator: 1, ceiling: 1, run: 1,
  duck: 1, roundess: 1, terrorism: 1, she: 1, over: 1, equipment: 2, test: 1,
  freshness: 1, feminism: 1, bucket: 1, goodness: 1, manliness: 1,
  reflection: 1, uncomfortable: 1, tourism: 1, house: 1, ableism: 1, stairs: 1,
  heroism: 1, sadness: 1, socialism: 1, fruit: 1, dogs: 1, mechanism: 1,
  symbolism: 1, predilection: 1, up: 1, sedition: 1, faithfulness: 1,
  fruition: 1, criticism: 1, conformation: 1, extradition: 1, braveness: 1,
  ionization: 1, indigestion: 1, bubble: 1, introspection: 1, liquid: 1,
  apartment: 1, deep: 1, department: 1, centralization: 1, bitter: 1, ...}
</code>```

So I know that I'm not passing a stream to my tocsv function, but something happens in tocsv that converts it to a stream and doesn't convert it to a writeable format before outputting to the csv file. Anyone have any idea how I can make a workaround to this? I am using this CSV module: https://github.com/beatrichartz/csv

Thanks!

答:
There is an example of producing the CSV in the README of the CSV module you use:

```<code>file = File.open!("test.csv", [:write, :utf8])
table_data |> CSV.encode |> Enum.each(&IO.write(file, &1))
</code>```

Please note, that IO.write/2 writes the bytes to the device, while IO.inspect/3 inspects the second argument according to the given options using the IO device. Also, CSV.encode/1 expects a two-dimensional list.

That said, you probably should stick with IO.write/2 as mentioned in the example, and produce a 2d list in count rather that a Map:

```<code>defp count(words) when is_list(words) do
  words
  |> Enum.reduce(%{}, &update_count/2)
  |> Enum.reduce([], fn {k, v}, acc -> [[k, v] | acc] end)
end

defp tocsv(map) do
  file = File.open!("test.csv", [:write, :utf8])

  map
  |> IO.inspect
  |> CSV.encode
  |> Enum.each(&IO.write(file, &1))
end
</code>```

In such an simple case, I would just use bare Elixir to produce a file, though (assuming count returns a map, as in your original code):

```<code>defp tocsv(map) do
  File.open("test.csv", [:write, :utf8], fn(file) ->
    Enum.each(map, &IO.write(file, Enum.join(Tuple.to_list(&1), ?,) <> "\n"))
  end)
end
</code>```

Or, even simpler:

```<code>defp tocsv(map) do
  File.write!("test.csv",
     map
     |> Enum.map(Enum.join(&Tuple.to_list(&1), ?,))
     |> Enum.join("\n"))
end
</code>```

Body:
I've been scratching my head on this one for a while. I am trying to write a program which outputs the frequency of every word in a given text file to a .csv file. I have succeeded in creating functions that find the frequency of each word and output the result of this as a map, but my tocsv function writes the results as Stream results for some reason and I cannot figure out why, or how to avoid this. Here is my code:

defmodule WordFrequency do

  def wordCount(readFile) do
     readFile
     |> words
     |> count
     |> tocsv
  end

  defp words(file) do
    file
    |> File.stream!
    |> Stream.map(&String.trim_trailing(&1))
    |> Stream.map(&String.split(&1,~r{[^A-Za-z0-9_]}))
    |> Enum.to_list
    |> List.flatten

  end

  defp count(words) when is_list(words) do
    Enum.reduce(words, %{}, &update_count/2)
  end

  defp update_count(word, acc) do
    Map.update acc, String.to_atom(word), 1, &(&1 + 1)
  end

  defp tocsv(map) do
    file = File.open!("test.csv", [:write, :utf8])
    map
    |> IO.inspect
    |> Enum.map(&CSV.encode(&1))
    |> Enum.each(&IO.inspect(file, &1, []))
  end

end

The results of count (it's a test file) are:

bitterness: 1, fan: 1, respiration: 1, radiator: 1, ceiling: 1, run: 1,
  duck: 1, roundess: 1, terrorism: 1, she: 1, over: 1, equipment: 2, test: 1,
  freshness: 1, feminism: 1, bucket: 1, goodness: 1, manliness: 1,
  reflection: 1, uncomfortable: 1, tourism: 1, house: 1, ableism: 1, stairs: 1,
  heroism: 1, sadness: 1, socialism: 1, fruit: 1, dogs: 1, mechanism: 1,
  symbolism: 1, predilection: 1, up: 1, sedition: 1, faithfulness: 1,
  fruition: 1, criticism: 1, conformation: 1, extradition: 1, braveness: 1,
  ionization: 1, indigestion: 1, bubble: 1, introspection: 1, liquid: 1,
  apartment: 1, deep: 1, department: 1, centralization: 1, bitter: 1, ...}

So I know that I'm not passing a stream to my tocsv function, but something happens in tocsv that converts it to a stream and doesn't convert it to a writeable format before outputting to the csv file. Anyone have any idea how I can make a workaround to this? I am using this CSV module: https://github.com/beatrichartz/csv

Thanks!

Body:
There is an example of producing the CSV in the README of the CSV module you use:

file = File.open!("test.csv", [:write, :utf8])
table_data |> CSV.encode |> Enum.each(&IO.write(file, &1))

Please note, that IO.write/2 writes the bytes to the device, while IO.inspect/3 inspects the second argument according to the given options using the IO device. Also, CSV.encode/1 expects a two-dimensional list.

That said, you probably should stick with IO.write/2 as mentioned in the example, and produce a 2d list in count rather that a Map:

defp count(words) when is_list(words) do
  words
  |> Enum.reduce(%{}, &update_count/2)
  |> Enum.reduce([], fn {k, v}, acc -> [[k, v] | acc] end)
end

defp tocsv(map) do
  file = File.open!("test.csv", [:write, :utf8])

  map
  |> IO.inspect
  |> CSV.encode
  |> Enum.each(&IO.write(file, &1))
end

In such an simple case, I would just use bare Elixir to produce a file, though (assuming count returns a map, as in your original code):

defp tocsv(map) do
  File.open("test.csv", [:write, :utf8], fn(file) ->
    Enum.each(map, &IO.write(file, Enum.join(Tuple.to_list(&1), ?,) <> "\n"))
  end)
end

Or, even simpler:

defp tocsv(map) do
  File.write!("test.csv",
     map
     |> Enum.map(Enum.join(&Tuple.to_list(&1), ?,))
     |> Enum.join("\n"))
end

ContentLicense: CC BY-SA 4.0


问:
Show Log From AVD
I am testing my application on an Android Virtual Device (AVD) and have noticed my app crashes after a certain button is pressed. The diolouge is Unfortunately, myApplication has stopped. without any option to report the crash. My question is how can I see the AVD's output to see what went wrong to fix the crash.

I also checked the Run Window during the crash, but all it said was Application Terminated. without providing why it crashed. Looking at a log file could allow me to find the bug, I just need to know where to get it. Thanks.

AVD: 2.7" mdpi running Android 7.1

答:
In order to look the crash report, see in the Logcat Window. When your app is crash, don't click OK. Open the Logcat you will see the error. If you don't see any report in window, use this comment

adb kill-server

adb start-server

Hope it helps.

Title: Show Log From AVD