问:
Separate loggers for different methods
I use loggers to print traces that are specific to certain methods. That way when I want to debug my code I can activate traces in only those methods I care about.

I used to be able to do that with log4j v1. I would instrument selected methods with loggers like this:

```<code>private static void method1() {
  Logger logger = Logger.getLogger("org.examples.method1");
  logger.debug("Hello from method1");
  etc...
}
private static void method2() {
  Logger logger = Logger.getLogger("org.examples.method2");
  logger.debug("Hello from method2");
  etc...
}
</code>```

Then in my log4j.properties file, I would activate the traces like this:

```<code>log4j.logger.org.examples.method1=debug
log4j.logger.org.examples.method2=debug
etc...
</code>```

I am trying to replicate that behavior in log4j v2, but am having problems with it.

As far as instrumenting methods with loggers, I am doing OK. I do it the same way as with v1, except that I use LogManager.getLogger() instead of Logger.getLogger() (which does not exist in v2).

For activating the loggers, I need to use the v2 syntax, so I now do this:

```<code>logger.app.name = org.examples.method1
logger.app.level = debug

logger.app.name = org.examples.method2
logger.app.level = debug
</code>```

The problem is that when I run code that invokes both method1 and method2, only the method2 traces appear. In order to see the method1 traces, I have to comment out the method2 properties. Note that I have tried adding the additivity = true to both loggers, to no effect.

Piotr (see answer below) says that I need to have a different value for the '.app' bit in the above code. So instead I should write something like this:

```<code>logger.1.name = org.examples.method1
logger.1.level = debug

logger.2.name = org.examples.method2
logger.2.level = debug
</code>```

But this is really inconvenient for my use case because I have to:

Make sure I use the same number on all lines that pertain to a given logger

Make sure that I never use the same number for a different logger

One solution would be for me to write a macro that would automatically generate the two lines from the name of the logger. So, for a logger called org.examples.method1, it might generate:

```<code>logger.org_examples_method1.name = org.examples.method1
logger.org_examples_method1.level = debug
</code>```

Pietr also suggested that I might use the .yml or .json syntax instead of .properties. But when I tried the .yml syntax, I had the same problem, namely, if I write this:

```<code>  Loggers:
    logger:
        - name: org.examples.method1
          level: debug
    logger:
        - name: org.examples.method2
          level: debug
</code>```

Then only the method2 traces are being printed. And here, there does not seem to be a "second id" involved, so I am not sure how to fix it.

答:
As you remarked the properties format is not the easiest one to use, since it requires at least to lines per logger and plenty useless identifiers to generate. By comparison you have:

in the properties format:
```<code>logger.<id1>.name=org.example.foo
logger.<id1>.level=INFO
logger.<id2>.name=org.example.bar
logger.<id2>.level=DEBUG
</code>```

in the XML format:

<Loggers>
    <Logger name="org.example.foo" level="INFO"/>
    <Logger name="org.example.bar" level="DEBUG"/>
</Loggers>
```
</li>
<li>in the YAML format:
<pre class="lang-yaml prettyprint-override"><code>Loggers:
    logger:
        - name: org.example.foo
          level: INFO
        - name: org.example.bar
          level: DEBUG
</code>```

in the JSON format:

"loggers": {
    "logger": [
        { "name": "org.example.foo", "level": "INFO" },
        { "name": "org.example.bar", "level": "DEBUG" }
    ]
}
```

There has been some propositions recently aimed at shortening the properties format: see LOG4J2-3341, LOG4J2-3394 or my own PR #735.

Title: Separate loggers for different methods

Body:
I use loggers to print traces that are specific to certain methods. That way when I want to debug my code I can activate traces in only those methods I care about.

I used to be able to do that with log4j v1. I would instrument selected methods with loggers like this:

private static void method1() {
  Logger logger = Logger.getLogger("org.examples.method1");
  logger.debug("Hello from method1");
  etc...
}
private static void method2() {
  Logger logger = Logger.getLogger("org.examples.method2");
  logger.debug("Hello from method2");
  etc...
}

Then in my log4j.properties file, I would activate the traces like this:

log4j.logger.org.examples.method1=debug
log4j.logger.org.examples.method2=debug
etc...

I am trying to replicate that behavior in log4j v2, but am having problems with it.

As far as instrumenting methods with loggers, I am doing OK. I do it the same way as with v1, except that I use LogManager.getLogger() instead of Logger.getLogger() (which does not exist in v2).

For activating the loggers, I need to use the v2 syntax, so I now do this:

logger.app.name = org.examples.method1
logger.app.level = debug

logger.app.name = org.examples.method2
logger.app.level = debug

The problem is that when I run code that invokes both method1 and method2, only the method2 traces appear. In order to see the method1 traces, I have to comment out the method2 properties. Note that I have tried adding the additivity = true to both loggers, to no effect.

Piotr (see answer below) says that I need to have a different value for the '.app' bit in the above code. So instead I should write something like this:

logger.1.name = org.examples.method1
logger.1.level = debug

logger.2.name = org.examples.method2
logger.2.level = debug

But this is really inconvenient for my use case because I have to:

Make sure I use the same number on all lines that pertain to a given logger

Make sure that I never use the same number for a different logger

One solution would be for me to write a macro that would automatically generate the two lines from the name of the logger. So, for a logger called org.examples.method1, it might generate:

logger.org_examples_method1.name = org.examples.method1
logger.org_examples_method1.level = debug

Pietr also suggested that I might use the .yml or .json syntax instead of .properties. But when I tried the .yml syntax, I had the same problem, namely, if I write this:

  Loggers:
    logger:
        - name: org.examples.method1
          level: debug
    logger:
        - name: org.examples.method2
          level: debug

Then only the method2 traces are being printed. And here, there does not seem to be a "second id" involved, so I am not sure how to fix it.

Body:
As you remarked the properties format is not the easiest one to use, since it requires at least to lines per logger and plenty useless identifiers to generate. By comparison you have:

in the properties format:

logger.<id1>.name=org.example.foo
logger.<id1>.level=INFO
logger.<id2>.name=org.example.bar
logger.<id2>.level=DEBUG

in the XML format:

<Loggers>
    <Logger name="org.example.foo" level="INFO"/>
    <Logger name="org.example.bar" level="DEBUG"/>
</Loggers>

in the YAML format:

Loggers:
    logger:
        - name: org.example.foo
          level: INFO
        - name: org.example.bar
          level: DEBUG

in the JSON format:

"loggers": {
    "logger": [
        { "name": "org.example.foo", "level": "INFO" },
        { "name": "org.example.bar", "level": "DEBUG" }
    ]
}

There has been some propositions recently aimed at shortening the properties format: see LOG4J2-3341, LOG4J2-3394 or my own PR #735.


来源: stackexchange

问:
How can I get __LINE__ as a string constant?
In C++ (or C) how can I get the line number (__LINE__) as a string?

In particular, I want a macro that magically has "example.cpp:14" on line 14 of example.cpp. C++ automatically combines juxtaposed string literals, so I just need __LINE__ as a string.

答:
The trick to turning numerical constants into strings is the STR and XSTR macros, defined below:

```<code>#include <iostream>

//! See https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html
#define XSTR(a) STR(a)
#define STR(a) #a

#define LINE_AS_STR XSTR(__LINE__)
#define FILE_AND_LINE __FILE__ ":" LINE_AS_STR

int main() {
    constexpr const char* line = LINE_AS_STR;
    std::cout << "That was line \"" << line << "\"" << std::endl;
    std::cout << FILE_AND_LINE << std::endl;
}
</code>```

output:

```<code>That was line "11"
example.cpp:13
</code>```

https://godbolt.org/z/xzE1nWeMd

ContentLicense: CC BY-SA 4.0

Body:
The trick to turning numerical constants into strings is the STR and XSTR macros, defined below:

#include <iostream>

//! See https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html
#define XSTR(a) STR(a)
#define STR(a) #a

#define LINE_AS_STR XSTR(__LINE__)
#define FILE_AND_LINE __FILE__ ":" LINE_AS_STR

int main() {
    constexpr const char* line = LINE_AS_STR;
    std::cout << "That was line \"" << line << "\"" << std::endl;
    std::cout << FILE_AND_LINE << std::endl;
}

output:

That was line "11"
example.cpp:13

https://godbolt.org/z/xzE1nWeMd


问:
Internals of numpy.sum
Why are the two sums returning different values? In fact, if 0.1 is summed up 10 times in IEEE arithmetic, the result should not be exactly 1. It could be that np.sum() groups the sum differently, so that by chance the result is exactly 1. But is there is doc about this (besides studying the source code)? Surely, numpy isn't rounding off the result. And AFAIK, it is also using IEEE double floating point.</p>
```<code>import numpy as np

print(1-sum(np.ones(10)*0.1))
print(1-np.sum(np.ones(10)*0.1))

-----

1.1102230246251565e-16
0.0
</code>```

答:
Sorry, I found the solution in the docs. The algorithm of numpy.sum() is indeed more clever:

For floating point numbers the numerical precision of sum (and np.add.reduce) is in general limited by directly adding each number individually to the result causing rounding errors in every step. However, often numpy will use a numerically better approach (partial pairwise summation) leading to improved precision in many use-cases. This improved precision is always provided when no axis is given. When axis is given, it will depend on which axis is summed. Technically, to provide the best speed possible, the improved precision is only used when the summation is along the fast axis in memory. Note that the exact precision may vary depending on other parameters. In contrast to NumPy, Python’s math.fsum function uses a slower but more precise approach to summation. Especially when summing a large number of lower precision floating point numbers, such as float32, numerical errors can become significant. In such cases it can be advisable to use dtype="float64" to use a higher precision for the output.

See https://numpy.org/doc/stable/reference/generated/numpy.sum.html

Title: Internals of numpy.sum

Body:
Why are the two sums returning different values? In fact, if 0.1 is summed up 10 times in IEEE arithmetic, the result should not be exactly 1. It could be that np.sum() groups the sum differently, so that by chance the result is exactly 1. But is there is doc about this (besides studying the source code)? Surely, numpy isn't rounding off the result. And AFAIK, it is also using IEEE double floating point.

import numpy as np

print(1-sum(np.ones(10)*0.1))
print(1-np.sum(np.ones(10)*0.1))

-----

1.1102230246251565e-16
0.0


问:
Install docker on compute Canada
I need to install docker on compute Canada but I have multiple problems. firstly, I do not have access so I cant use the sudo command. as a result, I can't follow docker documents to install docker by binary source.
Secondly, in compute Canada documents are mentioned that I should use ./configure to install new software but I get this error: -bash: ./configure: No such file or directory.
any suggestion?</p>

答:
On ComputeCanada, like all shared HPC facilities, Docker is a joke.  We provide Singularity, which can do what Docker does (including use Dockerfiles).  We could also provide Podman, which is almost a pure/fixed Docker clone, and possibly a little easier to use than Singularity.

"./configure" is a common way to configure a package, but depends on the package providing such a script.  If it doesn't work, you are probably trying the command in the wrong location.  Most open-source packages do provide such a script in the base of their source tree, though some are simpler Makefile-based ones that just need "make".

You should simply open a support ticket for these issues, since none of them are new or novel.  support@computecanada.ca - and please provide as much information about what you're trying to do as possible.

I am ComputeCanada staff.  Feel free to email me as well (hahn@sharcnet.ca).

Title: Install docker on compute Canada


问:
How to set samesite=none, secure=true in Beego?
I have to set cookies as samesite = none and secure = true for my 3D pay URL. I've spent a lot of time trying to solve problem. How can i do it?

simple example for PHP

```<code>setcookie('cross-site-cookie', 'bar', ['samesite' => 'None', 'secure' => true]);
</code>```

I tried this method in Beego:

```<code>beego.BConfig.WebConfig.Session.SessionCookieSameSite = http.SameSiteNoneMode
</code>```

答:
hope this would help you:</p>
```<code>http.SetCookie(c.Ctx.ResponseWriter, &http.Cookie{
                Name:     "sessionid",
                Value:    c.CruSession.SessionID(),
                Path:     "/",
                Domain:   "",
                MaxAge:   86400,
                Secure:   true,
                HttpOnly: true,
                SameSite: http.SameSiteNoneMode,
            })
