问:
How to set up a simple https server using a Cloudflare SSL certificate?
I can't seem to get my server to connect over https.

I created a free Cloudflare account to get a free SSL certificate for a test server. I downloaded the origin certificate and key from Cloudflare onto my Ubuntu server running on the Google Cloud Platform.

https on port 443 is allowed in firewall options.

I tried to create a simple python https server as shown here:

```<code>from socketserver import TCPServer
from http.server import SimpleHTTPRequestHandler
from ssl import wrap_socket

httpd = TCPServer(('localhost', 443), SimpleHTTPRequestHandler)
httpd.socket = wrap_socket(httpd.socket, certfile='./cert.pem', keyfile='./cert.key', server_side=True)
httpd.serve_forever()
</code>```

It runs with no errors but does not produce any output. I try to connect from the browser by accessing https://ip_address without specifying the port since I think https connects to port 443 by default.

I ran a simple http server on port 80 and that worked.

I'm expecting to see the basic html page in the directory connected over https, but I get ERR_CONNECTION_REFUSED in the browser instead.

答:
Change localhost to 0.0.0.0.

Localhost only accepts connections from inside the machine. This is the loopback address.

0.0.0.0 means bind to all available networks. This accepts connections from outside and inside the machine.

Body:
I can't seem to get my server to connect over https.

I created a free Cloudflare account to get a free SSL certificate for a test server. I downloaded the origin certificate and key from Cloudflare onto my Ubuntu server running on the Google Cloud Platform.

https on port 443 is allowed in firewall options.

I tried to create a simple python https server as shown here:

from socketserver import TCPServer
from http.server import SimpleHTTPRequestHandler
from ssl import wrap_socket

httpd = TCPServer(('localhost', 443), SimpleHTTPRequestHandler)
httpd.socket = wrap_socket(httpd.socket, certfile='./cert.pem', keyfile='./cert.key', server_side=True)
httpd.serve_forever()

It runs with no errors but does not produce any output. I try to connect from the browser by accessing https://ip_address without specifying the port since I think https connects to port 443 by default.

I ran a simple http server on port 80 and that worked.

I'm expecting to see the basic html page in the directory connected over https, but I get ERR_CONNECTION_REFUSED in the browser instead.


来源: stackexchange

问:
String Comparison returning false while they have same value

I have strings stored in SQLite database which are shown in an Activity. the problem is if I compare the text of the button with a string value it returns false while equals show it matches. I am curious to know who it is returning false while they are both the same.

I have tried and tostring methods.

```<code>while (result.moveToNext()) {

 Button btn = new Button(this);
 btn.setWidth(100);
 btn.setHeight(40);
 //    btn.setSingleLine(); //keep text in single line don't break big words
 //    btn.setAutoSizeTextTypeUniformWithConfiguration(1, 15, 1,
 //          TypedValue.COMPLEX_UNIT_DIP);
 messageReceived = result.getString(1).trim();
 btn.setText(result.getString(1).trim());

 String btnText = btn.getText().toString().trim();

 String Value = Boolean.toString(btnText == messageReceived);
 Toast toast = Toast.makeText(this, Value, Toast.LENGTH_LONG);
 toast.setGravity(Gravity.CENTER, 5, 5);
 toast.show();

 if (messageReceived.equals(btnText)) {
  Toast toast2 = Toast.makeText(this, "matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 } else {
  Toast toast2 = Toast.makeText(this, "Not Matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 }

 Toast.makeText(this, "A: " + btn.getText() + " B: " + messageReceived, Toast.LENGTH_LONG).show();

 btn.setOnClickListener(this);
 grid.addView(btn);

 //messageReceived="pungi";

 if (btnText == messageReceived) {
  btn.setBackgroundColor(Color.YELLOW);
 }

}
</code>```

答:
This line btnText==messageReceived will always return a false as both are not pointing to same object.

equals method match the content where as == operator match the object pointing to same address.
Read out this document to know more about == and equals.
== vs equals

Hope this helps you

ContentLicense: CC BY-SA 4.0

Body:
I have strings stored in SQLite database which are shown in an Activity. the problem is if I compare the text of the button with a string value it returns false while equals show it matches. I am curious to know who it is returning false while they are both the same.

I have tried and tostring methods.

while (result.moveToNext()) {

 Button btn = new Button(this);
 btn.setWidth(100);
 btn.setHeight(40);
 //    btn.setSingleLine(); //keep text in single line don't break big words
 //    btn.setAutoSizeTextTypeUniformWithConfiguration(1, 15, 1,
 //          TypedValue.COMPLEX_UNIT_DIP);
 messageReceived = result.getString(1).trim();
 btn.setText(result.getString(1).trim());

 String btnText = btn.getText().toString().trim();

 String Value = Boolean.toString(btnText == messageReceived);
 Toast toast = Toast.makeText(this, Value, Toast.LENGTH_LONG);
 toast.setGravity(Gravity.CENTER, 5, 5);
 toast.show();

 if (messageReceived.equals(btnText)) {
  Toast toast2 = Toast.makeText(this, "matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 } else {
  Toast toast2 = Toast.makeText(this, "Not Matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 }

 Toast.makeText(this, "A: " + btn.getText() + " B: " + messageReceived, Toast.LENGTH_LONG).show();

 btn.setOnClickListener(this);
 grid.addView(btn);

 //messageReceived="pungi";

 if (btnText == messageReceived) {
  btn.setBackgroundColor(Color.YELLOW);
 }

}


问:
my app token is useless, how could I access to the dataset
I am trying to use my own generated app token to access the socrata data, but I don't know why my app token is useless, and it always returns "forbidden 403" and "error in getResponse()"

I checked the syntax for read.socrata() function, and modify the the parameters but it still not works

```<code>api_url2004 <- "https://openpaymentsdata.cms.gov/resource/gysc-m9qm.csv?$$app_token = <token>"
query <- soql() %>%
  soql_add_endpoint(api_url2004) %>%
  soql_limit(2000)
token <- "<token>"
data <- read.socrata(query, app_token = token)
</code>```

I would expect that I could successfully logged in and access to the dataset, it now only displays 403 error

答:
It appears this data set is private. I attempted to access the normal data set, https://openpaymentsdata.cms.gov/d/gysc-m9qm and received a login screen. This indicates the data set is private, so you won't be able to access the API without logging-in an having privileges to the private data set.

As a note, the app token doesn't grant you access to private data sets. In RSocrata, this would require using the email and password options in read.socrata().

Body:
I am trying to use my own generated app token to access the socrata data, but I don't know why my app token is useless, and it always returns "forbidden 403" and "error in getResponse()"

I checked the syntax for read.socrata() function, and modify the the parameters but it still not works

api_url2004 <- "https://openpaymentsdata.cms.gov/resource/gysc-m9qm.csv?$$app_token = <token>"
query <- soql() %>%
  soql_add_endpoint(api_url2004) %>%
  soql_limit(2000)
token <- "<token>"
data <- read.socrata(query, app_token = token)

I would expect that I could successfully logged in and access to the dataset, it now only displays 403 error


问:
Python data manipulation: How to group by ID, then subset rows forward/back 1 month base on datatime conditions in each group?
I want to subset data after groupby, and subset rows forward and backward 1 month by datatime conditions.

Here is the test dataframe:

```<code>
import pandas as pd
from itertools import chain

df_1 = pd.DataFrame({
        'ID' : list(chain.from_iterable([['A'] * 365, ['B'] * 365, ['C'] * 365])),
        'Date' : pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist() + pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist() + pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist(),
        'Value' : np.random.randn(365 * 3)
        })

df_2 = pd.DataFrame({
        'ID' : ['A', 'B', 'C'],
        'Initial_date' : pd.to_datetime(['2018-04-24', '2018-09-22', '2018-12-12'], format = '%Y-%m-%d')
        })

df = pd.merge(df_1, df_2, how = 'left', left_on = 'ID', right_on = 'ID')

</code>```

the output of test dataframe is:

```<code>  ID       Date  Value Initial_date
0  A 2018-01-01 -1.084   2018-04-24
1  A 2018-01-02  0.585   2018-04-24
2  A 2018-01-03  0.812   2018-04-24
3  A 2018-01-04 -1.115   2018-04-24
4  A 2018-01-05 -1.724   2018-04-24

</code>```

So here is what I want to have:

For A user, his initial date is 2018-04-24, so I want to have all rows from 1 month backward, which is 2018-03-24, to 1 month forward, which is 2018-05-24.
As well as B and C users.

The result should be the same as

```<code>df_a = df[(df['ID'] == 'A') & (df['Date'] > '2018-03-23') & (df['Date'] < '2018-05-25')]

df_b = df[(df['ID'] == 'B') & (df['Date'] > '2018-08-21') & (df['Date'] < '2018-10-23')]

df_c = df[(df['ID'] == 'C') & (df['Date'] > '2018-11-11') & (df['Date'] < '2018-12-31')]

df_result = pd.concat([df_a, df_b, df_c])
</code>```

The df_result.head() is

```<code>   ID       Date  Value Initial_date
82  A 2018-03-24 -1.013   2018-04-24
83  A 2018-03-25 -0.023   2018-04-24
84  A 2018-03-26 -0.053   2018-04-24
85  A 2018-03-27 -1.091   2018-04-24
86  A 2018-03-28  1.839   2018-04-24
</code>```

Note *1: For the marginal date, it is not necessarily included or excluded the exact date. For example, for A, from 2018-03-23 or 2018-03-24 does not matter for me.

Note *2: For C users, the forward date is less than 1 month since his initial date is on 2018-12-12, so to the end of 2018 is OK.

答:
IIUC, you can try the following:</p>

```<code># set 1-month interval
delta = pd.DateOffset(months=1)

# get the subset
df_result = df[df.Date.gt(df.Initial_date-delta) & df.Date.lt(df.Initial_date+delta)]
</code>```

Body:
I want to subset data after groupby, and subset rows forward and backward 1 month by datatime conditions.

Here is the test dataframe:

import pandas as pd
from itertools import chain

df_1 = pd.DataFrame({
        'ID' : list(chain.from_iterable([['A'] * 365, ['B'] * 365, ['C'] * 365])),
        'Date' : pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist() + pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist() + pd.date_range(start = '2018-01-01', end = '2018-12-31').tolist(),
        'Value' : np.random.randn(365 * 3)
        })

df_2 = pd.DataFrame({
        'ID' : ['A', 'B', 'C'],
        'Initial_date' : pd.to_datetime(['2018-04-24', '2018-09-22', '2018-12-12'], format = '%Y-%m-%d')
        })

df = pd.merge(df_1, df_2, how = 'left', left_on = 'ID', right_on = 'ID')

the output of test dataframe is:

  ID       Date  Value Initial_date
0  A 2018-01-01 -1.084   2018-04-24
1  A 2018-01-02  0.585   2018-04-24
2  A 2018-01-03  0.812   2018-04-24
3  A 2018-01-04 -1.115   2018-04-24
4  A 2018-01-05 -1.724   2018-04-24

So here is what I want to have:

For A user, his initial date is 2018-04-24, so I want to have all rows from 1 month backward, which is 2018-03-24, to 1 month forward, which is 2018-05-24.
As well as B and C users.

The result should be the same as

df_a = df[(df['ID'] == 'A') & (df['Date'] > '2018-03-23') & (df['Date'] < '2018-05-25')]

df_b = df[(df['ID'] == 'B') & (df['Date'] > '2018-08-21') & (df['Date'] < '2018-10-23')]

df_c = df[(df['ID'] == 'C') & (df['Date'] > '2018-11-11') & (df['Date'] < '2018-12-31')]

df_result = pd.concat([df_a, df_b, df_c])

The df_result.head() is

   ID       Date  Value Initial_date
82  A 2018-03-24 -1.013   2018-04-24
83  A 2018-03-25 -0.023   2018-04-24
84  A 2018-03-26 -0.053   2018-04-24
85  A 2018-03-27 -1.091   2018-04-24
86  A 2018-03-28  1.839   2018-04-24

Note *1: For the marginal date, it is not necessarily included or excluded the exact date. For example, for A, from 2018-03-23 or 2018-03-24 does not matter for me.

Note *2: For C users, the forward date is less than 1 month since his initial date is on 2018-12-12, so to the end of 2018 is OK.

Body:
IIUC, you can try the following:

# set 1-month interval
delta = pd.DateOffset(months=1)

# get the subset
df_result = df[df.Date.gt(df.Initial_date-delta) & df.Date.lt(df.Initial_date+delta)]


问:
How to convert nested object into dictionary?
I want to backup my firestore data into mysql using Python 3.
right now I am struggling to convert the object into a dictionary.

my data structure :

status > phone_number > time_stamp > message_status

docs = db.collection(u'status').stream()
for doc in docs:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))
```

when I print the docs it shows <generator object Query.stream at 0x113c306d8>. I have tried the above command but I don't get the resul.

答:
Use a dictionary comprehension to turn the docs generator into a dict:

```<code>docs = db.collection(u'status').stream()

docs_dict = {doc.id:doc.to_dict() for doc in docs}

# print dictionary keys
for k in docs_dict:
    print(u'doc id: {}'.format(k))
</code>```

Also, watch out for the timeout on the stream() method. If you have thousands of docs in your collection, you will need to make multiple stream() requests or use a recursive function.

Body:
I want to backup my firestore data into mysql using Python 3.
right now I am struggling to convert the object into a dictionary.

my data structure :

status > phone_number > time_stamp > message_status

docs = db.collection(u'status').stream()
for doc in docs:
    print(u'{} => {}'.format(doc.id, doc.to_dict()))

when I print the docs it shows <generator object Query.stream at 0x113c306d8>. I have tried the above command but I don't get the resul.

Body:
Use a dictionary comprehension to turn the docs generator into a dict:

docs = db.collection(u'status').stream()

docs_dict = {doc.id:doc.to_dict() for doc in docs}

# print dictionary keys
for k in docs_dict:
    print(u'doc id: {}'.format(k))

Also, watch out for the timeout on the stream() method. If you have thousands of docs in your collection, you will need to make multiple stream() requests or use a recursive function.


问:
What UNIX commands support coloured output?
I enjoy using UNIX/bash commands that support coloured output.  Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option.  However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.

The ones in my ~/.bash_aliases file are:

```<code>ls --color=auto
grep --color
phpunit --ansi
</code>```

What else is there?  Is there a list somewhere of all commands that support coloured output?  Or better still, some command for grepping my local man pages and plucking out the appropriate command names.

答:
A quick bit of google search also reveals grc and grcat, which can be used to colorise any arbitrary text or command. Not sure how well they work though. I'm certainly going to try them out now that I've found them.

Ah, here we go. grc uses the /etc/grc.conf file to colorise a given command based on which regexp it matches. A quick grep of my (Ubuntu 8.10) /etc/grc.conf reveals it currently has support for:

```<code>[~]$ less /etc/grc.conf | grep '^#'
# anything to do with irc
# log file
# ping command
# traceroute command
# gcc command
# make command
# netstat command
# diff command
# last command
# ldap tools
# cvs command
</code>```

But I'm sure you could add your own for other programs you are interested in.

To use grc, simply put it before the command you want to colorise (lets say diff):

```<code>grc diff foo.txt bar.txt
</code>```

And you could certainly alias diff='grc diff' to make diff colorised by default.

OwnerDisplayName: DavidWinterbottom

ContentLicense: CC BY-SA 2.5

Body:
I enjoy using UNIX/bash commands that support coloured output.  Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option.  However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.

The ones in my ~/.bash_aliases file are:

ls --color=auto
grep --color
phpunit --ansi

What else is there?  Is there a list somewhere of all commands that support coloured output?  Or better still, some command for grepping my local man pages and plucking out the appropriate command names.

LastEditorDisplayName: Eddie

Body:
A quick bit of google search also reveals grc and grcat, which can be used to colorise any arbitrary text or command. Not sure how well they work though. I'm certainly going to try them out now that I've found them.

Ah, here we go. grc uses the /etc/grc.conf file to colorise a given command based on which regexp it matches. A quick grep of my (Ubuntu 8.10) /etc/grc.conf reveals it currently has support for:

[~]$ less /etc/grc.conf | grep '^#'
# anything to do with irc
# log file
# ping command
# traceroute command
# gcc command
# make command
# netstat command
# diff command
# last command
# ldap tools
# cvs command

But I'm sure you could add your own for other programs you are interested in.

To use grc, simply put it before the command you want to colorise (lets say diff):

grc diff foo.txt bar.txt

And you could certainly alias diff='grc diff' to make diff colorised by default.

OwnerDisplayName: David Dean

LastEditorDisplayName: David Dean


问:
What type of problems can mapreduce solve?
Is there a theoretical analysis available which describes what kind of problems mapreduce can solve?</p>

答: The answer lies is really in the name of the algorithm.  MapReduce is not a general purpose parallel programming work or batch execution framework as some of the answers suggest.  Map Reduce is really useful when large data sets that need to be processed (Mapping phase) and derive certain attributes from there, and then need to be summarized on on those derived attributes (Reduction Phase).

OwnerDisplayName: aamit

LastEditorDisplayName: Welbog

ContentLicense: CC BY-SA 3.0


问:
How can I using this variable?
I want to using this variable (ntime[]) in main class
I think I must using 'extends', but I don't know how I using that.
What Can I using variable, and How can I use it?
I want to know It is using extends, or another variable it can.
Thank you

I was using extends
~~ void main(String args[]) extends * throws IOException
&
~~ void main extends * (String args[]) *** throws IOException

but it is not work

import java.util.Calendar;

```<code>class *****
 {
 public void ***** throws IOException
 {
 int [] ntime = new int [6];
 BufferedReader inbr = new BufferedReader (new
 InputStreamReader(System.in));
 Calendar now= Calendar.getInstance();
 ntime[0] = now.get(Calendar.YEAR);
 ntime[1] = now.get(Calendar.MONTH);
....
 ntime[5] = now.get(Calendar.SECOND);
 }
 }

 class *****  {
 public static void main(String args[]) throws IOException
 {

***** objecta = new ***();
   objecta.test01();
  System.out.println("Time is  " + ntime[0] + ... + ntime[5]);
 }
 }
</code>```

symbol:   variable ntime
  location: class ***

答:
Since ntime is a member of the *** class.

To be able access it, you have to create first an instance of that class and make sure that ntime isn't a private member. Which i think you did when you created your 'objecta'. And then you will have to access your variable ntime through that object.

For example you would call

```<code>objecta.ntime[0]
</code>```

Title: How can I using this variable?

Body:
I want to using this variable (ntime[]) in main class
I think I must using 'extends', but I don't know how I using that.
What Can I using variable, and How can I use it?
I want to know It is using extends, or another variable it can.
Thank you

I was using extends
~~ void main(String args[]) extends * throws IOException
&
~~ void main extends * (String args[]) *** throws IOException

but it is not work

import java.util.Calendar;

class *****
 {
 public void ***** throws IOException
 {
 int [] ntime = new int [6];
 BufferedReader inbr = new BufferedReader (new
 InputStreamReader(System.in));
 Calendar now= Calendar.getInstance();
 ntime[0] = now.get(Calendar.YEAR);
 ntime[1] = now.get(Calendar.MONTH);
....
 ntime[5] = now.get(Calendar.SECOND);
 }
 }

 class *****  {
 public static void main(String args[]) throws IOException
 {

***** objecta = new ***();
   objecta.test01();
  System.out.println("Time is  " + ntime[0] + ... + ntime[5]);
 }
 }

symbol:   variable ntime
  location: class ***

Body:
Since ntime is a member of the *** class.

To be able access it, you have to create first an instance of that class and make sure that ntime isn't a private member. Which i think you did when you created your 'objecta'. And then you will have to access your variable ntime through that object.

For example you would call

objecta.ntime[0]


问:
GetType return Int instead of System.Int32
GetType().ToString() returns the FullName of the object. I want the name that you usually use to instantiate that object, i.e, int instead of Int32. Is there a way to do this? </p>

答:
```<code>GetType().ToString().FromDotNetTypeToCSharpType();
</code>```

Using the extension method below. I came up with something similar for some templating I was doing in c# using the following Microsoft reference:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/built-in-types-table

Optionally, a boolean whether the type is nullable can be passed in for the shortcut nullable syntax.

```<code>    /// <summary>Converts a .Net type name to a C# type name. It will remove the "System." namespace, if present,</summary>
    public static string FromDotNetTypeToCSharpType(this string dotNetTypeName, bool isNull = false)
    {
        string cstype = "";
        string nullable = isNull ? "?" : "";
        string prefix = "System.";
        string typeName = dotNetTypeName.StartsWith(prefix) ? dotNetTypeName.Remove(0, prefix.Length) : dotNetTypeName;

        switch (typeName)
        {
            case "Boolean": cstype = "bool"; break;
            case "Byte":    cstype = "byte"; break;
            case "SByte":   cstype = "sbyte"; break;
            case "Char":    cstype = "char"; break;
            case "Decimal": cstype = "decimal"; break;
            case "Double":  cstype = "double"; break;
            case "Single":  cstype = "float"; break;
            case "Int32":   cstype = "int"; break;
            case "UInt32":  cstype = "uint"; break;
            case "Int64":   cstype = "long"; break;
            case "UInt64":  cstype = "ulong"; break;
            case "Object":  cstype = "object"; break;
            case "Int16":   cstype = "short"; break;
            case "UInt16":  cstype = "ushort"; break;
            case "String":  cstype = "string"; break;

            default: cstype = typeName; break; // do nothing
        }
        return $"{cstype}{nullable}";

    }
</code>```

Body:
GetType().ToString().FromDotNetTypeToCSharpType();

Using the extension method below. I came up with something similar for some templating I was doing in c# using the following Microsoft reference:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/built-in-types-table

Optionally, a boolean whether the type is nullable can be passed in for the shortcut nullable syntax.

    /// <summary>Converts a .Net type name to a C# type name. It will remove the "System." namespace, if present,</summary>
    public static string FromDotNetTypeToCSharpType(this string dotNetTypeName, bool isNull = false)
    {
        string cstype = "";
        string nullable = isNull ? "?" : "";
        string prefix = "System.";
        string typeName = dotNetTypeName.StartsWith(prefix) ? dotNetTypeName.Remove(0, prefix.Length) : dotNetTypeName;

        switch (typeName)
        {
            case "Boolean": cstype = "bool"; break;
            case "Byte":    cstype = "byte"; break;
            case "SByte":   cstype = "sbyte"; break;
            case "Char":    cstype = "char"; break;
            case "Decimal": cstype = "decimal"; break;
            case "Double":  cstype = "double"; break;
            case "Single":  cstype = "float"; break;
            case "Int32":   cstype = "int"; break;
            case "UInt32":  cstype = "uint"; break;
            case "Int64":   cstype = "long"; break;
            case "UInt64":  cstype = "ulong"; break;
            case "Object":  cstype = "object"; break;
            case "Int16":   cstype = "short"; break;
            case "UInt16":  cstype = "ushort"; break;
            case "String":  cstype = "string"; break;

            default: cstype = typeName; break; // do nothing
        }
        return $"{cstype}{nullable}";

    }


问:
Hibernate, PostgreSQL: how to search in an array column
I use the PostgreSQL table agents. It has a column zip_codes character(5)[] that stores the zip codes of the areas the agents are responsible for.

It stores agent1 with the zip codes {11111,22222} and agent2 with the zip code {33333}.

I want to look for all agents that are responsible for a special area.

Without Hibernate it is easy: SELECT * FROM agents WHERE '11111' = ANY (zip_codes) returns agent1.

But how do I make it with HQL? It does not know any. But if I use in instead, I will get wrong results: if I write select agents from Agents as agents where '{11111}' in (agents.zip_codes), agent1 will not be found. If I use '{33333}' instead, agent2 will be found.

Of course I can search with something like (in sql) WHERE zip_codes[1] = '11111' OR zip_codes[2] = '11111' (arrays in PostgreSQL start with index 1), but this is not handy for many entries in zip_codes.

答:
you can regist dailect like this

```<code>public class MyPostgresSQLDialect extends PostgreSQLDialect {
  public MyPostgresSQLDialect() {
    super();

    this.registerFunction( "array_any", new SQLFunctionTemplate(StandardBasicTypes.INTEGER,"ANY(?1)") );
    this.registerFunction( "array_array", new SQLFunctionTemplate(StandardBasicTypes.INTEGER,"array[?1]") );

  }
}
</code>```

now you can use in hql

```<code>String hql = " from tablename" +
            " where year = :year and month = :month and :version = array_any(versions)";
</code>```

remeber regist dailect in sessionFactory

```<code><prop key="hibernate.dialect">com.test.MyPostgresSQLDialect</prop>
</code>```

Body:
you can regist dailect like this

public class MyPostgresSQLDialect extends PostgreSQLDialect {
  public MyPostgresSQLDialect() {
    super();

    this.registerFunction( "array_any", new SQLFunctionTemplate(StandardBasicTypes.INTEGER,"ANY(?1)") );
    this.registerFunction( "array_array", new SQLFunctionTemplate(StandardBasicTypes.INTEGER,"array[?1]") );

  }
}

now you can use in hql

String hql = " from tablename" +
            " where year = :year and month = :month and :version = array_any(versions)";

remeber regist dailect in sessionFactory

<prop key="hibernate.dialect">com.test.MyPostgresSQLDialect</prop>


答:
It probably because == compare addresses when equal compares content
example

```<code>String s1 = new String("sd");
String s2 = new String("sd");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
</code>```

First return false when second return true

Title: String Comparison returning false while they have same value

Body:
It probably because == compare addresses when equal compares content
example

String s1 = new String("sd");
String s2 = new String("sd");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));

First return false when second return true


问:
Compare functions in haskell
I have a list of commands ([Command]) which looks like [forward 15, left 20, right 10].
I want to add forward 15 to [Command] whenever I see a forward 15 command. I used elem and == to compare whether the element is forward 15 or not but it gives me No instance for (Eq Command) arising error.
Also, in another function, I want to add [left 15, forward 15, forward 15, right 15, right 15, forward 15, forward 15, left 15] to [Command] whenever I see 4 consecutive forward 15 commands.
Thus my question is how to compare functions, because forward is a function and I can't compare it using elem or ==.

Command is defined as a type, not as a data, hence I can't use deriving Eq.

```<code>type Command = Funcs -> (Picture, Funcs)

data Funcs = Funcs {pen :: Bool, angle :: Float, point :: Point, penColor :: Color} deriving (Eq, Show)

forward :: Float -> Command
forward x = ....
</code>```

答:
You might be missing a deriving clause in your data definition.

```<code>Prelude> data Command = Forward Int | Left Int | Right Int deriving (Eq, Show)
Prelude> Forward 15 == Forward 15
True
</code>```

If you do not have the deriving clause you will see

No instance for (Eq Command) arising from a use of ‘==’

By the way, while it is true that Forward happens to be a (constructor) function, you want to make sure you are doing == comparisons not on functions themselves (you can't do this in Haskell) but rather on the result of applying the function. So you can never compare

```<code>Forward == Forward
</code>```

because the type of Forward is Int->Command (a function) but you can compare

```<code>Forward 15 == Forward 15
</code>```

as long as you associate the type Command with the Eq typeclass.

Title: Compare functions in haskell

Body:
I have a list of commands ([Command]) which looks like [forward 15, left 20, right 10].
I want to add forward 15 to [Command] whenever I see a forward 15 command. I used elem and == to compare whether the element is forward 15 or not but it gives me No instance for (Eq Command) arising error.
Also, in another function, I want to add [left 15, forward 15, forward 15, right 15, right 15, forward 15, forward 15, left 15] to [Command] whenever I see 4 consecutive forward 15 commands.
Thus my question is how to compare functions, because forward is a function and I can't compare it using elem or ==.

Command is defined as a type, not as a data, hence I can't use deriving Eq.

type Command = Funcs -> (Picture, Funcs)

data Funcs = Funcs {pen :: Bool, angle :: Float, point :: Point, penColor :: Color} deriving (Eq, Show)

forward :: Float -> Command
forward x = ....

Body:
You might be missing a deriving clause in your data definition.

Prelude> data Command = Forward Int | Left Int | Right Int deriving (Eq, Show)
Prelude> Forward 15 == Forward 15
True

If you do not have the deriving clause you will see

No instance for (Eq Command) arising from a use of ‘==’

By the way, while it is true that Forward happens to be a (constructor) function, you want to make sure you are doing == comparisons not on functions themselves (you can't do this in Haskell) but rather on the result of applying the function. So you can never compare

Forward == Forward

because the type of Forward is Int->Command (a function) but you can compare

Forward 15 == Forward 15

as long as you associate the type Command with the Eq typeclass.


问:
Laravel application shared hosting, storage folder symbolic Link issue
I've created symbolic link at local PC, where its working fine, but I've uploaded same it to shared hosting, it is not working there.
Basically I've images in the storage folder root/storage/public/images/

i want to display them by getting

```<code>$path=asset('storage/images/'.$item->image);
</code>```

so the problem is in the shared hosting this way

```<code>$path=asset('storage/images/'.$item->image);
</code>```

getting from the domain directory not from the parent directory, so for that there is no way to create symbolic link on shared hosting so what should I do to get images from the parent directory.
I am beginner in laravel one can help me to solve this problem.
Thanks

答:
first delete folder storage from folder public and, using this code in web.php

```<code>Route::get('foo', function(){
    $targetFolder = $_SERVER['DOCUMENT_ROOT'].'/project_foder/laravel/storage/app/public';
    $linkFolder = $_SERVER['DOCUMENT_ROOT'].'/project_foder/public/storage';
    symlink($targetFolder, $linkFolder);
    return 'success';
});
</code>```

or

```<code>Route::get('foo', function(){
    Artisan::call('storage:link', []);
    return 'success';
})
</code>```

Body:
I've created symbolic link at local PC, where its working fine, but I've uploaded same it to shared hosting, it is not working there.
Basically I've images in the storage folder root/storage/public/images/

i want to display them by getting

$path=asset('storage/images/'.$item->image);

so the problem is in the shared hosting this way

$path=asset('storage/images/'.$item->image);

getting from the domain directory not from the parent directory, so for that there is no way to create symbolic link on shared hosting so what should I do to get images from the parent directory.
I am beginner in laravel one can help me to solve this problem.
Thanks

Body:
first delete folder storage from folder public and, using this code in web.php

Route::get('foo', function(){
    $targetFolder = $_SERVER['DOCUMENT_ROOT'].'/project_foder/laravel/storage/app/public';
    $linkFolder = $_SERVER['DOCUMENT_ROOT'].'/project_foder/public/storage';
    symlink($targetFolder, $linkFolder);
    return 'success';
});

or

Route::get('foo', function(){
    Artisan::call('storage:link', []);
    return 'success';
})


问:
Should I use resource routing even for non-CRUD routes (Rails)?
Is it considered best practice to use resourceful routes in Rails whenever possible, even if the CRUD verbs don't really match the actions being performed (details follow)?

In my Rails app, I'm implementing an OAuth login system using sorcery's external module. I closely followed their official tutorial, which defines the routes for the OAuth methods like this.

# config/routes.rb
post "oauth/callback" => "oauths#callback"
get "oauth/callback" => "oauths#callback" # for use with Github, Facebook
get "oauth/:provider" => "oauths#oauth", :as => :auth_at_provider
```

<p>Basically, <code>auth_at_provider</code> is called when the user clicks the "Login via [Provider Name]" button, and the <code>callback</code> is called once they log in via the external provider.</p>

<p>I left the routes as-is, but a teammate reviewing it suggested we use resource routing, like this for example:</p>

<pre class="lang-rb prettyprint-override"><code>resources :oauth only: [:index, :create, :show]
</code>```

I guess this is technically possible, but for me the singular routes defined in the tutorial are much more intuitive and self-explanatory. So my questions are:

Is it considered better (or common) to use resourceful routes even in cases like this? or

Are resourceful routes just a shorthand for cookie-cutter routes, and should only be used for straightforward controllers?

答:
I wouldn't use the resource(s) helpers. The name tells you it's used for resources and oauth logic are not resources.

You could refactor the routes a little bit though

```<code>namespace :oauth do
  match :callback, via: [:get, :post]
  get ":provider", action: :oauth, as: :at_provider
end
</code>```

This creates this routes:

```<code>              oauth_callback GET|POST /oauth/callback(.:format)                                                                oauth#callback
           oauth_at_provider GET      /oauth/:provider(.:format)                                                               oauth#oauth
</code>```

They are basically the same routes, DRYer and without misleading "resource" wording.

*Note the little change from "auth_at_provider" to "oauth_at_provider" introduced by the namespace

Body:
Is it considered best practice to use resourceful routes in Rails whenever possible, even if the CRUD verbs don't really match the actions being performed (details follow)?

In my Rails app, I'm implementing an OAuth login system using sorcery's external module. I closely followed their official tutorial, which defines the routes for the OAuth methods like this.

# config/routes.rb
post "oauth/callback" => "oauths#callback"
get "oauth/callback" => "oauths#callback" # for use with Github, Facebook
get "oauth/:provider" => "oauths#oauth", :as => :auth_at_provider

Basically, auth_at_provider is called when the user clicks the "Login via [Provider Name]" button, and the callback is called once they log in via the external provider.

I left the routes as-is, but a teammate reviewing it suggested we use resource routing, like this for example:

resources :oauth only: [:index, :create, :show]

I guess this is technically possible, but for me the singular routes defined in the tutorial are much more intuitive and self-explanatory. So my questions are:

Is it considered better (or common) to use resourceful routes even in cases like this? or

Are resourceful routes just a shorthand for cookie-cutter routes, and should only be used for straightforward controllers?

Body:
I wouldn't use the resource(s) helpers. The name tells you it's used for resources and oauth logic are not resources.

You could refactor the routes a little bit though

namespace :oauth do
  match :callback, via: [:get, :post]
  get ":provider", action: :oauth, as: :at_provider
end

This creates this routes:

              oauth_callback GET|POST /oauth/callback(.:format)                                                                oauth#callback
           oauth_at_provider GET      /oauth/:provider(.:format)                                                               oauth#oauth

They are basically the same routes, DRYer and without misleading "resource" wording.

*Note the little change from "auth_at_provider" to "oauth_at_provider" introduced by the namespace


问:
Regex using brackets for a single character
I was solving this regex problem

Given a test string, s , write a RegEx that matches s under the following conditions:

s must start with Mr., Mrs., Ms., Dr. or Er.

The rest of the string must contain only one or more English alphabetic letters (upper and lowercase).

I used this pattern

```<code>Regex_Pattern = r'^(Mr|Mrs|Ms|Dr|Er)\..[A-Za-z]+$'
</code>```

but it failed this test case "Ms._underscore", then I tried using this pattern

```<code>Regex_Pattern = r'^(Mr|Mrs|Ms|Dr|Er)[\..][A-Za-z]+$'
</code>```

and it passed all test cases, I cannot figure out the difference.

答:
Here, we can visualize our expressions and check:

We can see that the difference is here, between \.. and [\..].

In the first one, we are saying that we must have a . followed by any char.

In the second, we want to just pass one of . or ., which is equal to [.].

Demo for second expression

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I was solving this regex problem

Given a test string, s , write a RegEx that matches s under the following conditions:

s must start with Mr., Mrs., Ms., Dr. or Er.

The rest of the string must contain only one or more English alphabetic letters (upper and lowercase).

I used this pattern

Regex_Pattern = r'^(Mr|Mrs|Ms|Dr|Er)\..[A-Za-z]+$'

but it failed this test case "Ms._underscore", then I tried using this pattern

Regex_Pattern = r'^(Mr|Mrs|Ms|Dr|Er)[\..][A-Za-z]+$'

and it passed all test cases, I cannot figure out the difference.


Title: Is is possible to read from an input file and convert each line of the text file into a vector of strings?

Body:
I have a text file as shown below:

---#--###----
-#---#----##-
####-#-#-#-##
---#---#-#---
-#-####---##-
-#------#----
-############
------------@

Can I read from the input file and get an output in this format

[ ["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"]
  ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"]
  ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"]
  ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"]
  ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"]
  ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"]
  ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
  ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]
]

I tried reading the input file line by line and adding to a vector:

    (defn loadFile2 []
        (with-open [rdr (clojure.java.io/reader "map.txt")]
        (reduce conj [] (line-seq rdr)))
    )

    (defn convert_input_to_string []
        "Converts"
        ;(def temp )
        (loop [i 0 temp (loadFile2)]
            (if (< i (count temp))

            (recur (inc i) (assoc temp i (str (join (seq (get temp
             i))))) )
            temp
            ))
    )

(convert_input_to_string).

This approach gives me a vector of strings:

[---#--###----
 -#---#----##-
 ####-#-#-#-##
 ---#---#-#---
 -#-####---##-
 -#------#----
 -############
 ------------@
]

I want the vector in this format:

[ ["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"]
  ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"]
  ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"]
  ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"]
  ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"]
  ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"]
  ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
  ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]]

Body:
Go step by step.

Read data (As file is small, just slurp). Let's name the file grid.txt

(slurp "grid.txt")
"---#--###----\r\n-#---#----##-\r\n####-#-#-#-##\r\n---#---#-#---\r\n-#-####---##-\r\n-#------#----\r\n-############\r\n------------@"

Break into lines:

(->> (slurp "grid.txt")
     (clojure.string/split-lines))
["---#--###----" "-#---#----##-" "####-#-#-#-##" "---#---#-#---" "-#-####---##-" "-#------#----" "-############" "------------@"]

Convert each string to character vector:

(->> (slurp "grid.txt")
     (clojure.string/split-lines)
     (map vec))
([\- \- \- \# \- \- \# \# \# \- \- \- \-] [\- \# \- \- \- \# \- \- \- \- \# \# \-] [\# \# \# \# \- \# \- \# \- \# \- \# \#] [\- \- \- \# \- \- \- \# \- \# \- \- \-] [\- \# \- \# \# \# \# \- \- \- \# \# \-] [\- \# \- \- \- \- \- \- \# \- \- \- \-] [\- \# \# \# \# \# \# \# \# \# \# \# \#] [\- \- \- \- \- \- \- \- \- \- \- \- \@])

Convert top level to vector:

(->> (slurp "grid.txt")
     (clojure.string/split-lines)
     (map vec)
     (into []))
[[\- \- \- \# \- \- \# \# \# \- \- \- \-] [\- \# \- \- \- \# \- \- \- \- \# \# \-] [\# \# \# \# \- \# \- \# \- \# \- \# \#] [\- \- \- \# \- \- \- \# \- \# \- \- \-] [\- \# \- \# \# \# \# \- \- \- \# \# \-] [\- \# \- \- \- \- \- \- \# \- \- \- \-] [\- \# \# \# \# \# \# \# \# \# \# \# \#] [\- \- \- \- \- \- \- \- \- \- \- \- \@]]

Note that this isn't the same as your expected output because the inner vectors contain characters, not strings.

If you really wanted strings instead, you Need to add a line:

(->> (slurp "grid.txt")
     (clojure.string/split-lines)
     (map #(map str %))
     (map vec)
     (into []))
[["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"] ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"] ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"] ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"] ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"] ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"] ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"] ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]]


问:
I have problem linking my css to html using external method of writing css
Have been trying to link my html and my css writing code using css external method, can anybody put me through please?</p>

答:
if your css file is on the same folder of the html file then the link will be in the following way.

```<code><link rel="stylesheet" type="text/css" href="css_file_name.css">
</code>```

if your css file is on another folder in the root directory then:

```<code><link rel="stylesheet" type="text/css" href="folder_name/css_file_name.css">
</code>```

Body:
if your css file is on the same folder of the html file then the link will be in the following way.

<link rel="stylesheet" type="text/css" href="css_file_name.css">

if your css file is on another folder in the root directory then:

<link rel="stylesheet" type="text/css" href="folder_name/css_file_name.css">


问:
can I split some text on python?
I want to split text on python and take some part, for example:

let the blue sky meet the blue sea

I want this for the result:

blue sky

this is my code

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
print bluee
```

and the result from the code is
blue sky meet the blue sea

答:
```<code> text = "let the blue sky meet the blue sea"
 text=text.split(" ")
 text=text[2]+" "+text[3]
 print(text)
</code>```

Title: can I split some text on python?

Body:
I want to split text on python and take some part, for example:

let the blue sky meet the blue sea

I want this for the result:

blue sky

this is my code

text = "let the blue sky meet the blue sea"
bluee = text.split("the", 1)[1]
print bluee

and the result from the code is
blue sky meet the blue sea


问:
Retrieving value from Tkinter combobox
Eventually I want to use the values in the comboboxes as parameters in other functions, but I think if I can just get them to print for now, that will be enough to build off of. Here's what I have so far.

```<code>import tkinter as tk
from tkinter import ttk
import time

def ok():
    betType = betTypeVar.get()
    season = seasonVar.get()
    print(betType, season)

def CreateSimPreviousSeasonWindow():

    prevSeasonWindow = tk.Tk()

    #============= Bet Type Input =============#
    betTypeVar = tk.StringVar()

    betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
    betTypeChosen = ttk.Combobox(prevSeasonWindow, values=['Moneyline','Total'])
    betTypeChosen.grid(row=0, column=1)

    seasonVar = tk.StringVar()
    seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
    seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
    seasonChosen.grid(row=1,column=1)

    button = tk.Button(prevSeasonWindow, text='OK', command=ok)
    button.grid(row=2,column=0)

    prevSeasonWindow.mainloop()
</code>```

This gives me

```<code>  File "C:[directory...]", line 6, in ok
    betType = betTypeVar.get()
NameError: name 'betTypeVar' is not defined
</code>```

To me it looks pretty obvious that this error is because ok() doesn't have any parameters passed to it, so it has no idea what 'betTypeVar' is, but all the tutorials I've read do it this way, so I'm missing something. If I try actually passing ok() the arguments, it still doesn't work.

答:
There are two things to fix in your code. First let's focus on CreateSimPreviousSeasonWindow:

```<code>betTypeVar = tk.StringVar()
seasonVar = tk.StringVar()
</code>```

You defined two StringVar but you actually never used it or linked them to your combobox object. The correct way is to set them as a textvaraible:

```<code>betTypeChosen = ttk.Combobox(prevSeasonWindow, textvariable=betTypeVar, values=['Moneyline','Total'])
seasonChosen = ttk.Combobox(prevSeasonWindow, textvariable=seasonVar, values=['2018', '2017'])
</code>```

Next, NameError: name 'betTypeVar' is not defined is due to your variables being local variables. You are trying to access the same variable across different functions. To pass them around, you need to declare global:

```<code>def ok():
    global betTypeVar, seasonVar
    betType = betTypeVar.get()
    season = seasonVar.get()
    print(betType, season)

def CreateSimPreviousSeasonWindow():
    global betTypeVar, seasonVar
    ...
</code>```

Also I want to point out that if you just want to retrieve the values of the combobox, you don't really need to create two StringVar. Just combobox.get() already works good enough.

```<code>import tkinter as tk
from tkinter import ttk
import time

def ok():
    global betTypeChosen, seasonChosen
    print (betTypeChosen.get(), seasonChosen.get())

def CreateSimPreviousSeasonWindow():
    global betTypeChosen,seasonChosen

    prevSeasonWindow = tk.Tk()

    #============= Bet Type Input =============#

    betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
    betTypeChosen = ttk.Combobox(prevSeasonWindow,values=['Moneyline','Total'])
    betTypeChosen.grid(row=0, column=1)

    seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
    seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
    seasonChosen.grid(row=1,column=1)

    button = tk.Button(prevSeasonWindow, text='OK', command=ok)
    button.grid(row=2,column=0)

    prevSeasonWindow.mainloop()

CreateSimPreviousSeasonWindow()
</code>```

Title: Retrieving value from Tkinter combobox

Body:
Eventually I want to use the values in the comboboxes as parameters in other functions, but I think if I can just get them to print for now, that will be enough to build off of. Here's what I have so far.

import tkinter as tk
from tkinter import ttk
import time

def ok():
    betType = betTypeVar.get()
    season = seasonVar.get()
    print(betType, season)

def CreateSimPreviousSeasonWindow():

    prevSeasonWindow = tk.Tk()

    #============= Bet Type Input =============#
    betTypeVar = tk.StringVar()

    betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
    betTypeChosen = ttk.Combobox(prevSeasonWindow, values=['Moneyline','Total'])
    betTypeChosen.grid(row=0, column=1)

    seasonVar = tk.StringVar()
    seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
    seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
    seasonChosen.grid(row=1,column=1)

    button = tk.Button(prevSeasonWindow, text='OK', command=ok)
    button.grid(row=2,column=0)

    prevSeasonWindow.mainloop()

This gives me

  File "C:[directory...]", line 6, in ok
    betType = betTypeVar.get()
NameError: name 'betTypeVar' is not defined

To me it looks pretty obvious that this error is because ok() doesn't have any parameters passed to it, so it has no idea what 'betTypeVar' is, but all the tutorials I've read do it this way, so I'm missing something. If I try actually passing ok() the arguments, it still doesn't work.

Body:
There are two things to fix in your code. First let's focus on CreateSimPreviousSeasonWindow:

betTypeVar = tk.StringVar()
seasonVar = tk.StringVar()

You defined two StringVar but you actually never used it or linked them to your combobox object. The correct way is to set them as a textvaraible:

betTypeChosen = ttk.Combobox(prevSeasonWindow, textvariable=betTypeVar, values=['Moneyline','Total'])
seasonChosen = ttk.Combobox(prevSeasonWindow, textvariable=seasonVar, values=['2018', '2017'])

Next, NameError: name 'betTypeVar' is not defined is due to your variables being local variables. You are trying to access the same variable across different functions. To pass them around, you need to declare global:

def ok():
    global betTypeVar, seasonVar
    betType = betTypeVar.get()
    season = seasonVar.get()
    print(betType, season)

def CreateSimPreviousSeasonWindow():
    global betTypeVar, seasonVar
    ...

Also I want to point out that if you just want to retrieve the values of the combobox, you don't really need to create two StringVar. Just combobox.get() already works good enough.

import tkinter as tk
from tkinter import ttk
import time

def ok():
    global betTypeChosen, seasonChosen
    print (betTypeChosen.get(), seasonChosen.get())

def CreateSimPreviousSeasonWindow():
    global betTypeChosen,seasonChosen

    prevSeasonWindow = tk.Tk()

    #============= Bet Type Input =============#

    betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
    betTypeChosen = ttk.Combobox(prevSeasonWindow,values=['Moneyline','Total'])
    betTypeChosen.grid(row=0, column=1)

    seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
    seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
    seasonChosen.grid(row=1,column=1)

    button = tk.Button(prevSeasonWindow, text='OK', command=ok)
    button.grid(row=2,column=0)

    prevSeasonWindow.mainloop()

CreateSimPreviousSeasonWindow()


问:
ctx is a required argument
I am trying to make a simple music bot. When I execute the command I get this error: discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

This is my code:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix= "-")