</code>```

Body:
I have to set cookies as samesite = none and secure = true for my 3D pay URL. I've spent a lot of time trying to solve problem. How can i do it?

simple example for PHP

setcookie('cross-site-cookie', 'bar', ['samesite' => 'None', 'secure' => true]);

I tried this method in Beego:

beego.BConfig.WebConfig.Session.SessionCookieSameSite = http.SameSiteNoneMode

Body:
hope this would help you:

http.SetCookie(c.Ctx.ResponseWriter, &http.Cookie{
                Name:     "sessionid",
                Value:    c.CruSession.SessionID(),
                Path:     "/",
                Domain:   "",
                MaxAge:   86400,
                Secure:   true,
                HttpOnly: true,
                SameSite: http.SameSiteNoneMode,
            })


问:
React Router Dom V6 pass array to path
I want to render same page by multiple routes in react-router-dom v6 like how it was in v5.
However, I couldn't find a efficient way to do it.

Example in v5 I can do this:

```<code>    <BrowserRouter>
      <Switch>
        <Route path={["/dashboard", "/home"]} render={<Home />} />
        <Route path="/other" render={<OtherPage/>} />
        <Route path={["/", "/404"]} render={<NotFound />} />
      </Switch>
    </BrowserRouter>

</code>```

But in v6, it is said that the path needs to be a string.

The only way I found that can achieve this is to separate them as follow:

```<code>    <BrowserRouter>
      <Routes>
        <Route path="/dashboard" element={<Home />} />
        <Route path="/home" element={<Home />} />
      </Routes>
    </BrowserRouter>

</code>```

Which means I have to write <Home /> multiple times.

I want to keep my code as CLEAN as possible.

I checked the official documentation, but didn't mention about this part. And I did research, but couldn't find a solution.

答:
I created this helper function and it works in React Router v6:

const renderMultiRoutes = ({ element: Element, paths, ...rest }: MultiRoutes) =>
  paths.map((path) => <Route key={path} path={path} {...rest} element={Element} />);
```
<p>Then I can do the following:</p>
```<Routes>
  {renderMultiRoutes({
    paths: ['/', '/dashboard'],
    element: <Feature />,
  })}
</Routes>
```

Title: React Router Dom V6 pass array to path

Body:
I want to render same page by multiple routes in react-router-dom v6 like how it was in v5.
However, I couldn't find a efficient way to do it.

Example in v5 I can do this:

    <BrowserRouter>
      <Switch>
        <Route path={["/dashboard", "/home"]} render={<Home />} />
        <Route path="/other" render={<OtherPage/>} />
        <Route path={["/", "/404"]} render={<NotFound />} />
      </Switch>
    </BrowserRouter>

But in v6, it is said that the path needs to be a string.

The only way I found that can achieve this is to separate them as follow:

    <BrowserRouter>
      <Routes>
        <Route path="/dashboard" element={<Home />} />
        <Route path="/home" element={<Home />} />
      </Routes>
    </BrowserRouter>

Which means I have to write <Home /> multiple times.

I want to keep my code as CLEAN as possible.

I checked the official documentation, but didn't mention about this part. And I did research, but couldn't find a solution.

Body:
I created this helper function and it works in React Router v6:

const renderMultiRoutes = ({ element: Element, paths, ...rest }: MultiRoutes) =>
  paths.map((path) => <Route key={path} path={path} {...rest} element={Element} />);

Then I can do the following:

<Routes>
  {renderMultiRoutes({
    paths: ['/', '/dashboard'],
    element: <Feature />,
  })}
</Routes>


问:
Select unique characters present in one list in a list of lists
I am trying to filter all the characters that are present in a that are not present in b and c. I want to do this from the list l.

```<code>a<-c("A", "B", "C", "D", "E")
b<-c("A", "E", "I", "O", "U")
c<-c("H", "E", "L", "L", "O")
l<-list(a,b,c)
</code>```

So the answer should be BCD.

答:
We could use setdiff as well

```<code>setdiff(l[[1]], unlist(l[-1]))
[1] "B" "C" "D"
</code>```

Body:
I am trying to filter all the characters that are present in a that are not present in b and c. I want to do this from the list l.

a<-c("A", "B", "C", "D", "E")
b<-c("A", "E", "I", "O", "U")
c<-c("H", "E", "L", "L", "O")
l<-list(a,b,c)

So the answer should be BCD.

Body:
We could use setdiff as well

setdiff(l[[1]], unlist(l[-1]))
[1] "B" "C" "D"


问:
create lists from google sheet

I have a google sheet looks like the image, how could I create two lists using Python.
list_1 = [Country,State,State,State,City,City,City,City]
list_2 = [USA,California,Washington ,New York,San Francisco, Los Angeles,Seattle,New York City]
Thanks!

答:
```<code>#read a excel sheet
sheed_df = pd.read_excel("<path to excel sheet>")
list_1 = []
list_2 = []
title = []
number = []
# find index of each header and find name of the header
# header means the value filling list_1
for num in range (sheed_df['No'].valus):
    title_row = sheed_df[sheed_df['No'] == num]
    topic = title_row ['Topic'].values[0]
    title.append(topic)
    number.append(title_row.index.values[0])
number.append(sheed_df.tail(1).index.valus[0])
# now you have all information and you can create a list
for i , j in enumerate(title):
     counters = 1
     if i+1 <= len(number):
         for itr in range (number[i+1]-number[i]):
              index_topic = number[i] + counters
              list_1.append(j)
              list_2.append(sheed_df.iloc[index_topic,1])
              counters = counters + 1

</code>```

Title: create lists from google sheet


问:
Count date range based on criteria
Let´s suppose I have generated a report with dates (day/month/year) when soccer teams won titles. This is how the report is going to look like:

Area
Team
Champions League
Europe    League

England
Chelsea
27/01/2021
15/01/2021

Spain
Real Madri
27/02/2021
20/01/2021

Spain
Barcelona

18/02/2021

France
PSG
27/03/2021
27/02/2021

My objective here is going to count how many titles each area won per month. So, this is how my desired output looks like:

Area
January
February
March

England
2

Spain
1
2

France

1
1

What I tried to do was the following (for January and England):

```<code>=COUNTIFS(Table[[#All],[Champions League]:[Europe League]],">01/01/2021",Table[[#All],[Champions League]:[Europe League]],"<31/01/2022",Table[[#All],[Area]],"=England")
</code>```

However, my output using this formula is "#VALUE!". Can you please help trying to figure out what I am doing wrong?

答:
COUNTIFS doesn't like your dissimilar sized criteria ranges.

You would be better served setting your data up in a tabular format like so:

Area
Team
Championship
Date

England
Chelsea
Champions League
1/27/2021

England
Chelsea
Europe League
1/15/2021

Spain
Real Madri
Champions League
2/27/2021

Spain
Real Madri
Europe League
1/20/2021

Spain
Barcelona
Europe League
2/18/2021

France
PSG
Champions League
3/27/2021

France
PSG
Europe League
2/27/2021

You get your data into this format easily by using Power Query.  Simply load the data in, select the two date columns, and Unpivot.

And then you could use a simple Pivot Table to display the data in your preferred format:

To turn the full date to just the Month name select one cell > right-click > Group > by Month

Title: Count date range based on criteria

Body:
Let´s suppose I have generated a report with dates (day/month/year) when soccer teams won titles. This is how the report is going to look like:

Area
Team
Champions League
Europe    League

England
Chelsea
27/01/2021
15/01/2021

Spain
Real Madri
27/02/2021
20/01/2021

Spain
Barcelona

18/02/2021

France
PSG
27/03/2021
27/02/2021

My objective here is going to count how many titles each area won per month. So, this is how my desired output looks like:

Area
January
February
March

England
2

Spain
1
2

France

1
1

What I tried to do was the following (for January and England):