class VoiceConnectionError(commands.CommandError):
    """Custom Exception class for connection errors."""
    ...

class InvalidVoiceChannel(VoiceConnectionError):
    """Exception for cases of invalid Voice Channels."""
    ...

@bot.event
async def on_ready():
    print('Bot ready')

@bot.command(name='connect', aliases=['join'])
async def connect(self, ctx, *, channel: discord.VoiceChannel=None):
    await ctx.send(f'Connected to: **{channel}**', delete_after=10)

bot.run('TOKEN')
```
<p>The command should move the bot into the voice channel in discord.</p>
<p>This is the full traceback:</p>
```Full traceback:
Ignoring exception in command connect:
Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 859, in invoke
    await ctx.command.invoke(ctx)
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/core.py", line 718, in invoke
    await self.prepare(ctx)
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/core.py", line 682, in prepare
    await self._parse_arguments(ctx)
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/core.py", line 596, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/core.py", line 442, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
```

答:
Your commands should only accept a self parameter if they are part of a cog.  Remove the parameter:

```<code>@bot.command(name='connect', aliases=['join'], pass_context=True)
async def connect(ctx, *, channel: discord.VoiceChannel=None):
    ...
</code>```

Title: ctx is a required argument

Body:
I am trying to make a simple music bot. When I execute the command I get this error: discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

This is my code:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix= "-")

class VoiceConnectionError(commands.CommandError):
    """Custom Exception class for connection errors."""
    ...

class InvalidVoiceChannel(VoiceConnectionError):
    """Exception for cases of invalid Voice Channels."""
    ...

@bot.event
async def on_ready():
    print('Bot ready')

@bot.command(name='connect', aliases=['join'])
async def connect(self, ctx, *, channel: discord.VoiceChannel=None):
    await ctx.send(f'Connected to: **{channel}**', delete_after=10)

bot.run('TOKEN')

The command should move the bot into the voice channel in discord.

This is the full traceback:

Full traceback:
Ignoring exception in command connect:
Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/bot.py", line 859, in invoke
    await ctx.command.invoke(ctx)
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/core.py", line 718, in invoke
    await self.prepare(ctx)
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/core.py", line 682, in prepare
    await self._parse_arguments(ctx)
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/core.py", line 596, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "/anaconda3/lib/python3.6/site-packages/discord/ext/commands/core.py", line 442, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

Body:
Your commands should only accept a self parameter if they are part of a cog.  Remove the parameter:

@bot.command(name='connect', aliases=['join'], pass_context=True)
async def connect(ctx, *, channel: discord.VoiceChannel=None):
    ...


问:
A Starting Menu for a simple game
I am making this small and simple game with Java, and when I start it up, it just starts the game without any menus or something. Now, I want to make it so that if I run the game, there comes a game menu, or starting menu, where you can select new game, and exit. But, how would I do this? I need some help with this.

Edit:

The game is in a 800x600 screen, and I want like, a menu that takes over the whole 800x600 screen, with just a "Start Game" and a "Exit" button.

答: You could subclass JFrame, add two JButtons to it and show that frame when needed.</p>

Title: A Starting Menu for a simple game


问:
How to merge two .txt files into one, matching each line by timestamp, using awk
Summary:

I currently have two .txt files imported from a survey system I am testing. Column 1 of each data file is a timestamp of the format "HHMMSS.SSSSSS". In file1, there is a second column of field intensity readings. In file2 there are two additional columns of positional information. I'm attempting to write a script that matches data points between these files by lining the timestamps up. The issue is that at no point are any of the timestamps the exact same value. The script must be able to match data points (lines in each .txt file) based the timestamp of its closest counterpart in the other file (i.e. the time 125051.354948 from file1 should "match" the nearest timestamp in file2, which is 125051.112784).

If anyone with a little bit more awk/sed/join/regex/Unix knowledge could point me in the right direction, I would be very appreciative.

What I have so far:

(Please note that the exact syntax shown here may not make sense for the sample .txt files attached in this question, there are more extensive versions of these files with more columns that were being used for testing scripts.)

I'm new to awk/Unix/shell scripting so please bear with me if some of these trial solutions don't work or don't make a whole lot of sense.

I have already attempted some solutions posted here on stack overflow using join, but it doesn't seem to want to properly sort or join either of these files:

```<code>    ${
      join -o 1.1,2.2 -1 2 -2 1 <(sort -k 2 file1) <(sort -k 1 file2)
      join -v 1 -o 1.1,1.2 -1 2 -2 1 <(sort -k 2 file1) <(sort -k 1
    file2)
    } | sort -k 1
</code>```

Result: only outputs a similar version of the original file2

I attempted to reconfigure existing awk solutions that were posted here as well:

```<code>    awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$3]=$2; next} {print $1, (v[$3] ?
    v[$3] : 0)}' file1 file2 > file3

    awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$1]=$2; next} {print $1, (v[$1] ?
    v[$1] : 0)}' file1 file2 > file3
</code>```

Result: both of these awk commands result in the output of file2's
data with nothing from file1 included (or so it seems).

```<code>awk -F '
FNR == NR {
    time[$3]
    next
}
{   for(i in time)
        if(index($3, i) == 1) {
            print
            next

        }
}' file1 file2 > file3
</code>```

Result: keeps returning a syntax error regarding the "." of ".txt"

I looked into integrating some sort of regex or split command to the script... but was confused as to how to proceed and didn't come up with anything of substance.

Sample Data

```<code>    $ cat file1.txt

    125051.354948 058712.429

    125052.352475 058959.934

    125054.354322 058842.619

    125055.352671 058772.045

    125057.351794 058707.281

    125058.352678 058758.959

    $ cat file2.txt

    125050.105886 4413.34358 07629.87620

    125051.112784 4413.34369 07629.87606

    125052.100811 4413.34371 07629.87605

    125053.097826 4413.34373 07629.87603

    125054.107361 4413.34373 07629.87605

    125055.107038 4413.34375 07629.87604

    125056.093783 4413.34377 07629.87602

    125057.097928 4413.34378 07629.87603

    125058.098475 4413.34378 07629.87606

    125059.095787 4413.34376 07629.87602