=COUNTIFS(Table[[#All],[Champions League]:[Europe League]],">01/01/2021",Table[[#All],[Champions League]:[Europe League]],"<31/01/2022",Table[[#All],[Area]],"=England")

However, my output using this formula is "#VALUE!". Can you please help trying to figure out what I am doing wrong?


问:
The length of labels must equal to the number of rows in the input data
I don't know why I'm getting this error! My data training is a sparse matrix.

```<code>dim(training)
> 14407 161

dim(label.train)
> 14407 1

xgb.train <- xgb.DMatrix(data = training, label = label.train)
> Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) :
The length of labels must equal to the number of rows in the input data
</code>```

I have checked my data and:

label.train is a data.frame

training does not have all zero rows or columns

all values in training are numeric

PS. My data is huge so I can't post a reproducible code, just need tips for what might be wrong from those who have experienced this error.

答:
It is most likely your other script's data did not have any missing (NA) value. When you sparse (I'm guessing you were trying to one hot encoding columns) a data frame to a matrix, R will automatically remove missing value and hence the error.

The best practice is to use "is.na" to replace all nulls to 0.

ContentLicense: CC BY-SA 3.0

Body:
I don't know why I'm getting this error! My data training is a sparse matrix.

dim(training)
> 14407 161

dim(label.train)
> 14407 1

xgb.train <- xgb.DMatrix(data = training, label = label.train)
> Error in setinfo.xgb.DMatrix(dmat, names(p), p[[1]]) :
The length of labels must equal to the number of rows in the input data

I have checked my data and:

label.train is a data.frame

training does not have all zero rows or columns

all values in training are numeric

PS. My data is huge so I can't post a reproducible code, just need tips for what might be wrong from those who have experienced this error.


问:
navbar is not appearing on mobile phones view
my problem is when i press on the hamburger menu the whole menu does not appear (in mobile view) - even though i'm sure about the code and it working properly, the only problem in mobile view i can't diplay all the main menu ( work - blog - contact ) so when i hover on the icon i don't get anything.

nav-bar {
  font-size: 18px;
  padding-bottom: 10px;
}

.main-menu {
  list-style-type: none;
}

.main-menu li {
  text-align: center;
  margin: 15px auto;
}

.main-menu a {
  text-decoration: none;
  color: black;
}

.main-menu a:hover {
  text-decoration: overline;
}

.main-menu li i {
  padding-right: 10px;
}

.logo {
  margin-top: 10px;
  margin-left: 20px;
  width: 200px;
}

.logo img {
  width: 40px;
  border-radius: 20px;
  margin-top: 20px;
  margin-left: 30px;
  margin-bottom: 30px;
}

.menu-toggle {
  position: absolute;
  top: 10px;
  right: 20px;
  cursor: pointer;
  color: black;
  font-size: 24px;
}

.active {
  display: block;
}

.main-menu {
  display: none;
}

@media screen and (min-width: 60rem) {
  /*Desktop view*/
  .nav-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 0;
    min-height: 70px;
  }
  .main-menu {
    display: flex;
    flex-wrap: wrap;
    margin-right: 30px;
  }
  .main-menu li {
    margin: 0px 0px 5px 0px;
  }
  .main-menu a {
    margin-left: 40px;
  }
  /* Hide the menu toogle icon when the full menu is visible */
  .menu-toggle {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="nav-bar">
  <!-- The Toggle Button is used to hide and show the menu for a Mobile Layout -->
  <span class="menu-toggle">
         <i class="fas fa-bars"></i>
    </span>

    <img src="img/logo.png" alt="Logo">

  <ul class="main-menu">
    <li>
      <i class="fas fa-home"></i>Works
    </li>
    <li>
      <i class="fas fa-university"></i>Blogs
    </li>
    <li>
      <i class="fas fa-headset"></i>Contact
    </li>
  </ul>
</nav></code>```

答:
Your main-menu CSS is set to display none for mobile.

.main-menu {
  display: none;
}
```
<p>You need to tell it what to do like you did with desktop:</p>
<pre class="lang-css prettyprint-override"><code>.main-menu {
  display: flex;
  flex-wrap: wrap;
  margin-right: 30px;
}
</code>```

Body:
my problem is when i press on the hamburger menu the whole menu does not appear (in mobile view) - even though i'm sure about the code and it working properly, the only problem in mobile view i can't diplay all the main menu ( work - blog - contact ) so when i hover on the icon i don't get anything.

nav-bar {
  font-size: 18px;
  padding-bottom: 10px;
}

.main-menu {
  list-style-type: none;
}

.main-menu li {
  text-align: center;
  margin: 15px auto;
}

.main-menu a {
  text-decoration: none;
  color: black;
}

.main-menu a:hover {
  text-decoration: overline;
}

.main-menu li i {
  padding-right: 10px;
}

.logo {
  margin-top: 10px;
  margin-left: 20px;
  width: 200px;
}

.logo img {
  width: 40px;
  border-radius: 20px;
  margin-top: 20px;
  margin-left: 30px;
  margin-bottom: 30px;
}

.menu-toggle {
  position: absolute;
  top: 10px;
  right: 20px;
  cursor: pointer;
  color: black;
  font-size: 24px;
}

.active {
  display: block;
}

.main-menu {
  display: none;
}

@media screen and (min-width: 60rem) {
  /*Desktop view*/
  .nav-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 0;
    min-height: 70px;
  }
  .main-menu {
    display: flex;
    flex-wrap: wrap;
    margin-right: 30px;
  }
  .main-menu li {
    margin: 0px 0px 5px 0px;
  }
  .main-menu a {
    margin-left: 40px;
  }
  /* Hide the menu toogle icon when the full menu is visible */
  .menu-toggle {
    display: none;
  }
}

      Works

      Blogs

      Contact

Body:
Your main-menu CSS is set to display none for mobile.

.main-menu {
  display: none;
}

You need to tell it what to do like you did with desktop:

.main-menu {
  display: flex;
  flex-wrap: wrap;
  margin-right: 30px;
}


问:
AWS sagemaker error - AttributeError: 'NoneType' object has no attribute 'startswith'
As per this - How to use a pretrained model from s3 to predict some data? , I was trying to use an existing model to create an endpoint, but I was facing the following error -

```<code>    Traceback (most recent call last):
  File "/miniconda3/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 55, in handle
    self.handle_request(listener_name, req, client, addr)
  File "/miniconda3/lib/python3.7/site-packages/gunicorn/workers/ggevent.py", line 143, in handle_request
    super().handle_request(listener_name, req, sock, addr)
  File "/miniconda3/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 106, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_sklearn_container/serving.py", line 124, in main
    serving_env.module_dir)
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_sklearn_container/serving.py", line 101, in import_module
    user_module = importlib.import_module(module_name)
  File "/miniconda3/lib/python3.7/importlib/__init__.py", line 118, in import_module
    if name.startswith('.'):
</code>```

As per Problem deploying the best estimator gotten with sagemaker.estimator.Estimator (w/ sklearn custom image), https://forums.aws.amazon.com/thread.jspa?threadID=313838 , I am using the correct env variables (along with SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT, SAGEMAKER_PROGRAM, and SAGEMAKER_SUBMIT_DIRECTORY), but somehow the health checks are failing while creation of the endpoint.

I tried the similar thing via AWS console and it is working surprisingly.
Is there a work around for this to do it via code?

My code snippet:

```<code>trainedmodel = sagemaker.model.Model(
model_data='s3://my-bucket/my-key/output/model.tar.gz',
image='my-image',
env={"SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv",
     "SAGEMAKER_USE_NGINX": "True",
     "SAGEMAKER_WORKER_CLASS_TYPE": "gevent",
     "SAGEMAKER_KEEP_ALIVE_SEC": "60",
     "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
     "SAGEMAKER_ENABLE_CLOUDWATCH_METRICS": "false",
     "SAGEMAKER_PROGRAM": "my-script.py",
     "SAGEMAKER_REGION": "us-east-1",
     "SAGEMAKER_SUBMIT_DIRECTORY": "s3://my-bucket/my-key/source/sourcedir.tar.gz"
    },
role=role)

trainedmodel.deploy(initial_instance_count=1, instance_type='ml.c4.xlarge', endpoint_name = 'my-endpoint')
</code>```

答:
What worked for me was creating the model from a training job and then using the env variables listed in the question:</p>
```<code>training_src_file     = "s3://bucket_data_assets/training-src-files.tar.gz"
churn_model = sagemaker_session.create_model_from_job(
    training_job_name=completed_training_job_name,
    name=None,
    role=role, image_uri=None,
    model_data_url=None,
    env={"SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv",
     "SAGEMAKER_USE_NGINX": "True",
     "SAGEMAKER_WORKER_CLASS_TYPE": "gevent",
     "SAGEMAKER_KEEP_ALIVE_SEC": "60",
     "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
     "SAGEMAKER_ENABLE_CLOUDWATCH_METRICS": "false",
     "SAGEMAKER_PROGRAM": "train.py", #the entry point present in training-src-files.tar.gz
     "SAGEMAKER_REGION": "us-east-1",
     "SAGEMAKER_SUBMIT_DIRECTORY": training_src_file,
    }
</code>```

Body:
As per this - How to use a pretrained model from s3 to predict some data? , I was trying to use an existing model to create an endpoint, but I was facing the following error -

    Traceback (most recent call last):
  File "/miniconda3/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 55, in handle
    self.handle_request(listener_name, req, client, addr)
  File "/miniconda3/lib/python3.7/site-packages/gunicorn/workers/ggevent.py", line 143, in handle_request
    super().handle_request(listener_name, req, sock, addr)
  File "/miniconda3/lib/python3.7/site-packages/gunicorn/workers/base_async.py", line 106, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_sklearn_container/serving.py", line 124, in main
    serving_env.module_dir)
  File "/miniconda3/lib/python3.7/site-packages/sagemaker_sklearn_container/serving.py", line 101, in import_module
    user_module = importlib.import_module(module_name)
  File "/miniconda3/lib/python3.7/importlib/__init__.py", line 118, in import_module
    if name.startswith('.'):

As per Problem deploying the best estimator gotten with sagemaker.estimator.Estimator (w/ sklearn custom image), https://forums.aws.amazon.com/thread.jspa?threadID=313838 , I am using the correct env variables (along with SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT, SAGEMAKER_PROGRAM, and SAGEMAKER_SUBMIT_DIRECTORY), but somehow the health checks are failing while creation of the endpoint.

I tried the similar thing via AWS console and it is working surprisingly.
Is there a work around for this to do it via code?

My code snippet:

trainedmodel = sagemaker.model.Model(
model_data='s3://my-bucket/my-key/output/model.tar.gz',
image='my-image',
env={"SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv",
     "SAGEMAKER_USE_NGINX": "True",
     "SAGEMAKER_WORKER_CLASS_TYPE": "gevent",
     "SAGEMAKER_KEEP_ALIVE_SEC": "60",
     "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
     "SAGEMAKER_ENABLE_CLOUDWATCH_METRICS": "false",
     "SAGEMAKER_PROGRAM": "my-script.py",
     "SAGEMAKER_REGION": "us-east-1",
     "SAGEMAKER_SUBMIT_DIRECTORY": "s3://my-bucket/my-key/source/sourcedir.tar.gz"
    },
role=role)

trainedmodel.deploy(initial_instance_count=1, instance_type='ml.c4.xlarge', endpoint_name = 'my-endpoint')

Body:
What worked for me was creating the model from a training job and then using the env variables listed in the question:

training_src_file     = "s3://bucket_data_assets/training-src-files.tar.gz"
churn_model = sagemaker_session.create_model_from_job(
    training_job_name=completed_training_job_name,
    name=None,
    role=role, image_uri=None,
    model_data_url=None,
    env={"SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT": "text/csv",
     "SAGEMAKER_USE_NGINX": "True",
     "SAGEMAKER_WORKER_CLASS_TYPE": "gevent",
     "SAGEMAKER_KEEP_ALIVE_SEC": "60",
     "SAGEMAKER_CONTAINER_LOG_LEVEL": "20",
     "SAGEMAKER_ENABLE_CLOUDWATCH_METRICS": "false",
     "SAGEMAKER_PROGRAM": "train.py", #the entry point present in training-src-files.tar.gz
     "SAGEMAKER_REGION": "us-east-1",
     "SAGEMAKER_SUBMIT_DIRECTORY": training_src_file,
    }


问:
How to exit fullscreen on pressing ESC or by toggling the fullscreen button
In the below snippet, when "Make a fullscreen" button is pressed, the iFrame enters fullscreen mode. I'm looking for a solution to exit fullscreen mode on pressing "ESC" or by pressing "Make fullscreen button" again.

```<code><button onclick="makeFullscreen('game');">[Make a fullscreen]</button>
</code>```
```<code>function makeFullscreen(id){
    var el = document.getElementById(id);
    el.style = "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"
}
</code>```

Fully working

```<code>const fullscreenStyle = "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:99999;"

const normalStyle = "width:1000px;height:700px;border:0;"

function enterFullScreen(el) {
  el.style = fullscreenStyle;
  document.querySelector('.button1').style = 'position:absolute;top:0;right:0;z-index:999999;';
}

function exitFullScreen(el) {
  el.style = normalStyle;
  document.querySelector('.button1').style = 'position:absolute;top:auto;right:auto;';
}

function toggleFullScreen() {
  var el = document.getElementById("game");
  if (el.style.position === "fixed") {
    exitFullScreen(el);
  } else {
    enterFullScreen(el);
  }
}

document.addEventListener("keydown", function(e) {
  if (e.key === "Escape") {
    var el = document.getElementById("game");
    exitFullScreen(el);
  }
}, false);
</code>```

答:
Since Fullscreen API is out, another solution can be that instead of binding Make a Fullscreen logic to the button, bind the logic for toggling full screen. For that :

Store fullscreen and normal mode CSS in 2 separate variables

Create 2 functions, enterFullscreen and exitFullScreen

Create a 3rd function toggleFullScreen that checks the mode and does the following :

If fullscreen mode is ON, call exitFullscreen

Else call enterFullScreen

To implement exit on pressing ESC

Add an event listener for keydown events

When the event is triggered, check the key in the event.

If the key matches Escape, call exitFullScreen

The following solution does the same.

```<code><!DOCTYPE html>
<html lang="en">
<body>
  <iframe id="game" style="width:1000px;height:700px;border:0;" allowfullscreen="true" msallowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true" sandbox="allow-same-origin allow-popups allow-scripts allow-pointer-lock allow-orientation-lock allow-popups" src="https://randomurl.com/">
  </iframe>
  <button onclick="toggleFullScreen('game');">
     [Toggle fullscreen]
  </button>
</body>
<script type="text/javascript">
 const fullscreenStyle = "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"
 const normalStyle = "width:1000px;height:700px;border:0;"

 function enterFullScreen(el) {
    el.style = fullscreenStyle;
 }

 function exitFullScreen(el) {
    el.style = normalStyle;
 }

 function toggleFullScreen() {
   var el = document.getElementById("game");
   if (el.style.position === "fixed") {
     exitFullScreen(el);
   } else {
     enterFullScreen(el);
   }
 }

 document.addEventListener("keydown", function(e) {
   if (e.key === "Escape") {
     var el = document.getElementById("game");
     exitFullScreen(el);
   }
 }, false);
</script>
</html>
</code>```

Body:
In the below snippet, when "Make a fullscreen" button is pressed, the iFrame enters fullscreen mode. I'm looking for a solution to exit fullscreen mode on pressing "ESC" or by pressing "Make fullscreen button" again.

<button onclick="makeFullscreen('game');">[Make a fullscreen]</button>

function makeFullscreen(id){
    var el = document.getElementById(id);
    el.style = "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"
}

Fully working

const fullscreenStyle = "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:99999;"

const normalStyle = "width:1000px;height:700px;border:0;"

function enterFullScreen(el) {
  el.style = fullscreenStyle;
  document.querySelector('.button1').style = 'position:absolute;top:0;right:0;z-index:999999;';
}

function exitFullScreen(el) {
  el.style = normalStyle;
  document.querySelector('.button1').style = 'position:absolute;top:auto;right:auto;';
}

function toggleFullScreen() {
  var el = document.getElementById("game");
  if (el.style.position === "fixed") {
    exitFullScreen(el);
  } else {
    enterFullScreen(el);
  }
}

document.addEventListener("keydown", function(e) {
  if (e.key === "Escape") {
    var el = document.getElementById("game");
    exitFullScreen(el);
  }
}, false);

Body:
Since Fullscreen API is out, another solution can be that instead of binding Make a Fullscreen logic to the button, bind the logic for toggling full screen. For that :

Store fullscreen and normal mode CSS in 2 separate variables

Create 2 functions, enterFullscreen and exitFullScreen

Create a 3rd function toggleFullScreen that checks the mode and does the following :

If fullscreen mode is ON, call exitFullscreen

Else call enterFullScreen

To implement exit on pressing ESC

Add an event listener for keydown events

When the event is triggered, check the key in the event.

If the key matches Escape, call exitFullScreen

The following solution does the same.

<!DOCTYPE html>
<html lang="en">
<body>
  <iframe id="game" style="width:1000px;height:700px;border:0;" allowfullscreen="true" msallowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true" sandbox="allow-same-origin allow-popups allow-scripts allow-pointer-lock allow-orientation-lock allow-popups" src="https://randomurl.com/">
  </iframe>
  <button onclick="toggleFullScreen('game');">
     [Toggle fullscreen]
  </button>
</body>
<script type="text/javascript">
 const fullscreenStyle = "position:fixed; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"
 const normalStyle = "width:1000px;height:700px;border:0;"

 function enterFullScreen(el) {
    el.style = fullscreenStyle;
 }

 function exitFullScreen(el) {
    el.style = normalStyle;
 }

 function toggleFullScreen() {
   var el = document.getElementById("game");
   if (el.style.position === "fixed") {
     exitFullScreen(el);
   } else {
     enterFullScreen(el);
   }
 }

 document.addEventListener("keydown", function(e) {
   if (e.key === "Escape") {
     var el = document.getElementById("game");
     exitFullScreen(el);
   }
 }, false);
</script>
</html>


问:
Location of the error token always starts at 0
I'm writing a parser with error handling. I would like to output to the user the exact location of the parts of the input that couldn't be parsed.

However, the location of the error token always starts at 0, even if before it were parts that were parsed successfully.

Here's a heavily simplified example of what I did.
(The problematic part is probably in the parser.yy.)

Location.hh:

#pragma once
#include <string>

// The full version tracks position in bytes, line number and offset in the current line.
// Here however, I've shortened it to line number only.
struct Location
{
    int beginning, ending;
    operator std::string() const { return std::to_string(beginning) + '-' + std::to_string(ending); }
};
```
<p><em>LexerClass.hh</em>:</p>
<pre class="lang-cc prettyprint-override"><code>#pragma once
#include <istream>
#include <string>
#if ! defined(yyFlexLexerOnce)
    #include <FlexLexer.h>
#endif
#include "Location.hh"

class LexerClass : public yyFlexLexer
{
    int currentPosition = 0;
protected:
    std::string *yylval = nullptr;
    Location *yylloc = nullptr;
public:
    LexerClass(std::istream &in) : yyFlexLexer(&in) {}
    [[nodiscard]] int yylex(std::string *const lval, Location *const lloc);
    void onNewLine() { yylloc->beginning = yylloc->ending = ++currentPosition; }
};
</code>```

lexer.ll:

```<code>%{
    #include "./parser.hh"
    #include "./LexerClass.hh"

    #undef  YY_DECL
    #define YY_DECL int LexerClass::yylex(std::string *const lval, Location *const lloc)
%}

%option c++ noyywrap
%option yyclass="LexerClass"

%%

%{
    yylval = lval;
    yylloc = lloc;
%}

[[:blank:]] ;
\n          { onNewLine(); }
[0-9]       { return yy::Parser::token::DIGIT; }
.           { return yytext[0]; }
</code>```

parser.yy:

```<code>%language "c++"

%code requires {
    #include "LexerClass.hh"
    #include "Location.hh"
}

%define api.parser.class {Parser}
%define api.value.type {std::string}
%define api.location.type {Location}
%parse-param {LexerClass &lexer}
%defines

%code {
    template<typename RHS>
    void calcLocation(Location &current, const RHS &rhs, const int n);
    #define YYLLOC_DEFAULT(Cur, Rhs, N) calcLocation(Cur, Rhs, N)

    #define yylex lexer.yylex
}

%token DIGIT

%%

numbers:
      %empty
    | numbers number ';' { std::cout << std::string(@number) << "\tnumber" << std::endl; }
    | error ';' { yyerrok; std::cerr << std::string(@error) << "\terror context" << std::endl; }
    ;

number:
      DIGIT {}
    | number DIGIT {}
    ;

%%

#include <iostream>

template<typename RHS>
inline void calcLocation(Location &current, const RHS &rhs, const int n)
{
    current = (n <= 1)
        ? YYRHSLOC(rhs, n)
        : Location{YYRHSLOC(rhs, 1).beginning, YYRHSLOC(rhs, n).ending};
}

void yy::Parser::error(const Location &location, const std::string &message)
{
    std::cout << std::string(location) << "\terror: " << message << std::endl;
}

int main()
{
    LexerClass lexer(std::cin);
    yy::Parser parser(lexer);
    return parser();
}
</code>```

For the input:

```<code>123
456
789;
123;
089
xxx
123;
765
432;
</code>```

expected output:

```<code>0-2 number
3-3 number
5-5 error: syntax error
4-6 error context
7-8 number
</code>```

actual output:

```<code>0-2 number
3-3 number
5-5 error: syntax error
0-6 error context
7-8 number
</code>```

答:
Here's your numbers rule, for reference (without actions, since they're not really relevant):

```<code>numbers:
      %empty
    | numbers number ';'
    | error ';'
</code>```

numbers is also your start symbol. It should be reasonably clear that there is nothing before a numbers non-terminal in any derivation. There is a top-level numbers non-terminal, which encompasses the entire input, and it starts with a numbers non-terminal which contains everything except the last number ;, and so on. All of these numbers start at the beginning.

Similarly, the error pseudotoken is at the start of some numbers derivation. So it, too, must start at the beginning of the input.

In other words, your statement that "the location of the error token always starts at 0, even if before it were parts that were parsed successfully" is untestable. The location of the error token always starts at 0, because there cannot be anything before it, and the output you're receiving is "expected". Or, at least, predictable; I understand that you didn't expect it, and it's an easy confusion to fall into. I didn't really see it until I ran the parser with tracing enabled, which is highly recommended; note that to do so, it's helpful to add an overload of std::operator(ostream&, Location const&).

Body:
I'm writing a parser with error handling. I would like to output to the user the exact location of the parts of the input that couldn't be parsed.

However, the location of the error token always starts at 0, even if before it were parts that were parsed successfully.

Here's a heavily simplified example of what I did.
(The problematic part is probably in the parser.yy.)

Location.hh:

#pragma once
#include <string>

// The full version tracks position in bytes, line number and offset in the current line.
// Here however, I've shortened it to line number only.
struct Location
{
    int beginning, ending;
    operator std::string() const { return std::to_string(beginning) + '-' + std::to_string(ending); }
};

LexerClass.hh:

#pragma once
#include <istream>
#include <string>
#if ! defined(yyFlexLexerOnce)
    #include <FlexLexer.h>
#endif
#include "Location.hh"

class LexerClass : public yyFlexLexer
{
    int currentPosition = 0;
protected:
    std::string *yylval = nullptr;
    Location *yylloc = nullptr;
public:
    LexerClass(std::istream &in) : yyFlexLexer(&in) {}
    [[nodiscard]] int yylex(std::string *const lval, Location *const lloc);
    void onNewLine() { yylloc->beginning = yylloc->ending = ++currentPosition; }
};

lexer.ll:

%{
    #include "./parser.hh"
    #include "./LexerClass.hh"

    #undef  YY_DECL
    #define YY_DECL int LexerClass::yylex(std::string *const lval, Location *const lloc)
%}

%option c++ noyywrap
%option yyclass="LexerClass"

%%

%{
    yylval = lval;
    yylloc = lloc;
%}

[[:blank:]] ;
\n          { onNewLine(); }
[0-9]       { return yy::Parser::token::DIGIT; }
.           { return yytext[0]; }

parser.yy:

%language "c++"

%code requires {
    #include "LexerClass.hh"
    #include "Location.hh"
}

%define api.parser.class {Parser}
%define api.value.type {std::string}
%define api.location.type {Location}
%parse-param {LexerClass &lexer}
%defines

%code {
    template<typename RHS>
    void calcLocation(Location &current, const RHS &rhs, const int n);
    #define YYLLOC_DEFAULT(Cur, Rhs, N) calcLocation(Cur, Rhs, N)

    #define yylex lexer.yylex
}

%token DIGIT

%%

numbers:
      %empty
    | numbers number ';' { std::cout << std::string(@number) << "\tnumber" << std::endl; }
    | error ';' { yyerrok; std::cerr << std::string(@error) << "\terror context" << std::endl; }
    ;

number:
      DIGIT {}
    | number DIGIT {}
    ;

%%

#include <iostream>

template<typename RHS>
inline void calcLocation(Location &current, const RHS &rhs, const int n)
{
    current = (n <= 1)
        ? YYRHSLOC(rhs, n)
        : Location{YYRHSLOC(rhs, 1).beginning, YYRHSLOC(rhs, n).ending};
}

void yy::Parser::error(const Location &location, const std::string &message)
{
    std::cout << std::string(location) << "\terror: " << message << std::endl;
}

int main()
{
    LexerClass lexer(std::cin);
    yy::Parser parser(lexer);
    return parser();
}

For the input:

123
456
789;
123;
089
xxx
123;
765
432;

expected output:

0-2 number
3-3 number
5-5 error: syntax error
4-6 error context
7-8 number

actual output:

0-2 number
3-3 number
5-5 error: syntax error
0-6 error context
7-8 number

Body:
Here's your numbers rule, for reference (without actions, since they're not really relevant):

numbers:
      %empty
    | numbers number ';'
    | error ';'

numbers is also your start symbol. It should be reasonably clear that there is nothing before a numbers non-terminal in any derivation. There is a top-level numbers non-terminal, which encompasses the entire input, and it starts with a numbers non-terminal which contains everything except the last number ;, and so on. All of these numbers start at the beginning.

Similarly, the error pseudotoken is at the start of some numbers derivation. So it, too, must start at the beginning of the input.

In other words, your statement that "the location of the error token always starts at 0, even if before it were parts that were parsed successfully" is untestable. The location of the error token always starts at 0, because there cannot be anything before it, and the output you're receiving is "expected". Or, at least, predictable; I understand that you didn't expect it, and it's an easy confusion to fall into. I didn't really see it until I ran the parser with tracing enabled, which is highly recommended; note that to do so, it's helpful to add an overload of std::operator(ostream&, Location const&).


问:
Where are the best explanations of memory management for iPhone?
I am looking for good explanations out there. I have a 1000 pages book about objective-c, but unfortunately the part about memory management, retain counting, is described pretty bad and hard to understand.</p>

答: CocoaDev always has pretty good resources and their intro to memory management is no exception.</p>

OwnerDisplayName: Unknown Individual

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: drewh


问:
Can I search hashtags on twitter with wildcards
I'm hoping to find a way to search for hashtags on twitter that contain the characters 'SF'.  For example, there are tweets that have #LVvsSF (yes I'm a 9er fan!) and I'd like to come up with a search string that would pull this tweet if it has the above hashtag or even #SEAvsSF.

I have tried '%23vsSF' and '#%23vsSF' but neither are working.

Thanks,

答:
Wildcards in Twitter search work only on phrases, inside quotes, with spaces on both sides. For example:

```<code>"this is the * time today that"
</code>```

try it...

To the best of my knowledge, it is impossible to search Twitter (web app or API) using wildcards in a sigle word or hashtag.

Body:
Wildcards in Twitter search work only on phrases, inside quotes, with spaces on both sides. For example:

"this is the * time today that"

try it...

To the best of my knowledge, it is impossible to search Twitter (web app or API) using wildcards in a sigle word or hashtag.


问:
Add a callback to Firebase Login Function
I am fairly new to React and the use of Firebase. Right now I have a Firebase.js file where I have stored and exported all of my functions and consts. This is what it looks like:

```<code>export const auth = firebase.auth();

export function performLogin(email, password) {
  auth.signInWithEmailAndPassword(email, password).then(function(data) {
    //Works
  }).catch(function(error) {
    //Does not work
  });
}
</code>```

So, I have this login.js that I am calling performLogin from, and I was wondering what would be the best way of doing this? How can I create a callback, or at least read any kind of return message? This is how I call performLogin:

```<code>clickLogin(e){

    e.preventDefault();
    performLogin(this.state.email, this.state.password);
}
</code>```

And this works, as the console output tells me if the login was successful or not. However, I want to be able to use this function in order to retrieve the login status, and then determine wether or not I should prompt an error message or push the user to the admin dashboard. How would I do this?

Is it possible to call performLogin like this?

```<code>performLogin(this.state.email,this.state.password,(callback)){
 if (callback == true) { //Success } else { //Error }
}
</code>```

答:
Take a look at the function onAuthStateChanged from "firebase/auth" package.

Here is a link to the docs:
https://firebase.google.com/docs/auth/web/manage-users

Body:
I am fairly new to React and the use of Firebase. Right now I have a Firebase.js file where I have stored and exported all of my functions and consts. This is what it looks like:

export const auth = firebase.auth();

export function performLogin(email, password) {
  auth.signInWithEmailAndPassword(email, password).then(function(data) {
    //Works
  }).catch(function(error) {
    //Does not work
  });
}

So, I have this login.js that I am calling performLogin from, and I was wondering what would be the best way of doing this? How can I create a callback, or at least read any kind of return message? This is how I call performLogin:

clickLogin(e){

    e.preventDefault();
    performLogin(this.state.email, this.state.password);
}

And this works, as the console output tells me if the login was successful or not. However, I want to be able to use this function in order to retrieve the login status, and then determine wether or not I should prompt an error message or push the user to the admin dashboard. How would I do this?

Is it possible to call performLogin like this?

performLogin(this.state.email,this.state.password,(callback)){
 if (callback == true) { //Success } else { //Error }
}


问:
Need help running an existing django project on a new machine
Im just starting to do some work with an already existing python django project. I just installed python in my machine and Im trying to figure out how to install django and as I see I am supposed to use pip for this.

However, in all tutorials people are firstly creating a virtual environment for it. Now my question is since the project already exists do I need to create a virtual environment from scratch? I can see that there is already a env folder which includes bin and lib folders.

Can I somehow use this environment? And if so are there some specific commands for that?

I am on windows by the way.

答:
A virtual env is somehow to isolate packages from your system python package. I recommend you learn about them https://docs.python.org/3/tutorial/venv.html

But maybe your current project uses another package manager, for instance pipenv or poetry. If so, you will need to find references on their doc (mostly, pipenv install or poetry install). With pip, people usually add dependencies on a file like requirements.txt, which you use with pip install -r requirements.txt

Usually, you don't add python environement on source control, so it might be that this env folder is for environement variables ?

Whatever, all you need is those packages installed (with pip, pipenv, or poetry), then you should be able to run the django server through either your IDE, either 'python manage.py runserver'.

If you see any missing package (like missing module XXX) simply install them with your package manager.


问:
Angular 12 FormData API Issue
Having some issues trying to pass FormData from an Angular 12 app to a .Net Core API. Every attempt to send the data gets denied in preflight and never actually calls the backend endpoint (confirmed with Console.WriteLine there).

Followed the same patterns in many videos and websites and even created a side projected where it was able to work but for some reason in the main app it never sends. Only difference is that our main app uses PrimeNG as a framework so that is the main driver of collecting the files from the users. I've read their documentation but still not having success with it. Hopefully someone out there can help.

Attachment-Form Component

```<code>  File Upload <span class="example-text">(Max File Size: 10MB)</span>
  <p-fileUpload
    #form
    name="fileUpload[]"
    multiple="multiple"
    accept="{{ acceptedFiles }}"
    maxFileSize="10000000"
    customUpload="true"
    (uploadHandler)="uploadFiles($event)"
  >
    <ng-template pTemplate="content">
      <div
        *ngIf="form.files.length === 0 && uploadedFiles.length === 0"
        class="drag-drop"
      >
        <i class="pi pi-clone me-2"></i>DRAG & DROP FILES OR CLICK CHOOSE | THEN
        PRESS UPLOAD
      </div>

      <div *ngIf="uploadedFiles.length !== 0">
        <div class="p-fileupload-row" *ngFor="let file of uploadedFiles; let i">
          <div class="p-fileupload-filename">
            {{ file.name }} - {{ file.size }} bytes
          </div>
          <div>
            <button
              type="button"
              icon="pi pi-trash"
              pbutton
              (click)="showFile(file)"
              class="p-element p-button p-component p-button-icon-only p-button-danger"
            >
              <span class="p-button-icon pi pi-trash" aria-hidden="true"></span
              ><span aria-hidden="true" class="p-button-label"> </span>
            </button>
          </div>
        </div>
      </div>
    </ng-template>
  </p-fileUpload>
</div>
<div>
  File Upload <span class="example-text">(Max File Size: 10MB)</span>
  <p-fileUpload
    #form
    name="fileUpload[]"
    multiple="multiple"
    accept="{{ acceptedFiles }}"
    maxFileSize="10000000"
    customUpload="true"
    (uploadHandler)="uploadFiles($event)"
  >
    <ng-template pTemplate="content">
      <div
        *ngIf="form.files.length === 0 && uploadedFiles.length === 0"
        class="drag-drop"
      >
        <i class="pi pi-clone me-2"></i>DRAG & DROP FILES OR CLICK CHOOSE | THEN
        PRESS UPLOAD
      </div>

      <div *ngIf="uploadedFiles.length !== 0">
        <div class="p-fileupload-row" *ngFor="let file of uploadedFiles; let i">
          <div class="p-fileupload-filename">
            {{ file.name }} - {{ file.size }} bytes
          </div>
          <div>
            <button
              type="button"
              icon="pi pi-trash"
              pbutton
              (click)="showFile(file)"
              class="p-element p-button p-component p-button-icon-only p-button-danger"
            >
              <span class="p-button-icon pi pi-trash" aria-hidden="true"></span
              ><span aria-hidden="true" class="p-button-label"> </span>
            </button>
          </div>
        </div>
      </div>
    </ng-template>
  </p-fileUpload>
</div>
</code>```

Form Component (for custom upload event)

```<code>uploadFiles(event) {
    let files: any = <File>event.files;
    // console.log(files);

    const fileData = new FormData();
    for (let i = 0; i < files.length; i++) {
      fileData.append('file', files[i], files[i].name);
      // Console Log for my sake
      fileData.forEach((item) => console.log('fileData', item));
    }
 this.attachmentsService.uploadFiles(fileData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }
</code>```

Attachment Service

```<code>  uploadFiles(upload: any) {
    //Confirmation they are still there
    upload.forEach((item) => console.log('in api call', item));

    return this.http.post(
      'apiendpoint',
      upload
    );
  }

//I've used these headers and additional content-type headers as well and nothing worked
  headers = new HttpHeaders()
    .set('content-type', 'application/json')
    .set('Access-Control-Allow-Origin', '*')
    .set('Access-Control-Allow-Methods', '*');

</code>```

Failed Call Image

Any ideas are apricated.
Thanks,

2/7 Update for API Info

Startup.cs

```<code>        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "AttachmentService", Version = "v1" });
            });

            services.AddCors(c => {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });

            services.AddDbContext<AttachmentContext>(options =>
                options.UseNpgsql(Configuration["PGConnection"]));

            services.AddScoped<IAttachmentData, AttachmentData>();
            services.AddControllers();
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AttachmentService v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("AllowOrigin");

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

</code>```

Controller

```<code>     // [HttpOptions] <- Currently commented just as trial but doesn't work while on
        [HttpPost, Route("files")]
        public ActionResult<string> PostFiles(IFormCollection formData)
        {
            Console.WriteLine("post fired");
            // rest of logic
        }
</code>```

答:
Ultimately I figured out that it was denying the request at the http:5000 port but would accept it at the https:5001 port. It was taking my requests and trying to redirect them to the https port which was causing the deny.

Maybe consider just using https:5001 for post requests?

Title: Angular 12 FormData API Issue

Body:
Having some issues trying to pass FormData from an Angular 12 app to a .Net Core API. Every attempt to send the data gets denied in preflight and never actually calls the backend endpoint (confirmed with Console.WriteLine there).

Followed the same patterns in many videos and websites and even created a side projected where it was able to work but for some reason in the main app it never sends. Only difference is that our main app uses PrimeNG as a framework so that is the main driver of collecting the files from the users. I've read their documentation but still not having success with it. Hopefully someone out there can help.

Attachment-Form Component

  File Upload (Max File Size: 10MB)

    <ng-template pTemplate="content">

        DRAG & DROP FILES OR CLICK CHOOSE | THEN
        PRESS UPLOAD

            {{ file.name }} - {{ file.size }} bytes

            <button
              type="button"
              icon="pi pi-trash"
              pbutton
              (click)="showFile(file)"
              class="p-element p-button p-component p-button-icon-only p-button-danger"
            >

            </button>

    </ng-template>

  File Upload (Max File Size: 10MB)

    <ng-template pTemplate="content">

        DRAG & DROP FILES OR CLICK CHOOSE | THEN
        PRESS UPLOAD

            {{ file.name }} - {{ file.size }} bytes

            <button
              type="button"
              icon="pi pi-trash"
              pbutton
              (click)="showFile(file)"
              class="p-element p-button p-component p-button-icon-only p-button-danger"
            >

            </button>

    </ng-template>

Form Component (for custom upload event)

uploadFiles(event) {
    let files: any = <File>event.files;
    // console.log(files);

    const fileData = new FormData();
    for (let i = 0; i < files.length; i++) {
      fileData.append('file', files[i], files[i].name);
      // Console Log for my sake
      fileData.forEach((item) => console.log('fileData', item));
    }
 this.attachmentsService.uploadFiles(fileData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }

Attachment Service

  uploadFiles(upload: any) {
    //Confirmation they are still there
    upload.forEach((item) => console.log('in api call', item));

    return this.http.post(
      'apiendpoint',
      upload
    );
  }

//I've used these headers and additional content-type headers as well and nothing worked
  headers = new HttpHeaders()
    .set('content-type', 'application/json')
    .set('Access-Control-Allow-Origin', '*')
    .set('Access-Control-Allow-Methods', '*');

Failed Call Image

Any ideas are apricated.
Thanks,

2/7 Update for API Info

Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "AttachmentService", Version = "v1" });
            });

            services.AddCors(c => {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });

            services.AddDbContext<AttachmentContext>(options =>
                options.UseNpgsql(Configuration["PGConnection"]));

            services.AddScoped<IAttachmentData, AttachmentData>();
            services.AddControllers();
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "AttachmentService v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("AllowOrigin");

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

Controller

     // [HttpOptions] <- Currently commented just as trial but doesn't work while on
        [HttpPost, Route("files")]
        public ActionResult<string> PostFiles(IFormCollection formData)
        {
            Console.WriteLine("post fired");
            // rest of logic
        }


问:
Randomly changing for loop values
I've been working on a deep q learning snake game in my free time, with plans to add genetic algorithm components to it. To that end, I was setting up loops that would allow me to create a given population of snakes that would each run for some number of episodes for a total of some number of generations.

It should be simple. Just some nested for loops. Only, I've been getting some pretty wild results from my for loops.

This is the code in question:

```<code>def run(population_size=1, max_episodes=10, max_generations=50):
    total_score = 0

    agents = [Agent() for i in range(population_size)]
    game = SnakeGameAI()

    for cur_gen in range(max_generations):
        game.generation = cur_gen
        for agent_num, agent in enumerate(agents):
            # Set colors
            game.color1 = agent.color1
            game.color2 = agent.color2

            # Set agent number
            game.agent_num = agent_num

            for cur_episode in range(1, max_episodes+1):
                # Get old state
                state_old = agent.get_state(game)

                # Get move
                final_move = agent.get_action(state_old)

                # Perform move and get new state
                reward, done, score = game.play_step(final_move)
                state_new = agent.get_state(game)

                # Train short memory
                agent.train_short_memory(state_old, final_move, reward, state_new, done)

                # Remember
                agent.remember(state_old, final_move, reward, state_new, done)

                # Snake died
                if done:
                    # Train long memory, plot result
                    game.reset()
                    agent.episode = cur_episode
                    game.agent_episode = cur_episode
                    agent.train_long_memory()

                    if score > game.top_score:
                        game.top_score = score
                        agent.model.save()

                    total_score += score
                    game.mean_score = np.round((total_score / cur_episode), 3)

                    print(f"Agent{game.agent_num}")
                    print(f"Episode: {cur_episode}")
                    print(f"Generation: {cur_gen}")
                    print(f"Score: {score}")
                    print(f"Top Score: {game.top_score}")
                    print(f"Mean: {game.mean_score}\n")
</code>```

And this is the output it gives:

```<code>Agent0
Episode: 3
Generation: 7
Score: 0
Top Score: 0
Mean: 0.0

Agent0
Episode: 3
Generation: 14
Score: 0
Top Score: 0
Mean: 0.0

Agent0
Episode: 7
Generation: 20
Score: 1
Top Score: 1
Mean: 0.143

Agent0
Episode: 10
Generation: 26
Score: 0
Top Score: 1
Mean: 0.1

Agent0
Episode: 6
Generation: 28
Score: 1
Top Score: 1
Mean: 0.333

Agent0
Episode: 5
Generation: 37
Score: 0
Top Score: 1
Mean: 0.4

Agent0
Episode: 3
Generation: 43
Score: 0
Top Score: 1
Mean: 0.667

Agent0
Episode: 1
Generation: 45
Score: 1
Top Score: 1
Mean: 3.0

Agent0
Episode: 2
Generation: 49
Score: 0
Top Score: 1
Mean: 1.5
</code>```

The generation number steadily ticks up every second until it hits 49 and ends the loop, while the episode number randomly changes every time the snake dies. It's bizarre. I've never seen anything like this and have no idea what in my code could possible cause it.

答:
Answer:

For everyone who doesn't want to go through the comments where
Eli Harold helped me work this out, the problem was that I had my code treating each episode like a frame of the game. So instead of an episode being the full lifespan of a snake (an entire game), every time the snake took an action was an episode.

Here's what my code looks like now. I added a run loop, which fixed the issue.

```<code>def run(population_size=1, max_episodes=10, max_generations=50):
    total_score = 0

    agents = [Agent() for i in range(population_size)]
    game = SnakeGameAI()

    for cur_gen in range(max_generations):
        game.generation = cur_gen
        for agent_num, agent in enumerate(agents):
            # Set colors
            game.color1 = agent.color1
            game.color2 = agent.color2

            # Set agent number
            game.agent_num = agent_num

            for cur_episode in range(1, max_episodes+1):
                run = True
                while run:
                    # Get old state
                    state_old = agent.get_state(game)

                    # Get move
                    final_move = agent.get_action(state_old)

                    # Perform move and get new state
                    reward, done, score = game.play_step(final_move)
                    state_new = agent.get_state(game)

                    # Train short memory
                    agent.train_short_memory(state_old, final_move, reward, state_new, done)

                    # Remember
                    agent.remember(state_old, final_move, reward, state_new, done)

                    # Snake died
                    if done:
                        run = False
                        # Train long memory, plot result
                        game.reset()
                        agent.episode = cur_episode
                        game.agent_episode = cur_episode
                        agent.train_long_memory()

                        if score > game.top_score:
                            game.top_score = score
                            agent.model.save()

                        total_score += score
                        game.mean_score = np.round((total_score / cur_episode), 3)

                        print(f"Agent{game.agent_num}")
                        print(f"Episode: {cur_episode}")
                        print(f"Generation: {cur_gen}")
                        print(f"Score: {score}")
                        print(f"Top Score: {game.top_score}")
                        print(f"Mean: {game.mean_score}\n")
</code>```

Title: Randomly changing for loop values

Body:
I've been working on a deep q learning snake game in my free time, with plans to add genetic algorithm components to it. To that end, I was setting up loops that would allow me to create a given population of snakes that would each run for some number of episodes for a total of some number of generations.

It should be simple. Just some nested for loops. Only, I've been getting some pretty wild results from my for loops.

This is the code in question:

def run(population_size=1, max_episodes=10, max_generations=50):
    total_score = 0

    agents = [Agent() for i in range(population_size)]
    game = SnakeGameAI()

    for cur_gen in range(max_generations):
        game.generation = cur_gen
        for agent_num, agent in enumerate(agents):
            # Set colors
            game.color1 = agent.color1
            game.color2 = agent.color2

            # Set agent number
            game.agent_num = agent_num

            for cur_episode in range(1, max_episodes+1):
                # Get old state
                state_old = agent.get_state(game)

                # Get move
                final_move = agent.get_action(state_old)

                # Perform move and get new state
                reward, done, score = game.play_step(final_move)
                state_new = agent.get_state(game)

                # Train short memory
                agent.train_short_memory(state_old, final_move, reward, state_new, done)

                # Remember
                agent.remember(state_old, final_move, reward, state_new, done)

                # Snake died
                if done:
                    # Train long memory, plot result
                    game.reset()
                    agent.episode = cur_episode
                    game.agent_episode = cur_episode
                    agent.train_long_memory()

                    if score > game.top_score:
                        game.top_score = score
                        agent.model.save()

                    total_score += score
                    game.mean_score = np.round((total_score / cur_episode), 3)

                    print(f"Agent{game.agent_num}")
                    print(f"Episode: {cur_episode}")
                    print(f"Generation: {cur_gen}")
                    print(f"Score: {score}")
                    print(f"Top Score: {game.top_score}")
                    print(f"Mean: {game.mean_score}\n")

And this is the output it gives:

Agent0
Episode: 3
Generation: 7
Score: 0
Top Score: 0
Mean: 0.0

Agent0
Episode: 3
Generation: 14
Score: 0
Top Score: 0
Mean: 0.0

Agent0
Episode: 7
Generation: 20
Score: 1
Top Score: 1
Mean: 0.143

Agent0
Episode: 10
Generation: 26
Score: 0
Top Score: 1
Mean: 0.1

Agent0
Episode: 6
Generation: 28
Score: 1
Top Score: 1
Mean: 0.333

Agent0
Episode: 5
Generation: 37
Score: 0
Top Score: 1
Mean: 0.4

Agent0
Episode: 3
Generation: 43
Score: 0
Top Score: 1
Mean: 0.667

Agent0
Episode: 1
Generation: 45
Score: 1
Top Score: 1
Mean: 3.0

Agent0
Episode: 2
Generation: 49
Score: 0
Top Score: 1
Mean: 1.5

The generation number steadily ticks up every second until it hits 49 and ends the loop, while the episode number randomly changes every time the snake dies. It's bizarre. I've never seen anything like this and have no idea what in my code could possible cause it.

Body:
Answer:

For everyone who doesn't want to go through the comments where
Eli Harold helped me work this out, the problem was that I had my code treating each episode like a frame of the game. So instead of an episode being the full lifespan of a snake (an entire game), every time the snake took an action was an episode.

Here's what my code looks like now. I added a run loop, which fixed the issue.

def run(population_size=1, max_episodes=10, max_generations=50):
    total_score = 0

    agents = [Agent() for i in range(population_size)]
    game = SnakeGameAI()

    for cur_gen in range(max_generations):
        game.generation = cur_gen
        for agent_num, agent in enumerate(agents):
            # Set colors
            game.color1 = agent.color1
            game.color2 = agent.color2

            # Set agent number
            game.agent_num = agent_num

            for cur_episode in range(1, max_episodes+1):
                run = True
                while run:
                    # Get old state
                    state_old = agent.get_state(game)

                    # Get move
                    final_move = agent.get_action(state_old)

                    # Perform move and get new state
                    reward, done, score = game.play_step(final_move)
                    state_new = agent.get_state(game)

                    # Train short memory
                    agent.train_short_memory(state_old, final_move, reward, state_new, done)

                    # Remember
                    agent.remember(state_old, final_move, reward, state_new, done)

                    # Snake died
                    if done:
                        run = False
                        # Train long memory, plot result
                        game.reset()
                        agent.episode = cur_episode
                        game.agent_episode = cur_episode
                        agent.train_long_memory()

                        if score > game.top_score:
                            game.top_score = score
                            agent.model.save()

                        total_score += score
                        game.mean_score = np.round((total_score / cur_episode), 3)

                        print(f"Agent{game.agent_num}")
                        print(f"Episode: {cur_episode}")
                        print(f"Generation: {cur_gen}")
                        print(f"Score: {score}")
                        print(f"Top Score: {game.top_score}")
                        print(f"Mean: {game.mean_score}\n")


问:
Protoc on mac os --goout is not recognized as an flag
i'm running osx

```<code>$ uname -rsv
Darwin 21.2.0 Darwin Kernel Version 21.2.0: Sun Nov 28 20:28:54 PST 2021; root:xnu-8019.61.5~1/RELEASE_X86_64
</code>```

installed with brew and from binaries both didn't work

```<code>$ brew install protobuf
</code>```
```<code>$ protoc --version
libprotoc 3.19.4
</code>```

i'm getting an error when i'm trying to generate code using protos and grpc it says --go-out unknown flag

```<code>$ protoc -I protos/ protos/curr.proto --go-out=plugins=grpc:protos/curr
Unknown flag: --go-out
make: *** [protos] Error 1
</code>```

After installing  from pre-compiled binaries ( didn't work )

```<code>$ PB_REL="https://github.com/protocolbuffers/protobuf/releases"
$ curl -LO $PB_REL/download/v3.15.8/protoc-3.15.8-linux-x86_64.zip
$ unzip protoc-3.15.8-linux-x86_64.zip -d $HOME/.local
$ export PATH="$PATH:$HOME/.local/bin"
</code>```

-bash: /$HOME/.local/bin/protoc: cannot execute binary file

Any idea how to solve this ?

答:
even after installing protoc-gen-go and protoc-gen-grpc plugins kept giving an error

```<code>protoc --go_out=plugins=grpc:./protos  --go_opt=paths=source_relative protos/currency.proto
--go_out: protoc-gen-go: plugins are not supported; use 'protoc --go-grpc_out=...' to generate gRPC

</code>```

somehow this's in mac doesn't work due to no support for plugins

to solve you need to add

option go_package = "."; to your .proto file

then running should solve it .

```<code>protoc --go_out=.  --go_opt=paths=source_relative  --go-grpc_out=. --go-grpc_opt=paths=source_relative  ./protos/myproto.proto

</code>```

Body:
i'm running osx

$ uname -rsv
Darwin 21.2.0 Darwin Kernel Version 21.2.0: Sun Nov 28 20:28:54 PST 2021; root:xnu-8019.61.5~1/RELEASE_X86_64

installed with brew and from binaries both didn't work

$ brew install protobuf

$ protoc --version
libprotoc 3.19.4

i'm getting an error when i'm trying to generate code using protos and grpc it says --go-out unknown flag

$ protoc -I protos/ protos/curr.proto --go-out=plugins=grpc:protos/curr
Unknown flag: --go-out
make: *** [protos] Error 1

After installing  from pre-compiled binaries ( didn't work )

$ PB_REL="https://github.com/protocolbuffers/protobuf/releases"
$ curl -LO $PB_REL/download/v3.15.8/protoc-3.15.8-linux-x86_64.zip
$ unzip protoc-3.15.8-linux-x86_64.zip -d $HOME/.local
$ export PATH="$PATH:$HOME/.local/bin"

-bash: /$HOME/.local/bin/protoc: cannot execute binary file

Any idea how to solve this ?

Body:
even after installing protoc-gen-go and protoc-gen-grpc plugins kept giving an error

protoc --go_out=plugins=grpc:./protos  --go_opt=paths=source_relative protos/currency.proto
--go_out: protoc-gen-go: plugins are not supported; use 'protoc --go-grpc_out=...' to generate gRPC

somehow this's in mac doesn't work due to no support for plugins

to solve you need to add

option go_package = "."; to your .proto file

then running should solve it .

protoc --go_out=.  --go_opt=paths=source_relative  --go-grpc_out=. --go-grpc_opt=paths=source_relative  ./protos/myproto.proto


问:
Item Counter with oval/elipse shape in Flutter
What I'm trying to do is make a counter in Flutter which will be in this shape:

I'm fairly new regarding flutter and dart so I have tried to put this element inside of a Card but yeah I faced some issues due to overflow and it would be great if someone could give me a hint or point me to the right direction.

Here is my code for counter:

```<code>Card(child:Row(
        children: <Widget>[
           IconButton(icon:Icon(Icons.remove),onPressed: ()=>setState(()=>_itemCount--)),
           Text(_itemCount.toString()),
             IconButton(icon:Icon(Icons.add),onPressed: ()=>setState(()=>_itemCount++))
        ],
      ),);
</code>```

Any help would be great, thanks in advance :)

答:
You need to create a variable an assign it to the Text widget, not the function.
Increase

```<code>int theNumberThatIncreaseOrDecrease = 0;
</code>```

The function that increments the number:

```<code>_itemCountIncrease() {
    setState(() {
        theNumberThatIncreaseOrDecrease += 1;
    });
}
</code>```

The function that decreases the number:

```<code>_itemCountDecrease() {
    setState(() {
        theNumberThatIncreaseOrDecrease -= 1;
    });
}
</code>```

Your card:

```<code>Card(
    child: Row(
        children: <Widget>[
            IconButton(
                icon: Icon(Icons.remove),
                onPressed: () => _itemCountIncrease(),
            ),
            Text(theNumberThatIncreaseOrDecrease.toString()),
            IconButton(
                icon: Icon(Icons.add),
                onPressed: () => _itemCountDecreese(),
            ),
        ],
    ),
)
</code>```

Body:
What I'm trying to do is make a counter in Flutter which will be in this shape:

I'm fairly new regarding flutter and dart so I have tried to put this element inside of a Card but yeah I faced some issues due to overflow and it would be great if someone could give me a hint or point me to the right direction.

Here is my code for counter:

Card(child:Row(
        children: <Widget>[
           IconButton(icon:Icon(Icons.remove),onPressed: ()=>setState(()=>_itemCount--)),
           Text(_itemCount.toString()),
             IconButton(icon:Icon(Icons.add),onPressed: ()=>setState(()=>_itemCount++))
        ],
      ),);

Any help would be great, thanks in advance :)

Body:
You need to create a variable an assign it to the Text widget, not the function.
Increase

int theNumberThatIncreaseOrDecrease = 0;

The function that increments the number:

_itemCountIncrease() {
    setState(() {
        theNumberThatIncreaseOrDecrease += 1;
    });
}

The function that decreases the number:

_itemCountDecrease() {
    setState(() {
        theNumberThatIncreaseOrDecrease -= 1;
    });
}

Your card:

Card(
    child: Row(
        children: <Widget>[
            IconButton(
                icon: Icon(Icons.remove),
                onPressed: () => _itemCountIncrease(),
            ),
            Text(theNumberThatIncreaseOrDecrease.toString()),
            IconButton(
                icon: Icon(Icons.add),
                onPressed: () => _itemCountDecreese(),
            ),
        ],
    ),
)


问:
How to create a Kotlin Decimal Formatter
I would like to create a decimal formatter that would display up to 2 decimal digits, with a given separator.

For example with separator ","

```<code>input -> output
3.0   -> "3"
3.1   -> "3,1"
3.14  -> "3,14"
3.141 -> "3,14"
3.149 -> "3,15"
</code>```

I would like to do this in Kotlin, I guess I must use DecimalFormat but don't understand how to do so. Could you please help me?

答:
The code below was tested against all your examples and seemed to work well:

```<code>val locale = Locale("en", "UK")
val symbols = DecimalFormatSymbols(locale)
symbols.decimalSeparator = ','
val pattern = "#.##"
val decimalFormat = DecimalFormat(pattern, symbols)
val format = decimalFormat.format(3.14)
println(format)  //3,14
</code>```

To set a specific separator in your DecimalFormat, you can use setDecimalSeparator.

Pay attention to the pattern as # means:

A digit, leading zeroes are omitted

You can obviously change the locale to your fitting.

More information here.

Body:
I would like to create a decimal formatter that would display up to 2 decimal digits, with a given separator.

For example with separator ","

input -> output
3.0   -> "3"
3.1   -> "3,1"
3.14  -> "3,14"
3.141 -> "3,14"
3.149 -> "3,15"

I would like to do this in Kotlin, I guess I must use DecimalFormat but don't understand how to do so. Could you please help me?

Body:
The code below was tested against all your examples and seemed to work well:

val locale = Locale("en", "UK")
val symbols = DecimalFormatSymbols(locale)
symbols.decimalSeparator = ','
val pattern = "#.##"
val decimalFormat = DecimalFormat(pattern, symbols)
val format = decimalFormat.format(3.14)
println(format)  //3,14

To set a specific separator in your DecimalFormat, you can use setDecimalSeparator.

Pay attention to the pattern as # means:

A digit, leading zeroes are omitted

You can obviously change the locale to your fitting.

More information here.


问:
Stuck with React Fragments
I have been stuck with this React Fragment problem for a week. For some reason, my code is breaking in the return block. This causes my app to not work correctly. I followed the tutorial for the CRUD application, however, the teacher's app and fragments worked fine. I am the only one struggling. I cannot figure it out. Currently I was thinking of putting the return blocks in separate components and then importing them to avoid the error.

This is a CRUD application that uses Mapbox and MongoDB

Problem occurs on {newPlace} and closing ReactMapGL, Although I attempted to fix it still does not work.

```<code>import { useState, useEffect } from "react";
import ReactMapGl, { Marker, Popup } from "react-map-gl";
import { Room, Star } from "@material-ui/icons";
import axios from "axios";
import { format } from "timeago.js";
import "./app.css";
import Register from "./components/Register";
import Login from "./components/Login"
function App() {
  const [currentUser, setCurrentUser] = useState(null)
  const [pins, setPins] = useState([]);
  const [currentPlaceId, setCurrentPlaceId] = useState(null);
  const [title, setTitle] = useState(null)
  const [desc, setDesc] = useState(null)
  const [rating, setRating] = useState(0)
  const [newPlace, setNewPlace] = useState(null);
  const [viewport, setViewport] = useState({
    width: "100vw",
    height: "100vh",
    latitude: 40.71506434201678,
    longitude: -73.99684811789366,
    zoom: 10,
  });

  useEffect(() => {
    const getPins = async () => {
      try {
        const response = await axios.get("/pins");
        setPins(response.data);
      } catch (err) {
        console.log(err);
      }
    };
    getPins();
  }, []);

  const handleMarkerClick = (id, lat, long) => {
    setCurrentPlaceId(id);
    setViewport({ ...viewport, lattitude: lat, longitude: long });
  };

  //double Click to add new place
  const handleAddClick = (e) => {
    const [long, lat] = e.lnglat;
    setNewPlace({
      lat,
      long,
    });
  };

const handleSubmit = (e) =>{
  e.preventDefault()
  const newPin = {
    username: currentUser,
    title,
    desc,
    rating,
    lat:newPlace.lat,
    long:newPlace.long
  }
  try {
    const res = await axios.post("/pins", newPin);
    setPins([...pins, res.data]);
    setNewPlace(null);
  } catch (err) {
    console.log(err);
  }
}

  return (
    <div className="App">
      <ReactMapGl
        {...viewport}
        mapboxApiAccessToken={process.env.REACT_APP_MAPBOX}
        onViewportChange={(nextViewport) => setViewport(nextViewport)}
        mapStyle="mapbox://styles/shansiddiqui94/ckymlk1in22xu14pewxn6niqm"
        onDoubleClick={handleAddClick}
        transitionDuration="200"
      >
        {pins.map((p) => (
          <>
            <Marker
              latitude={40.7607183218919}
              longitude={-73.8311948975521}
              offsetLeft={-20}
              offsetTop={-10}
            >
              <Room
                style={{
                  fontSize: viewport.zoom * 7,
                  color: p.username === currentUser ? "tomato" : "slateblue",
                  cursor: "pointer",
                }}
                onClick={() => handleMarkerClick(p._id, p.lat, p.long)}
              ></Room>

            </Marker>
            {p._id === currentPlaceId && ( // if pin id = current id open popup
              <Popup
                latitude={p.lat}
                longitude={p.long}
                closeButton={true}
                closeOnClick={false}
                anchor="left"
                onClose={() => setCurrentPlaceId(null)}
              >
                <div className="card">
                  <label>Place</label>
                  <h4 className="place">{p.title}</h4>
                  <label>Review</label>
                  <p className="desc">{p.desc}</p>
                  <label>Rating</label>
                  <div className="stars">
                  {Array(p.rating).fill(<Star className="star"/>)}
                  </div>
                  <label>Info </label>
                  <span className="username">
                    Created by <b>{p.username}</b>
                  </span>
                  <span className="date">{format(p.createdAt)}</span>
                </div>
              </Popup>
            )}

        ))}
        </>
         {newPlace && (

          <Popup
            latitude={newPlace.lat}
            longitude={newPlace.long}
            closeButton={true}
            closeOnClick={false}
            anchor="left"
            onClose={() => setCurrentPlaceId(null)}
          >
            <div>
              <form onSubmit={handleSubmit}>
                <label>Title</label>
                <input placeholder="enter title" onChange={(e)=> setTitle(e.target.value)} />
                <label>Review</label>
                <textarea placeholder="Write a review" onChange={(e)=> setDesc(e.target.value)}/>
                <label>Rating</label>
                <select onChange={(e)=> setRating(e.target.value)}>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                </select>
                <button className="submitBtn" type="submit">
                  Add Pin
                </button>
              </form>
            </div>
          </Popup>
        )}
        {currentUser ? (<button className="button logout">Log Out</button>): (
        <div>
        <button className="button login">Login</button>
        <button className="button register">Register</button>
        </div>
        )}
        <Register />
      </ReactMapGl>
    </div>
  );
}

export default App;
</code>```

答:
You should put </> before ))}

```<code>                  <span className="date">{format(p.createdAt)}</span>
                </div>
              </Popup>
            )}
          </>
        ))}

         {newPlace && (

          <Popup
</code>```

Title: Stuck with React Fragments

Body:
I have been stuck with this React Fragment problem for a week. For some reason, my code is breaking in the return block. This causes my app to not work correctly. I followed the tutorial for the CRUD application, however, the teacher's app and fragments worked fine. I am the only one struggling. I cannot figure it out. Currently I was thinking of putting the return blocks in separate components and then importing them to avoid the error.

This is a CRUD application that uses Mapbox and MongoDB

Problem occurs on {newPlace} and closing ReactMapGL, Although I attempted to fix it still does not work.

import { useState, useEffect } from "react";
import ReactMapGl, { Marker, Popup } from "react-map-gl";
import { Room, Star } from "@material-ui/icons";
import axios from "axios";
import { format } from "timeago.js";
import "./app.css";
import Register from "./components/Register";
import Login from "./components/Login"
function App() {
  const [currentUser, setCurrentUser] = useState(null)
  const [pins, setPins] = useState([]);
  const [currentPlaceId, setCurrentPlaceId] = useState(null);
  const [title, setTitle] = useState(null)
  const [desc, setDesc] = useState(null)
  const [rating, setRating] = useState(0)
  const [newPlace, setNewPlace] = useState(null);
  const [viewport, setViewport] = useState({
    width: "100vw",
    height: "100vh",
    latitude: 40.71506434201678,
    longitude: -73.99684811789366,
    zoom: 10,
  });

  useEffect(() => {
    const getPins = async () => {
      try {
        const response = await axios.get("/pins");
        setPins(response.data);
      } catch (err) {
        console.log(err);
      }
    };
    getPins();
  }, []);

  const handleMarkerClick = (id, lat, long) => {
    setCurrentPlaceId(id);
    setViewport({ ...viewport, lattitude: lat, longitude: long });
  };

  //double Click to add new place
  const handleAddClick = (e) => {
    const [long, lat] = e.lnglat;
    setNewPlace({
      lat,
      long,
    });
  };

const handleSubmit = (e) =>{
  e.preventDefault()
  const newPin = {
    username: currentUser,
    title,
    desc,
    rating,
    lat:newPlace.lat,
    long:newPlace.long
  }
  try {
    const res = await axios.post("/pins", newPin);
    setPins([...pins, res.data]);
    setNewPlace(null);
  } catch (err) {
    console.log(err);
  }
}

  return (

      <ReactMapGl
        {...viewport}
        mapboxApiAccessToken={process.env.REACT_APP_MAPBOX}
        onViewportChange={(nextViewport) => setViewport(nextViewport)}
        mapStyle="mapbox://styles/shansiddiqui94/ckymlk1in22xu14pewxn6niqm"
        onDoubleClick={handleAddClick}
        transitionDuration="200"
      >
        {pins.map((p) => (
          <>
            <Marker
              latitude={40.7607183218919}
              longitude={-73.8311948975521}
              offsetLeft={-20}
              offsetTop={-10}
            >
              <Room
                style={{
                  fontSize: viewport.zoom * 7,
                  color: p.username === currentUser ? "tomato" : "slateblue",
                  cursor: "pointer",
                }}
                onClick={() => handleMarkerClick(p._id, p.lat, p.long)}
              ></Room>

            </Marker>
            {p._id === currentPlaceId && ( // if pin id = current id open popup
              <Popup
                latitude={p.lat}
                longitude={p.long}
                closeButton={true}
                closeOnClick={false}
                anchor="left"
                onClose={() => setCurrentPlaceId(null)}
              >

                  Place

{p.title}

                  Review

{p.desc}

                  Rating

                  {Array(p.rating).fill(<Star className="star"/>)}

                  Info

                    Created by {p.username}

                  {format(p.createdAt)}

              </Popup>
            )}

        ))}
        </>
         {newPlace && (

          <Popup
            latitude={newPlace.lat}
            longitude={newPlace.long}
            closeButton={true}
            closeOnClick={false}
            anchor="left"
            onClose={() => setCurrentPlaceId(null)}
          >

              <form onSubmit={handleSubmit}>
                Title
                <input placeholder="enter title" onChange={(e)=> setTitle(e.target.value)} />
                Review
                <textarea placeholder="Write a review" onChange={(e)=> setDesc(e.target.value)}/>
                Rating
                <select onChange={(e)=> setRating(e.target.value)}>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                </select>
                <button className="submitBtn" type="submit">
                  Add Pin
                </button>
              </form>

          </Popup>
        )}
        {currentUser ? (<button className="button logout">Log Out</button>): (

        <button className="button login">Login</button>
        <button className="button register">Register</button>

        )}
        <Register />
      </ReactMapGl>

  );
}

export default App;

Body:
You should put </> before ))}

                  <span className="date">{format(p.createdAt)}</span>
                </div>
              </Popup>
            )}
          </>
        ))}

         {newPlace && (

          <Popup