</code>```

Expected Result:

(Format: Column1File1 Column1File2 Column2File1 Column2File2 Column3File2)

```<code>    $ cat file3.txt

    125051.354948 125051.112784 058712.429 4413.34358 07629.87620

    125052.352475 125052.100811 058959.934 4413.34371 07629.87605

    125054.354322 125054.107361 058842.619 4413.34373 07629.87605

    125055.352671 125055.107038 058772.045 4413.34375 07629.87604

    125057.351794 125057.097928 058707.281 4413.34378 07629.87603

    125058.352678 125058.098475 058758.959 4413.34378 07629.87606
</code>```

As shown, not every data point from each file will find a match. Only pairs of lines that have the most proximal timestamps to one another will be written over to the new file

As previously mentioned, current solutions result in file3 being entirely blank, or just containing information from one of the two files (but not both)

Body:
Summary:

I currently have two .txt files imported from a survey system I am testing. Column 1 of each data file is a timestamp of the format "HHMMSS.SSSSSS". In file1, there is a second column of field intensity readings. In file2 there are two additional columns of positional information. I'm attempting to write a script that matches data points between these files by lining the timestamps up. The issue is that at no point are any of the timestamps the exact same value. The script must be able to match data points (lines in each .txt file) based the timestamp of its closest counterpart in the other file (i.e. the time 125051.354948 from file1 should "match" the nearest timestamp in file2, which is 125051.112784).

If anyone with a little bit more awk/sed/join/regex/Unix knowledge could point me in the right direction, I would be very appreciative.

What I have so far:

(Please note that the exact syntax shown here may not make sense for the sample .txt files attached in this question, there are more extensive versions of these files with more columns that were being used for testing scripts.)

I'm new to awk/Unix/shell scripting so please bear with me if some of these trial solutions don't work or don't make a whole lot of sense.

I have already attempted some solutions posted here on stack overflow using join, but it doesn't seem to want to properly sort or join either of these files:

    ${
      join -o 1.1,2.2 -1 2 -2 1 <(sort -k 2 file1) <(sort -k 1 file2)
      join -v 1 -o 1.1,1.2 -1 2 -2 1 <(sort -k 2 file1) <(sort -k 1
    file2)
    } | sort -k 1

Result: only outputs a similar version of the original file2

I attempted to reconfigure existing awk solutions that were posted here as well:

    awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$3]=$2; next} {print $1, (v[$3] ?
    v[$3] : 0)}' file1 file2 > file3

    awk 'BEGIN {FS=OFS="\t"} NR==FNR {v[$1]=$2; next} {print $1, (v[$1] ?
    v[$1] : 0)}' file1 file2 > file3

Result: both of these awk commands result in the output of file2's
data with nothing from file1 included (or so it seems).

awk -F '
FNR == NR {
    time[$3]
    next
}
{   for(i in time)
        if(index($3, i) == 1) {
            print
            next

        }
}' file1 file2 > file3

Result: keeps returning a syntax error regarding the "." of ".txt"

I looked into integrating some sort of regex or split command to the script... but was confused as to how to proceed and didn't come up with anything of substance.

Sample Data

    $ cat file1.txt

    125051.354948 058712.429

    125052.352475 058959.934

    125054.354322 058842.619

    125055.352671 058772.045

    125057.351794 058707.281

    125058.352678 058758.959

    $ cat file2.txt

    125050.105886 4413.34358 07629.87620

    125051.112784 4413.34369 07629.87606

    125052.100811 4413.34371 07629.87605

    125053.097826 4413.34373 07629.87603

    125054.107361 4413.34373 07629.87605

    125055.107038 4413.34375 07629.87604

    125056.093783 4413.34377 07629.87602

    125057.097928 4413.34378 07629.87603

    125058.098475 4413.34378 07629.87606

    125059.095787 4413.34376 07629.87602

Expected Result:

(Format: Column1File1 Column1File2 Column2File1 Column2File2 Column3File2)

    $ cat file3.txt

    125051.354948 125051.112784 058712.429 4413.34358 07629.87620

    125052.352475 125052.100811 058959.934 4413.34371 07629.87605

    125054.354322 125054.107361 058842.619 4413.34373 07629.87605

    125055.352671 125055.107038 058772.045 4413.34375 07629.87604

    125057.351794 125057.097928 058707.281 4413.34378 07629.87603

    125058.352678 125058.098475 058758.959 4413.34378 07629.87606

As shown, not every data point from each file will find a match. Only pairs of lines that have the most proximal timestamps to one another will be written over to the new file

As previously mentioned, current solutions result in file3 being entirely blank, or just containing information from one of the two files (but not both)

Body:
#!/bin/bash

if [[ $# -lt 2 ]]; then
  echo "wrong args, it should be $0 file1 file2"
  exit 0
fi

# clear blanks, add an extra column 'm' to file1, merge file1, file2, sort
{ awk 'NF{print $0, "m"}' "$1" ; awk 'NF' "$2"; } | sort -nk1,1 | \
  \
  awk '# record lines and fields in to a
       {a[NR] = $0; a[NR,1] = $1; a[NR,2] = $2; a[NR,3] = $3}
       END{
         for(i=1; i<= NR; ++i){

           # 3rd filed of file1 is "m"
           if(a[i, 3] == "m"){

             # get difference of column1 between current record ,previous record, next record
             prevDiff = (i-1) in a && a[i-1,3] == "m" ? -1 : a[i,1] - a[i-1,1]
             nextDiff = (i+1) in a && a[i+1,3] == "m" ? -1 : a[i+1,1] - a[i,1]

             # compare differences, choose the close one and print.
             if(prevDiff !=-1 && (nextVal == -1 || prevDiff < nextDiff))
               print a[i,1], a[i-1, 1], a[i, 2], a[i-1, 2], a[i-1, 3]
             else if(nextDiff !=-1 && (prevDiff == -1 || nextDiff < prevDiff))
               print a[i,1], a[i+1, 1], a[i, 2], a[i+1, 2], a[i+1, 3]
             else
               print a[i]
           }
         }
       }'

Out put of { awk 'NF{print $0, "m"}' "$1" ; awk 'NF' "$2"; } | sort -nk1,1 is:

125050.105886 4413.34358 07629.87620
125051.112784 4413.34369 07629.87606
125051.354948 058712.429 m
125052.100811 4413.34371 07629.87605
125052.352475 058959.934 m
125053.097826 4413.34373 07629.87603
125054.107361 4413.34373 07629.87605
125054.354322 058842.619 m
125055.107038 4413.34375 07629.87604
125055.352671 058772.045 m
125056.093783 4413.34377 07629.87602
125057.097928 4413.34378 07629.87603
125057.351794 058707.281 m
125058.098475 4413.34378 07629.87606
125058.352678 058758.959 m
125059.095787 4413.34376 07629.87602


问:
String Comparison returning false while they have same value

I have strings stored in SQLite database which are shown in an Activity. the problem is if I compare the text of the button with a string value it returns false while equals show it matches. I am curious to know who it is returning false while they are both the same.

I have tried and tostring methods.

```<code>while (result.moveToNext()) {

 Button btn = new Button(this);
 btn.setWidth(100);
 btn.setHeight(40);
 //    btn.setSingleLine(); //keep text in single line don't break big words
 //    btn.setAutoSizeTextTypeUniformWithConfiguration(1, 15, 1,
 //          TypedValue.COMPLEX_UNIT_DIP);
 messageReceived = result.getString(1).trim();
 btn.setText(result.getString(1).trim());

 String btnText = btn.getText().toString().trim();

 String Value = Boolean.toString(btnText == messageReceived);
 Toast toast = Toast.makeText(this, Value, Toast.LENGTH_LONG);
 toast.setGravity(Gravity.CENTER, 5, 5);
 toast.show();

 if (messageReceived.equals(btnText)) {
  Toast toast2 = Toast.makeText(this, "matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 } else {
  Toast toast2 = Toast.makeText(this, "Not Matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 }

 Toast.makeText(this, "A: " + btn.getText() + " B: " + messageReceived, Toast.LENGTH_LONG).show();

 btn.setOnClickListener(this);
 grid.addView(btn);

 //messageReceived="pungi";

 if (btnText == messageReceived) {
  btn.setBackgroundColor(Color.YELLOW);
 }

}
</code>```

答:
Oh, this is a good one. Boolean.toString(stringA == stringB) is actually doing a reference comparison; that is, checking if both objects are pointing to the same memory location. String.equals(), on the other hand, compares the values.

```<code>String A = new String("five");
String B = new String("five");

System.out.println(Boolean.toString(A == B)); // false.

System.out.println(Boolean.toString(A.equals(B))); // true
</code>```

Also, the Boolean.toString(A.equals(B)) can be replaced by A.equals(B), which will return a Boolean in the same sense.

Body:
I have strings stored in SQLite database which are shown in an Activity. the problem is if I compare the text of the button with a string value it returns false while equals show it matches. I am curious to know who it is returning false while they are both the same.

I have tried and tostring methods.

while (result.moveToNext()) {

 Button btn = new Button(this);
 btn.setWidth(100);
 btn.setHeight(40);
 //    btn.setSingleLine(); //keep text in single line don't break big words
 //    btn.setAutoSizeTextTypeUniformWithConfiguration(1, 15, 1,
 //          TypedValue.COMPLEX_UNIT_DIP);
 messageReceived = result.getString(1).trim();
 btn.setText(result.getString(1).trim());

 String btnText = btn.getText().toString().trim();

 String Value = Boolean.toString(btnText == messageReceived);
 Toast toast = Toast.makeText(this, Value, Toast.LENGTH_LONG);
 toast.setGravity(Gravity.CENTER, 5, 5);
 toast.show();

 if (messageReceived.equals(btnText)) {
  Toast toast2 = Toast.makeText(this, "matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 } else {
  Toast toast2 = Toast.makeText(this, "Not Matched", Toast.LENGTH_LONG);
  toast2.setGravity(Gravity.LEFT, 0, 0);
  toast2.show();
 }

 Toast.makeText(this, "A: " + btn.getText() + " B: " + messageReceived, Toast.LENGTH_LONG).show();

 btn.setOnClickListener(this);
 grid.addView(btn);

 //messageReceived="pungi";

 if (btnText == messageReceived) {
  btn.setBackgroundColor(Color.YELLOW);
 }

}

Body:
Oh, this is a good one. Boolean.toString(stringA == stringB) is actually doing a reference comparison; that is, checking if both objects are pointing to the same memory location. String.equals(), on the other hand, compares the values.

String A = new String("five");
String B = new String("five");

System.out.println(Boolean.toString(A == B)); // false.

System.out.println(Boolean.toString(A.equals(B))); // true

Also, the Boolean.toString(A.equals(B)) can be replaced by A.equals(B), which will return a Boolean in the same sense.


问:
How can I do something like foreach in Stata using R?
I'm new to R and am using Stata. I can loop through the variables using foreach and forvalue in Stata.

I would like to loop over column rather than loop over row. For example, I have column named var1, var2, var3. And the data as below:

```<code>var1 var2 var3
  1    1   1
  2   999  3
 999   2  999
</code>```

I would like to recode all "999" values in the variables to missing. In Stata, I can do

```<code>forvalue i = 1(1)3{
  replace var`i' ="NA" if var`i' =="999"
}
</code>```

Therefore, I have the outcome like

```<code>var1 var2 var3
  1    1   1
  2   NA   3
  NA   2  NA
</code>```

Also, if I have column named ht, wgt, bmi, I would like to calculate the mean of the column and store the mean in new column with respective name. The dataset is as below:

```<code> ht     wgt   bmi
154.5  43.1 18.1
164.2  63   23.4
</code>```

In Stata, I can do

```<code>foreach i of varlist ht wgt bmi{
  gen `i'mean = mean(`i')
}
</code>```

And the outcome will be

```<code> ht    wgt   bmi  htmean wgtmean bmimean
154.5  43.1 18.1  159.35  53.05   20.75
164.2  63   23.4  159.35  53.05   20.75
</code>```

I've no idea how to do using R.

答:
There are lots of different ways to do these kinds of things. E.g. for the height, weight, BMI example, you can do this basically the same way you did in Stata, using a for loop:

```<code># For-loop approach
for (col in c("ht", "wgt", "bmi")) {
    new_col = paste0(col, "_mean")
    df2[, new_col] = mean(df2[, col])
}
</code>```

The difference is there's a stronger separation between symbols in code and strings in R, so you specify the column names as strings, use paste0 to create strings representing the new column names, and then add them to the dataframe.

Another way to do this is using the dplyr package and the mutate_at function, which will apply the same transformation to multiple columns:

```<code>library(dplyr)

df2 %>%
    mutate_at(c("ht", "wgt", "bmi"),
              list(mean = ~ mean(.)))
</code>```

The syntax is a little tricky: first we give the column names, then the next argument shows how we want to transform the columns. . is a placeholder for the current column, ~ means R won't immediately try to calculate mean(.) but will wait until we have actual values to substitute in. When we use a list and give a name to the transformation, like list(transform = ~ . + 2), dplyr automatically uses the name as a suffix, so  you get column names like x_transform, y_transform etc.

Body:
I'm new to R and am using Stata. I can loop through the variables using foreach and forvalue in Stata.

I would like to loop over column rather than loop over row. For example, I have column named var1, var2, var3. And the data as below:

var1 var2 var3
  1    1   1
  2   999  3
 999   2  999

I would like to recode all "999" values in the variables to missing. In Stata, I can do

forvalue i = 1(1)3{
  replace var`i' ="NA" if var`i' =="999"
}

Therefore, I have the outcome like

var1 var2 var3
  1    1   1
  2   NA   3
  NA   2  NA

Also, if I have column named ht, wgt, bmi, I would like to calculate the mean of the column and store the mean in new column with respective name. The dataset is as below:

 ht     wgt   bmi
154.5  43.1 18.1
164.2  63   23.4

In Stata, I can do

foreach i of varlist ht wgt bmi{
  gen `i'mean = mean(`i')
}

And the outcome will be

 ht    wgt   bmi  htmean wgtmean bmimean
154.5  43.1 18.1  159.35  53.05   20.75
164.2  63   23.4  159.35  53.05   20.75

I've no idea how to do using R.

Body:
There are lots of different ways to do these kinds of things. E.g. for the height, weight, BMI example, you can do this basically the same way you did in Stata, using a for loop:

# For-loop approach
for (col in c("ht", "wgt", "bmi")) {
    new_col = paste0(col, "_mean")
    df2[, new_col] = mean(df2[, col])
}

The difference is there's a stronger separation between symbols in code and strings in R, so you specify the column names as strings, use paste0 to create strings representing the new column names, and then add them to the dataframe.

Another way to do this is using the dplyr package and the mutate_at function, which will apply the same transformation to multiple columns:

library(dplyr)

df2 %>%
    mutate_at(c("ht", "wgt", "bmi"),
              list(mean = ~ mean(.)))

The syntax is a little tricky: first we give the column names, then the next argument shows how we want to transform the columns. . is a placeholder for the current column, ~ means R won't immediately try to calculate mean(.) but will wait until we have actual values to substitute in. When we use a list and give a name to the transformation, like list(transform = ~ . + 2), dplyr automatically uses the name as a suffix, so  you get column names like x_transform, y_transform etc.


问:
I am getting a warning for the website deployed via Github pages that uses a custom domain. how do i get around it?
Problem:

I am getting below warning on github pages. However, my custom domain http://www.dilipagheda.com still works.

I am curious why i am getting this warning and do i need to address it? if yes, how?

Error:

```<code>The custom domain for your GitHub Pages site is pointed at an outdated IP address. You must update your site's DNS records if you'd like it to be available via your custom domain
</code>```

答:
I'm not 100% sure why it still works (maybe they're phasing people out to the new addresses?) but here's how to fix it.

Go to your domain registrar, where you have previously set up your DNS records.  You need to update your A records to the new ones provided by github.  Right now they are:

```<code>185.199.108.153
185.199.109.153
185.199.110.153
185.199.111.153
</code>```

After that, you need to delete and re-add your custom domain in the repo settings.  I got these IP addresses and instructions here in the github documentation.

Body:
Problem:

I am getting below warning on github pages. However, my custom domain http://www.dilipagheda.com still works.

I am curious why i am getting this warning and do i need to address it? if yes, how?

Error:

The custom domain for your GitHub Pages site is pointed at an outdated IP address. You must update your site's DNS records if you'd like it to be available via your custom domain

Body:
I'm not 100% sure why it still works (maybe they're phasing people out to the new addresses?) but here's how to fix it.

Go to your domain registrar, where you have previously set up your DNS records.  You need to update your A records to the new ones provided by github.  Right now they are:

185.199.108.153
185.199.109.153
185.199.110.153
185.199.111.153

After that, you need to delete and re-add your custom domain in the repo settings.  I got these IP addresses and instructions here in the github documentation.


问:
implicit declaration of function ‘gmtime_r’
What do I need to do to make gcc include the declaration of gmtime_r(3) from time.h? Looking at /usr/include/time.h, gmtime_r and localtime_r are inside #ifdef __USE_POSIX.

Do I need to do something to turn __USE_POSIX on, like a command-line option? I'm running with -std=c99 now. I understand that __USE_* macros are not intended to be set directly by user code.

```<code>/* Return the `struct tm' representation of *TIMER
   in Universal Coordinated Time (aka Greenwich Mean Time).  */
extern struct tm *gmtime (const time_t *__timer) __THROW;

/* Return the `struct tm' representation
   of *TIMER in the local timezone.  */
extern struct tm *localtime (const time_t *__timer) __THROW;

#ifdef __USE_POSIX
/* Return the `struct tm' representation of *TIMER in UTC,
   using *TP to store the result.  */
extern struct tm *gmtime_r (const time_t *__restrict __timer,
                struct tm *__restrict __tp) __THROW;

/* Return the `struct tm' representation of *TIMER in local time,
   using *TP to store the result.  */
extern struct tm *localtime_r (const time_t *__restrict __timer,
                   struct tm *__restrict __tp) __THROW;
#endif  /* POSIX */

</code>```

答:
The proper way to do this is:

```<code>#define _POSIX_C_SOURCE 200112L
#include <time.h>
</code>```

This method indicates explicitly the features that a source file requires, making it self-contained. It is also portable to any POSIX system using any compiler. No special compiler flag is needed.

With GCC this code will compile with -std=c89, -std=c99, or any other value. Importantly what -std=gnu?? enables by default might differ depending on version or platform.

See Feature Test Macros for details.

Body:
What do I need to do to make gcc include the declaration of gmtime_r(3) from time.h? Looking at /usr/include/time.h, gmtime_r and localtime_r are inside #ifdef __USE_POSIX.

Do I need to do something to turn __USE_POSIX on, like a command-line option? I'm running with -std=c99 now. I understand that __USE_* macros are not intended to be set directly by user code.

/* Return the `struct tm' representation of *TIMER
   in Universal Coordinated Time (aka Greenwich Mean Time).  */
extern struct tm *gmtime (const time_t *__timer) __THROW;

/* Return the `struct tm' representation
   of *TIMER in the local timezone.  */
extern struct tm *localtime (const time_t *__timer) __THROW;

#ifdef __USE_POSIX
/* Return the `struct tm' representation of *TIMER in UTC,
   using *TP to store the result.  */
extern struct tm *gmtime_r (const time_t *__restrict __timer,
                struct tm *__restrict __tp) __THROW;

/* Return the `struct tm' representation of *TIMER in local time,
   using *TP to store the result.  */
extern struct tm *localtime_r (const time_t *__restrict __timer,
                   struct tm *__restrict __tp) __THROW;
#endif  /* POSIX */

Body:
The proper way to do this is:

#define _POSIX_C_SOURCE 200112L
#include <time.h>

This method indicates explicitly the features that a source file requires, making it self-contained. It is also portable to any POSIX system using any compiler. No special compiler flag is needed.

With GCC this code will compile with -std=c89, -std=c99, or any other value. Importantly what -std=gnu?? enables by default might differ depending on version or platform.

See Feature Test Macros for details.


问:
Android - in Android Pie (API 28) RadialGradient draws a rectangle instead of a circle
I'm trying to simulate a TorchView with a background image and a foreground image. It works well on API 27 and below, but draw a rectangle on API 28.

Any idea why it doesn't work on Android Pie?

On API 27 and below
API 28

Torch View class:

```
class TorchView : View, OnTouchListener {

    var mBitmapBackground: Bitmap? = null
    var mBitmapForeground: Bitmap? = null
    var mMask: Bitmap? = null
    private var mPosX = 0f
    private var mPosY = 0f

    private lateinit var paintMask: Paint
    private lateinit var paintBackground: Paint
    private lateinit var paintForeground: Paint

    private var radius = 150

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    fun initBitmaps(bitmapBackground: Bitmap, bitmapForeground: Bitmap, radius: Int){
        this.radius = radius
        mBitmapBackground = bitmapBackground
        mBitmapForeground = bitmapForeground
        mMask = makeRadGrad()
        mPosX = (bitmapBackground.width/2 - radius).toFloat()
        mPosY = (bitmapBackground.height/2 - radius).toFloat()
        invalidate()
    }

    fun init() {
        paintBackground = Paint()

        paintMask = Paint()
        paintMask.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)

        paintForeground = Paint()
        paintForeground.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)

        isFocusable = true
        isFocusableInTouchMode = true
        this.setOnTouchListener(this)
    }

    public override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val mask = mMask
        val bitmapForeground = mBitmapBackground
        val bitmapBackground = mBitmapForeground
        if(mask != null && bitmapForeground != null && bitmapBackground != null){
            canvas.save()
            canvas.drawBitmap(bitmapBackground, 0f, 0f, paintBackground)
            canvas.drawBitmap(mask, mPosX, mPosY, paintMask)
            canvas.drawBitmap(bitmapForeground, 0f, 0f, paintForeground)
            canvas.restore()
        }
    }

    private fun makeRadGrad(): Bitmap {
        val gradient = RadialGradient(
            radius.toFloat(), radius.toFloat(), radius.toFloat(), -0xff0100,
            0x00000000, android.graphics.Shader.TileMode.CLAMP
        )
        val p = Paint()
        p.isDither = true
        p.shader = gradient

        val bitmap = Bitmap.createBitmap(radius*2, radius*2, Config.ARGB_8888)
        val c = Canvas(bitmap)
        c.drawCircle(radius.toFloat(), radius.toFloat(), radius.toFloat(), p)

        return bitmap
    }

    override fun onTouch(v: View?, event: MotionEvent): Boolean {
        mPosX = event.x - radius
        mPosY = event.y - radius
        invalidate()
        return true
    }
}
```

答:
According to the Official Document

PorterDuff was deprecated in Android API 28

You should replace PorterDuff with BlendMode

Maybe you should do some compatible work on Android API 28

Body:
I'm trying to simulate a TorchView with a background image and a foreground image. It works well on API 27 and below, but draw a rectangle on API 28.

Any idea why it doesn't work on Android Pie?

On API 27 and below
API 28

Torch View class:

class TorchView : View, OnTouchListener {

    var mBitmapBackground: Bitmap? = null
    var mBitmapForeground: Bitmap? = null
    var mMask: Bitmap? = null
    private var mPosX = 0f
    private var mPosY = 0f

    private lateinit var paintMask: Paint
    private lateinit var paintBackground: Paint
    private lateinit var paintForeground: Paint

    private var radius = 150

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    fun initBitmaps(bitmapBackground: Bitmap, bitmapForeground: Bitmap, radius: Int){
        this.radius = radius
        mBitmapBackground = bitmapBackground
        mBitmapForeground = bitmapForeground
        mMask = makeRadGrad()
        mPosX = (bitmapBackground.width/2 - radius).toFloat()
        mPosY = (bitmapBackground.height/2 - radius).toFloat()
        invalidate()
    }

    fun init() {
        paintBackground = Paint()

        paintMask = Paint()
        paintMask.xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)

        paintForeground = Paint()
        paintForeground.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER)

        isFocusable = true
        isFocusableInTouchMode = true
        this.setOnTouchListener(this)
    }

    public override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val mask = mMask
        val bitmapForeground = mBitmapBackground
        val bitmapBackground = mBitmapForeground
        if(mask != null && bitmapForeground != null && bitmapBackground != null){
            canvas.save()
            canvas.drawBitmap(bitmapBackground, 0f, 0f, paintBackground)
            canvas.drawBitmap(mask, mPosX, mPosY, paintMask)
            canvas.drawBitmap(bitmapForeground, 0f, 0f, paintForeground)
            canvas.restore()
        }
    }

    private fun makeRadGrad(): Bitmap {
        val gradient = RadialGradient(
            radius.toFloat(), radius.toFloat(), radius.toFloat(), -0xff0100,
            0x00000000, android.graphics.Shader.TileMode.CLAMP
        )
        val p = Paint()
        p.isDither = true
        p.shader = gradient

        val bitmap = Bitmap.createBitmap(radius*2, radius*2, Config.ARGB_8888)
        val c = Canvas(bitmap)
        c.drawCircle(radius.toFloat(), radius.toFloat(), radius.toFloat(), p)

        return bitmap
    }

    override fun onTouch(v: View?, event: MotionEvent): Boolean {
        mPosX = event.x - radius
        mPosY = event.y - radius
        invalidate()
        return true
    }
}


问:
Get a list of elements into separated arrays
Hello fellow developer out there,

I'm new to Python & I need to write a web scraper to catch info from Scholar Google.

I ended up coding this function to get values using Xpath:

```<code>thread = browser.find_elements(By.XPATH,(" %s" % exp))
xArray = []

for t in thread:
    if not atr:
        xThread = t.text
    else:
        xThread = t.get_attribute('href')

    xArray.append(xThread)

    return xArray
</code>```

I don't know if it's a good or a bad solution. So, I humbly accept any suggestions to make it work better.

Anyway, my actual problem is that I am getting all authors name from the page I am scraping and what I really need are the names, grouped by result.
When I ask to print the results I wish I could have something like this:

```<code>[[author1, author2,author 3],[author 4,author 5,author6]]
</code>```

What am I getting right now is:

```<code>[author1,author3,author4,author5,author6]
</code>```

The structure is as follows:

```<code><div class="gs_a">
    LR Hisch,
<a href="/citations?user=xuBuLKYAAAAJ&hl=es&oi=sra">AM Gobin</a>
    ,AR Lowery,
<a href="/citations?user=ziumTX0AAAAJ&hl=es&oi=sra">F Tam</a>
 ... -Annals of biomedical ...,2006 - Springer
</div>
</code>```

And the same structure is repetead all over the page for different documents and authors.

And this is the call to the function I explained earlier:

```<code>authors = (clothoSpins(".//*[@class='gs_a']//a"))
</code>```

Which gets me the entire list of authors.

答:
Here is the logic (used selenium in the below code but update it as per your need).

Logic:

```<code>url = "https://scholar.google.com/scholar?hl=en&as_sdt=0%2C21&q=python&btnG="
driver.get(url)
# get the authors and add to list
listBooks = []
books = driver.find_elements_by_xpath("//div[@class='gs_a']")
for bookNum in books:
    auths = []
    authors = driver.find_elements_by_xpath("(//div[@class='gs_a'])[%s]/a|(//div[@class='gs_a'])[%s]/self::*[not(a)]"%(bookNum+1,bookNum+1))
    for author in authors:
        auths.append(author.text)
    listBooks.append(auths)
</code>```

Output:

```<code>[['F Pedregosa', 'G Varoquaux', 'A Gramfort'], ['PD Adams', 'PV Afonine'], ['TE Oliphant'], ['JW Peirce'], ['S Anders', 'PT Pyl', 'W Huber'], ['MF Sanner'], ['S Bird', 'E Klein'], ['M Lutz - 2001 - books.google.com'], ['G Rossum - 1995 - dl.acm.org'], ['W McKinney - … of the 9th Python in Science Conference, 2010 - pdfs.semanticscholar.org']]
</code>```

Screenshot:

Body:
Hello fellow developer out there,

I'm new to Python & I need to write a web scraper to catch info from Scholar Google.

I ended up coding this function to get values using Xpath:

thread = browser.find_elements(By.XPATH,(" %s" % exp))
xArray = []

for t in thread:
    if not atr:
        xThread = t.text
    else:
        xThread = t.get_attribute('href')

    xArray.append(xThread)

    return xArray

I don't know if it's a good or a bad solution. So, I humbly accept any suggestions to make it work better.

Anyway, my actual problem is that I am getting all authors name from the page I am scraping and what I really need are the names, grouped by result.
When I ask to print the results I wish I could have something like this:

[[author1, author2,author 3],[author 4,author 5,author6]]

What am I getting right now is:

[author1,author3,author4,author5,author6]

The structure is as follows:

    LR Hisch,
AM Gobin
    ,AR Lowery,
F Tam
 ... -Annals of biomedical ...,2006 - Springer

And the same structure is repetead all over the page for different documents and authors.

And this is the call to the function I explained earlier:

authors = (clothoSpins(".//*[@class='gs_a']//a"))

Which gets me the entire list of authors.

Body:
Here is the logic (used selenium in the below code but update it as per your need).

Logic:

url = "https://scholar.google.com/scholar?hl=en&as_sdt=0%2C21&q=python&btnG="
driver.get(url)
# get the authors and add to list
listBooks = []
books = driver.find_elements_by_xpath("//div[@class='gs_a']")
for bookNum in books:
    auths = []
    authors = driver.find_elements_by_xpath("(//div[@class='gs_a'])[%s]/a|(//div[@class='gs_a'])[%s]/self::*[not(a)]"%(bookNum+1,bookNum+1))
    for author in authors:
        auths.append(author.text)
    listBooks.append(auths)

Output:

[['F Pedregosa', 'G Varoquaux', 'A Gramfort'], ['PD Adams', 'PV Afonine'], ['TE Oliphant'], ['JW Peirce'], ['S Anders', 'PT Pyl', 'W Huber'], ['MF Sanner'], ['S Bird', 'E Klein'], ['M Lutz - 2001 - books.google.com'], ['G Rossum - 1995 - dl.acm.org'], ['W McKinney - … of the 9th Python in Science Conference, 2010 - pdfs.semanticscholar.org']]

Screenshot:


问:
How to determine the actual font used from javascript
From this answer, the rendered fonts can be inspected via Chrome's Dev Tools. But how can we get these info directly from the JavaScript?

For example, I want to create a webpage, which shows the actual rendered fonts on this page.

答:
I think this function will work

var div = document.getElementById( 'show' );

function showCSS( element, property ) {
    return window.getComputedStyle( element, null ).getPropertyValue( property );
}

let fontName = showCSS( div, 'font-family' );
var para = document.createElement("p");
var node = document.createTextNode('Font Name: ' + fontName);
para.appendChild(node);

var element = document.getElementById("fontName");
element.appendChild(para)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
 font-family: Arial
}</code>```

Text: Show Font Name

```

Body:
I think this function will work

var div = document.getElementById( 'show' );

function showCSS( element, property ) {
    return window.getComputedStyle( element, null ).getPropertyValue( property );
}

let fontName = showCSS( div, 'font-family' );
var para = document.createElement("p");
var node = document.createTextNode('Font Name: ' + fontName);
para.appendChild(node);

var element = document.getElementById("fontName");
element.appendChild(para)

div {
 font-family: Arial
}

<div id="show">Text: Show Font Name</div>
<div id="fontName"></div>