问:
Execute code when app goes off-screen on Android & iOS
I am currently trying to implement a feature on my current project that will allow me to execute some code when the app goes off screen.

This is for security reasons as I want to push a route that requests the User's PIN number before allowing them back into the app.

My HSBC banking app implements a feature like this so it must be possible.

I have completed this for Android and it works a charm, I used: https://pub.dev/packages/screen_state

This package is Android only and I would like to replicate the same functionality for iOS, or, preferably, use an alternate method that will work on both platforms.

I have researched it online and can't find anything, I must be missing something obvious.

Thanks for your help.

答:
Use WidgetBinding Observer instead of this package</p>

```<code>class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {...}

    @override
    void initState() {
      super.initState();
      WidgetsBinding.instance.addObserver(this);
    }

    @override
    void dispose() {
      WidgetsBinding.instance.removeObserver(this);
      super.dispose();
    }

    @override
    void didChangeAppLifecycleState(AppLifecycleState state) {
      if(state == AppLifecycleState.resumed){
        // Here put your code you want to execute
      }
}
</code>```

Body:
Use WidgetBinding Observer instead of this package

class _MyHomePageState extends State<MyHomePage> with WidgetsBindingObserver {...}

    @override
    void initState() {
      super.initState();
      WidgetsBinding.instance.addObserver(this);
    }

    @override
    void dispose() {
      WidgetsBinding.instance.removeObserver(this);
      super.dispose();
    }

    @override
    void didChangeAppLifecycleState(AppLifecycleState state) {
      if(state == AppLifecycleState.resumed){
        // Here put your code you want to execute
      }
}


来源: stackexchange

问:
How can I set two rgb color codes for a backgroundColor in react-native
I need to set two rgb color codes in my app. How can I give two combination of background color in react-native</p>

```<code>color:{
   backgroundColor: 'rgb 00 d0 njd', 'rgb 0090 j099'
}
</code>```

答: Yes! you can use Gradient for combine two RGB Color codes.

ContentLicense: CC BY-SA 4.0

Body:
I need to set two rgb color codes in my app. How can I give two combination of background color in react-native

color:{
   backgroundColor: 'rgb 00 d0 njd', 'rgb 0090 j099'
}


问:
Unable to find column names in a FK constraint
I have created two tables in Snowflake.

```<code>create or replace TRANSIENT TABLE TESTPARENT (
COL1 NUMBER(38,0) NOT NULL,
COL2 VARCHAR(16777216) NOT NULL,
COL3 VARCHAR(16777216) NOT NULL,
constraint UNIQ_COL3 unique (COL3)
);

create or replace TRANSIENT TABLE TESTCHILD3 (
COL_A NUMBER(38,0) NOT NULL,
COL_B NUMBER(38,0) NOT NULL,
ABCDEF VARCHAR(16777216) NOT NULL,
constraint FKEY_1 foreign key (COL_A, COL_B) references TEST_DB.PUBLIC.TESTPARENT1(COL1,COL2),
constraint FKEY_2 foreign key (ABCDEF) references TEST_DB.PUBLIC.TESTPARENT(COL3)
);
</code>```

Now I want to execute a query and see the names of columns that are involved in FKEY_2 FOREIGN KEY
in Table TESTCHILD3, but it seems like there are no DB Table/View that keeps this information. I can find out the column names for UNIQUE KEY & PRIMARY KEY but there is nothing for FOREIGN KEYS.

EDIT
I have already tried INFORMATION_SCHEMA.TABLE_CONSTRAINTS, along with INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS and all the other system tables. No luck. Only DESC TABLE is giving me some info related to CONSTRAINTS and COLUMNS but that also has FOREIGN KEY CONSTRAINTS information missing.

答:
maybe you can try to query this view: INFORMATION_SCHEMA.TABLE_CONSTRAINTS

Note: TABLE_CONSTRAINTS only displays objects for which the current role for the session has been granted access privileges.

For more see: https://docs.snowflake.net/manuals/sql-reference/info-schema/table_constraints.html

Body:
I have created two tables in Snowflake.

create or replace TRANSIENT TABLE TESTPARENT (
COL1 NUMBER(38,0) NOT NULL,
COL2 VARCHAR(16777216) NOT NULL,
COL3 VARCHAR(16777216) NOT NULL,
constraint UNIQ_COL3 unique (COL3)
);

create or replace TRANSIENT TABLE TESTCHILD3 (
COL_A NUMBER(38,0) NOT NULL,
COL_B NUMBER(38,0) NOT NULL,
ABCDEF VARCHAR(16777216) NOT NULL,
constraint FKEY_1 foreign key (COL_A, COL_B) references TEST_DB.PUBLIC.TESTPARENT1(COL1,COL2),
constraint FKEY_2 foreign key (ABCDEF) references TEST_DB.PUBLIC.TESTPARENT(COL3)
);

Now I want to execute a query and see the names of columns that are involved in FKEY_2 FOREIGN KEY
in Table TESTCHILD3, but it seems like there are no DB Table/View that keeps this information. I can find out the column names for UNIQUE KEY & PRIMARY KEY but there is nothing for FOREIGN KEYS.

EDIT
I have already tried INFORMATION_SCHEMA.TABLE_CONSTRAINTS, along with INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS and all the other system tables. No luck. Only DESC TABLE is giving me some info related to CONSTRAINTS and COLUMNS but that also has FOREIGN KEY CONSTRAINTS information missing.


问:
How to add filter to a custom query on Data Studio?
I'm building a dash using Data Studion and I need to create a custom query using CASE WHEN statments. The problem is that the conditions must be the values selected through a filter. How can I get the value selected on the filter and use it as a parameters on my query?</p>

答:
you can not , the only parameter that can be passed from  a filter is dates as per this documentation  https://support.google.com/datastudio/answer/6370296?hl=en

all you can do is vote for this feature request

https://issuetracker.google.com/issues/142183085


问:
Problem Deserialising JSON response from Wikipedia API
I am trying to use the Wikipedia search request API thus:

https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=100&gsrsearch=Simple Harmonic Motion

and then trying to deserialise thus:

```<code>WikiSearchResults R = s1.Deserialize<WikiSearchResults>(Json);
</code>```

using this class structure:

```<code>private class WikiSearchQuery{
     public WikiSearchPage[] pages { get; set; }
}

private class WikiSearchPage{
     public int pageid { get; set; }
     public string title { get; set; }
}

private class WikiSearchResults{
     public WikiSearchQuery[] query { get; set; }
}
</code>```

But I am getting this exception:

No parameterless constructor defined for type of WikiSearchQuery[]

I guess I am misinterpreting the JSON response. Can someone suggest what I am doing wrong?

答:
using (var client = new HttpClient())
      {
        var _reqMessage = new HttpRequestMessage();
        _reqMessage.Method = HttpMethod.Get;
        _reqMessage.RequestUri = new Uri("https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=100&gsrsearch=S");

        var response = client.SendAsync(_reqMessage);
        response.Wait();

        var result = response.Result;
        var resultJson = result.Content.ReadAsStringAsync().Result;

        var tes = JsonConvert.DeserializeObject<WikiSearchResults>(resultJson);
      }
```

<p>Models:</p>

```public class WikiSearchQuery
{
  [JsonProperty("pages")]
  public Dictionary<object, WikiSearchPage> Pages { get; set; }
}

public class WikiSearchPage
{
  [JsonProperty("pageid")]
  public int Pageid { get; set; }
  [JsonProperty("title")]
  public string Title { get; set; }
}

public class WikiSearchResults
{
  [JsonProperty("query")]
  public WikiSearchQuery Query { get; set; }
}
```

Body:
I am trying to use the Wikipedia search request API thus:

https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=100&gsrsearch=Simple Harmonic Motion

and then trying to deserialise thus:

WikiSearchResults R = s1.Deserialize<WikiSearchResults>(Json);

using this class structure:

private class WikiSearchQuery{
     public WikiSearchPage[] pages { get; set; }
}

private class WikiSearchPage{
     public int pageid { get; set; }
     public string title { get; set; }
}

private class WikiSearchResults{
     public WikiSearchQuery[] query { get; set; }
}

But I am getting this exception:

No parameterless constructor defined for type of WikiSearchQuery[]

I guess I am misinterpreting the JSON response. Can someone suggest what I am doing wrong?

Body:
using (var client = new HttpClient())
      {
        var _reqMessage = new HttpRequestMessage();
        _reqMessage.Method = HttpMethod.Get;
        _reqMessage.RequestUri = new Uri("https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=100&gsrsearch=S");

        var response = client.SendAsync(_reqMessage);
        response.Wait();

        var result = response.Result;
        var resultJson = result.Content.ReadAsStringAsync().Result;

        var tes = JsonConvert.DeserializeObject<WikiSearchResults>(resultJson);
      }

Models:

public class WikiSearchQuery
{
  [JsonProperty("pages")]
  public Dictionary<object, WikiSearchPage> Pages { get; set; }
}

public class WikiSearchPage
{
  [JsonProperty("pageid")]
  public int Pageid { get; set; }
  [JsonProperty("title")]
  public string Title { get; set; }
}

public class WikiSearchResults
{
  [JsonProperty("query")]
  public WikiSearchQuery Query { get; set; }
}


问:
Use SplitProcessor with space as delimiter in typoscript setup?
How do I specify a space as the delimiter using SplitProcessor?

I want to be able to loop over each word from the header field:

```<code>20 = TYPO3\CMS\Frontend\DataProcessing\SplitProcessor
20 {
    delimiter =
    fieldName = header
    as = words
}
</code>```

答:
The parameters for SplitProcessor are run though stdWrap, so you can use char to set it to a space character:

```<code>20 = TYPO3\CMS\Frontend\DataProcessing\SplitProcessor
20 {
    delimiter.char = 32
    fieldName = header
    as = words
}
</code>```

32 is the asci code for space.

Body:
How do I specify a space as the delimiter using SplitProcessor?

I want to be able to loop over each word from the header field:

20 = TYPO3\CMS\Frontend\DataProcessing\SplitProcessor
20 {
    delimiter =
    fieldName = header
    as = words
}

Body:
The parameters for SplitProcessor are run though stdWrap, so you can use char to set it to a space character:

20 = TYPO3\CMS\Frontend\DataProcessing\SplitProcessor
20 {
    delimiter.char = 32
    fieldName = header
    as = words
}

32 is the asci code for space.


问:
Java: overriding equals method doesn't do the trick when looking for a key of hashtable?
I have a hashtable looking like this:

```<code>Hashtable<Mapping, Integer> mappingCount = new Hashtable<Mapping, Integer>();
</code>```

I want to use this code:

```<code>if (mappingCount.get(currentMapping) != null)
    mappingCount.put(currentMapping, mappingCount.get(currentMapping) + 1);
else
    mappingCount.put(currentMapping, 1);
</code>```

In order to be able to get the value from the hashtable, for the class Mapping I did the following:

```<code>@Override
public boolean equals(Object obj) {
    return ((Mapping)obj).mappingXML.equals(this.mappingXML);
}
</code>```

However, this doesn't do the trick since mappingCount.get(currentMapping) always results in null. To be sure that something's not wrong, I did the following:

```<code>if (aaa.contains(currentMapping.getMappingXML()))
    System.out.println("found it!");
else
    aaa.add(currentMapping.getMappingXML());
</code>```

where aaa is List<String> aaa = new ArrayList<String>(). Of course, found it is printed many times. What am I doing wrong?

答:
You need to override hashCode as well.

From the Object#hashCode doc:

Returns a hash code value for the
  object. This method is supported for
  the benefit of hashtables such as
  those provided by java.util.Hashtable.

The general contract of hashCode is:

Whenever it is invoked on the same object more than once during an
  execution of a Java application, the
  hashCode method must consistently
  return the same integer, provided no
  information used in equals comparisons
  on the object is modified. This
  integer need not remain consistent
  from one execution of an application
  to another execution of the same
  application.

If two objects are equal according to the equals(Object) method, then
  calling the hashCode method on each of
  the two objects must produce the same
  integer result.

It is not required that if two objects are unequal according to the
  equals(java.lang.Object) method, then
  calling the hashCode method on each of
  the two objects must produce distinct
  integer results. However, the
  programmer should be aware that
  producing distinct integer results for
  unequal objects may improve the
  performance of hashtables.

As much as is reasonably practical,
  the hashCode method defined by class
  Object does return distinct integers
  for distinct objects. (This is
  typically implemented by converting
  the internal address of the object
  into an integer, but this
  implementation technique is not
  required by the JavaTM programming
  language.)

ContentLicense: CC BY-SA 3.0

Body:
I have a hashtable looking like this:

Hashtable<Mapping, Integer> mappingCount = new Hashtable<Mapping, Integer>();

I want to use this code:

if (mappingCount.get(currentMapping) != null)
    mappingCount.put(currentMapping, mappingCount.get(currentMapping) + 1);
else
    mappingCount.put(currentMapping, 1);

In order to be able to get the value from the hashtable, for the class Mapping I did the following:

@Override
public boolean equals(Object obj) {
    return ((Mapping)obj).mappingXML.equals(this.mappingXML);
}

However, this doesn't do the trick since mappingCount.get(currentMapping) always results in null. To be sure that something's not wrong, I did the following:

if (aaa.contains(currentMapping.getMappingXML()))
    System.out.println("found it!");
else
    aaa.add(currentMapping.getMappingXML());

where aaa is List<String> aaa = new ArrayList<String>(). Of course, found it is printed many times. What am I doing wrong?


答:
Use Index.intersection:

```<code>idx = idx1.intersection(idx2)
</code>```

Or, if the indexes have not been previously defined:

```<code>idx = df1.index.intersection(df2.index)
</code>```

Title: How to get the rows in Pandas dataframe with datetime index using another datetime index?

Body:
I have a Pandas dataframe with the following datetime index:

DatetimeIndex(['2020-01-02', '2020-01-03', '2020-01-06', '2020-01-07',
               '2020-01-08', '2020-01-09', '2020-01-10', '2020-01-13',
               '2020-01-14', '2020-01-15',
               ...
               '2020-01-17', '2020-01-21', '2020-01-22', '2020-01-23',
               '2020-01-24', '2020-01-27', '2020-01-28', '2020-01-29',
               '2020-01-30', '2020-01-31'],
              dtype='datetime64[ns]', name='Date', length=49098, freq=None)

I want to get the rows which intersect with the following datetime index:

DatetimeIndex(['2020-01-02', '2020-01-03', '2020-01-06', '2020-01-07',
               '2020-01-08', '2020-01-09', '2020-01-10'],
              dtype='datetime64[ns]', name='Date', freq=None)

What is the most natural (aka "Pythonic") way to do it?

Body:
Use Index.intersection:

idx = idx1.intersection(idx2)

Or, if the indexes have not been previously defined:

idx = df1.index.intersection(df2.index)


问:
Uncaught ReferenceError: __importDefault is not defined
I am new to angular. I encounter this error in my index.component.ts file.

Uncaught ReferenceError: __importDefault is not defined

Error screenshot attached

答:
I got this problem when i was upgrading from angular 6 to angular 8, this is due to  typescript,
since my TypeScript version cannot be downgraded, I have overridden this method. adding below code to index.html will resolve issue

GitHub Issue

```<code><script> var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }</script>
</code>```

Body:
I got this problem when i was upgrading from angular 6 to angular 8, this is due to  typescript,
since my TypeScript version cannot be downgraded, I have overridden this method. adding below code to index.html will resolve issue

GitHub Issue

<script> var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }</script>


问:
function prints out a multiplication table
```<code>def multiplication_table(start, stop):
    for x in range(1, 2):
        for y in range(1, 3):
            print(str(X * y), end=" ")
        print()

multiplication_table(1, 3)
</code>```

Should print the multiplication table shown below

Question

This function prints out a multiplication table (where each number is the result of multiplying the first number of its row by the number at the top of its column). Fill in the blanks so that calling multiplication_table(1, 3) will print out:

```<code>1 2 3
2 4 6
3 6 9
</code>```

Why is it not working

答:
```<code>def multiplication_table(start, stop):
    for x in range(start,stop+1):
        for y in range(start,stop+1):
            print(str(x*y), end=" ")
        print()

multiplication_table(1, 3)
</code>```

Body:
def multiplication_table(start, stop):
    for x in range(1, 2):
        for y in range(1, 3):
            print(str(X * y), end=" ")
        print()

multiplication_table(1, 3)

Should print the multiplication table shown below

Question

This function prints out a multiplication table (where each number is the result of multiplying the first number of its row by the number at the top of its column). Fill in the blanks so that calling multiplication_table(1, 3) will print out:

1 2 3
2 4 6
3 6 9

Why is it not working


问:
Should JWT be stored in localStorage or cookie?
For the purpose of securing REST API using JWT, according to some materials (like this guide and this question), the JWT can be stored in either localStorage or Cookies. Based on my understanding:

localStorage is subjected to XSS and generally it's not recommended to store any sensitive information in it.

With Cookies we can apply the flag "httpOnly" which mitigates the risk of XSS. However if we are to read the JWT from Cookies on backend, we then are subjected to CSRF.

So based on the above premise - it will be best if we store JWT in Cookies. On every request to server, the JWT will be read from Cookies and added in the Authorization header using Bearer scheme. The server can then verify the JWT in the request header (as opposed to reading it from the cookies).

Is my understanding correct? If so, does the above approach have any security concern? Or actually we can just get away with using localStorage in the first place?

答:
Do not store your token in LocalStorage or SessionStorage, because such token can be read from javascript and therefore it is vulnarable to XSS attack.

Do not store your token in Cookie. Cookie (with HttpOnly flag) is a better option - it's XSS prone, but it's vulnarable to CSRF attack

Instead, on login, you can deliver two tokens: access token and refresh token. Access token should be stored in Javascript memory and Refresh token should be stored in HttpOnly Cookie. Refresh token is used only and only for creating new access tokens - nothing more.

When user opens new tab, or on site refresh, you need to perform request to create new access token, based on refresh token which is stored in Cookie.

I also strongly recommend to read this article: https://hasura.io/blog/best-practices-of-using-jwt-with-graphql/


问:
Setting up a variable in setInterval(), react
I'm trying to setup a pause variable inside setInterval() function, after few times pressing button pause it became to act weirdly, it's not same like outer variable. What i'm doing wrong?
Run code snippet, and press pause few times

const {useState, useEffect} = React

        function App() {
          const [pause, setPause] = useState(false)
          const [innerVar, setInnerVar] = useState(false)
          const [outerVar, setOuterVar] = useState(false)
          useEffect(()=>{
            setOuterVar(pause)
          }, [pause])

          const interval = setInterval(function() {
            setInnerVar(pause)
          }, 2000)

          return (

              <button onClick={() => setPause(!pause)}>Pause</button>

Pause variable: {pause ? 'true': 'false'}

Inside setInteval: {innerVar ? 'true' : 'false'}

Outside setInterval: {outerVar ? 'true' : 'false'}

          )
        }

    ReactDOM.render(<App />, document.body)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script></code>```

答:
1) You're not clearing the interval.

2) According to your code, a new interval is set each time the component is rendered.

Set the interval in useEffect so that it is consistent with when the pause value changes and then clear the interval in the clean-up function.

const {useState, useEffect} = React

        function App() {
          const [pause, setPause] = useState(false)
          const [innerVar, setInnerVar] = useState(false)
          const [outerVar, setOuterVar] = useState(false)
          useEffect(()=>{
            setOuterVar(pause);
            const interval = setInterval(function() {
              setInnerVar(pause)
            }, 2000);
            return ()=>{clearInterval(interval);};
          }, [pause]);

          return (

              <button onClick={() => setPause(!pause)}>Pause</button>

Pause variable: {pause ? 'true': 'false'}

Inside setInteval: {innerVar ? 'true' : 'false'}

Outside setInterval: {outerVar ? 'true' : 'false'}

          )
        }

    ReactDOM.render(<App />, document.body)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script></code>```

UPDATE

From @Alexfrostwolf answer, you don't really need setInterval in this case now and use setTimeout instead. Though, will leave my answer with minimum modification from you code.

Body:
1) You're not clearing the interval.

2) According to your code, a new interval is set each time the component is rendered.

Set the interval in useEffect so that it is consistent with when the pause value changes and then clear the interval in the clean-up function.

const {useState, useEffect} = React

        function App() {
          const [pause, setPause] = useState(false)
          const [innerVar, setInnerVar] = useState(false)
          const [outerVar, setOuterVar] = useState(false)
          useEffect(()=>{
            setOuterVar(pause);
            const interval = setInterval(function() {
              setInnerVar(pause)
            }, 2000);
            return ()=>{clearInterval(interval);};
          }, [pause]);

          return (
            <div>
              <button onClick={() => setPause(!pause)}>Pause</button>
              <div>Pause variable: {pause ? 'true': 'false'}</div>
              <div>Inside setInteval: {innerVar ? 'true' : 'false'}</div>
              <div>Outside setInterval: {outerVar ? 'true' : 'false'}</div>
          </div>
          )
        }

    ReactDOM.render(<App />, document.body)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

UPDATE

From @Alexfrostwolf answer, you don't really need setInterval in this case now and use setTimeout instead. Though, will leave my answer with minimum modification from you code.


问:
How to change the language of ErrorText based on culture in aspx.cs
I'm new to the world of asp and was given the task to make sure a site can be translated with the click of a button.
So far i was able to make most of the page translate using recourse files but small things like the error messages you get when trying to login is what i'm stuck on.

The error messages for ASPX(Password is required and Username is required) is inside  so i cant "call" my resource file.
The "Username or password is incorrect" message is inside my ASPX.CS is inside a else statement and i cant figure out how to "call" the resource file.

Any help will truly be appreciated.

Thanks in advance

答:
The answer is quite simple. All you need to do is remember to convert to string

https://forums.asp.net/t/1930499.aspx?Displaying+messages+in+the+message+box+from+the+resource+files+in+c+


问:
Absolute/outer and inner namespace confusion in C#
```<code>using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}
</code>```

How could I solve this? Just moving the using statement inside my namespace doesn't help.

答:
Alias the namespace in the using statement:</p>

```<code>using ThatOuterFoo = Foo.Uber;
...
...
//Some time later...
var x = ThatOuterFoo.Bar();
</code>```

Body:
using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}

How could I solve this? Just moving the using statement inside my namespace doesn't help.

Body:
Alias the namespace in the using statement:

using ThatOuterFoo = Foo.Uber;
...
...
//Some time later...
var x = ThatOuterFoo.Bar();


问:
Trying to separate bar in histogram, and set custom labels
I have multiple CSV files containing a single line like this :

y,ymin,ymax

For example:

35.4587,36.6542,34.3546

I want to do a histogram with error bars that looks like this:

But instead I have this:

Because I don't understand how to separate the boxes, and how to give them arbitrary labels, regardless of the data I'm plotting.

Here is my code so far:

```<code>reset

set datafile separator ','

set style fill solid 1 border lt -1
set style histogram errorbars gap 2 lw 2
set style data histograms

set ylabel 'time (seconds)'

plot 'data1.csv' using 1:2:3 notitle, \
'data2.csv' using 1:2:3 notitle, \
'data3.csv' using 1:2:3 notitle, \
'data4.csv' using 1:2:3 notitle
</code>```

Best regards.

答:
To be honest, I do not really get along with the histogram styles. But I'm sure there is a way to achieve what you want. One alternative way would be to just draw it "manually" using with boxes and with yerrorbars and tune it as you like. Something like this, which can certainly be optimized, e.g. with a loop, depending on your data.

Code:

```<code>### "manual" histogram with errorbars
reset session

$Data1 <<EOD
60 58 62
EOD

$Data2 <<EOD
37 36 38
EOD

$Data3 <<EOD
46 44 48
EOD

$Data4 <<EOD
63 61 65
EOD

set boxwidth 0.4
unset key
set xrange [0.5:4.5]
set yrange [35:70]

set style fill solid 1 border lt -1
set errorbars lw 2 ls -1

plot $Data1 u (1):1:xtic("Some text")        w boxes lc 1, '' u (1):1:2:3 w yerrorbars pt -1, \
     $Data2 u (2):1:xtic("Some other text")  w boxes lc 2, '' u (2):1:2:3 w yerrorbars pt -1, \
     $Data3 u (3):1:xtic("Arbitrary text")   w boxes lc 3, '' u (3):1:2:3 w yerrorbars pt -1, \
     $Data4 u (4):1:xtic("Yet another text") w boxes lc 4, '' u (4):1:2:3 w yerrorbars pt -1
### end of code
</code>```

Result:

Body:
I have multiple CSV files containing a single line like this :

y,ymin,ymax

For example:

35.4587,36.6542,34.3546

I want to do a histogram with error bars that looks like this:

But instead I have this:

Because I don't understand how to separate the boxes, and how to give them arbitrary labels, regardless of the data I'm plotting.

Here is my code so far:

reset

set datafile separator ','

set style fill solid 1 border lt -1
set style histogram errorbars gap 2 lw 2
set style data histograms

set ylabel 'time (seconds)'

plot 'data1.csv' using 1:2:3 notitle, \
'data2.csv' using 1:2:3 notitle, \
'data3.csv' using 1:2:3 notitle, \
'data4.csv' using 1:2:3 notitle

Best regards.

Body:
To be honest, I do not really get along with the histogram styles. But I'm sure there is a way to achieve what you want. One alternative way would be to just draw it "manually" using with boxes and with yerrorbars and tune it as you like. Something like this, which can certainly be optimized, e.g. with a loop, depending on your data.

Code:

### "manual" histogram with errorbars
reset session

$Data1 <<EOD
60 58 62
EOD

$Data2 <<EOD
37 36 38
EOD

$Data3 <<EOD
46 44 48
EOD

$Data4 <<EOD
63 61 65
EOD

set boxwidth 0.4
unset key
set xrange [0.5:4.5]
set yrange [35:70]

set style fill solid 1 border lt -1
set errorbars lw 2 ls -1

plot $Data1 u (1):1:xtic("Some text")        w boxes lc 1, '' u (1):1:2:3 w yerrorbars pt -1, \
     $Data2 u (2):1:xtic("Some other text")  w boxes lc 2, '' u (2):1:2:3 w yerrorbars pt -1, \
     $Data3 u (3):1:xtic("Arbitrary text")   w boxes lc 3, '' u (3):1:2:3 w yerrorbars pt -1, \
     $Data4 u (4):1:xtic("Yet another text") w boxes lc 4, '' u (4):1:2:3 w yerrorbars pt -1
### end of code

Result:


问:
How to write google protobuf messages in java?
I am using google protobuf library to write messages in a file. However these messages do not look binary messages to me. The proto I am using is simple it has Name, Email and Cell No. The file I get is:

```<code>*
bilalÈÇbilal@gmail.com"
12345678
</code>```

If I read back I am able to read it, but this dont look binary data, what i want is writing binary to a file and then parsing it back while reading. I have gone through the API and found that we have multiple methods available for parseFrom(), like:

```<code>1) parseFrom(InputStream)
2) parseFrom(CodedInputStream)
3) parseFrom(Byte[])
</code>```

In the google protobuf tutorials they are using parseFrom(InputStream). And for binary messages i think I need parseFrom(Byte[]). But I dont know how i have to write binary messages. Help is appreciated. My end goal is to read binary messages in a spark dataframe using scalapb.

答: You are talking about writing messages, so that means you have to use the command {protoObj}.writeDelimitedTo({an outputstream}) (please pay attention to the delimited nature) and read them with {yourprotodefclass}.parseDelimitedFrom({an inputstream})

Body:
I am using google protobuf library to write messages in a file. However these messages do not look binary messages to me. The proto I am using is simple it has Name, Email and Cell No. The file I get is:

*
bilalÈÇbilal@gmail.com"
12345678

If I read back I am able to read it, but this dont look binary data, what i want is writing binary to a file and then parsing it back while reading. I have gone through the API and found that we have multiple methods available for parseFrom(), like:

1) parseFrom(InputStream)
2) parseFrom(CodedInputStream)
3) parseFrom(Byte[])

In the google protobuf tutorials they are using parseFrom(InputStream). And for binary messages i think I need parseFrom(Byte[]). But I dont know how i have to write binary messages. Help is appreciated. My end goal is to read binary messages in a spark dataframe using scalapb.


问:
How can I solve this strange error while doing 'npm install brain.js'?
My objetive is to test the brain.js script in nodejs, but I can't. I did this command:

npm install brain.js

And I got this result:

```<code>C:\Users\alumno_ciclo\Desktop\papelera>npm install brain.js
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142

> webworker-threads@0.7.17 install C:\Users\alumno_ciclo\node_modules\webworker-threads
> node-gyp rebuild

C:\Users\alumno_ciclo\node_modules\webworker-threads>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
gyp ERR! find Python
gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error
gyp ERR! find Python checking if the py launcher can be used to find Python 2
gyp ERR! find Python - "py.exe" is not in PATH or produced an error
gyp ERR! find Python checking if Python is C:\Python27\python.exe
gyp ERR! find Python - "C:\Python27\python.exe" could not be run
gyp ERR! find Python checking if Python is C:\Python37\python.exe
gyp ERR! find Python - "C:\Python37\python.exe" could not be run
gyp ERR! find Python
gyp ERR! find Python **********************************************************
gyp ERR! find Python You need to install the latest version of Python.
gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
gyp ERR! find Python you can try one of the following options:
gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
gyp ERR! find Python   (accepted by both node-gyp and npm)
gyp ERR! find Python - Set the environment variable PYTHON
gyp ERR! find Python - Set the npm configuration variable python:
gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
gyp ERR! find Python For more information consult the documentation at:
gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
gyp ERR! find Python **********************************************************
gyp ERR! find Python
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Python installation to use
gyp ERR! stack     at PythonFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:307:47)
gyp ERR! stack     at PythonFinder.runChecks (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:136:21)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:225:16)
gyp ERR! stack     at PythonFinder.execFileCallback (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:271:16)
gyp ERR! stack     at exithandler (child_process.js:310:5)
gyp ERR! stack     at ChildProcess.errorhandler (child_process.js:322:5)
gyp ERR! stack     at ChildProcess.emit (events.js:321:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
gyp ERR! stack     at onErrorNT (internal/child_process.js:467:16)
gyp ERR! stack     at processTicksAndRejections (internal/process/task_queues.js:84:21)
gyp ERR! System Windows_NT 10.0.18362
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\alumno_ciclo\node_modules\webworker-threads
gyp ERR! node -v v13.8.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok

> gl@4.4.1 install C:\Users\alumno_ciclo\node_modules\gl
> prebuild-install || node-gyp rebuild

prebuild-install WARN install No prebuilt binaries found (target=13.8.0 runtime=node arch=x64 libc= platform=win32)

C:\Users\alumno_ciclo\node_modules\gl>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
gyp ERR! find Python
gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error
gyp ERR! find Python checking if the py launcher can be used to find Python 2
gyp ERR! find Python - "py.exe" is not in PATH or produced an error
gyp ERR! find Python checking if Python is C:\Python27\python.exe
gyp ERR! find Python - "C:\Python27\python.exe" could not be run
gyp ERR! find Python checking if Python is C:\Python37\python.exe
gyp ERR! find Python - "C:\Python37\python.exe" could not be run
gyp ERR! find Python
gyp ERR! find Python **********************************************************
gyp ERR! find Python You need to install the latest version of Python.
gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
gyp ERR! find Python you can try one of the following options:
gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
gyp ERR! find Python   (accepted by both node-gyp and npm)
gyp ERR! find Python - Set the environment variable PYTHON
gyp ERR! find Python - Set the npm configuration variable python:
gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
gyp ERR! find Python For more information consult the documentation at:
gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
gyp ERR! find Python **********************************************************
gyp ERR! find Python
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Python installation to use
gyp ERR! stack     at PythonFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:307:47)
gyp ERR! stack     at PythonFinder.runChecks (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:136:21)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:225:16)
gyp ERR! stack     at PythonFinder.execFileCallback (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:271:16)
gyp ERR! stack     at exithandler (child_process.js:310:5)
gyp ERR! stack     at ChildProcess.errorhandler (child_process.js:322:5)
gyp ERR! stack     at ChildProcess.emit (events.js:321:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
gyp ERR! stack     at onErrorNT (internal/child_process.js:467:16)
gyp ERR! stack     at processTicksAndRejections (internal/process/task_queues.js:84:21)
gyp ERR! System Windows_NT 10.0.18362
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\alumno_ciclo\node_modules\gl
gyp ERR! node -v v13.8.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\alumno_ciclo\package.json'
npm WARN alumno_ciclo No description
npm WARN alumno_ciclo No repository field.
npm WARN alumno_ciclo No README data
npm WARN alumno_ciclo No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: webworker-threads@0.7.17 (node_modules\webworker-threads):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: webworker-threads@0.7.17 install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! gl@4.4.1 install: `prebuild-install || node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the gl@4.4.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\alumno_ciclo\AppData\Roaming\npm-cache\_logs\2020-02-19T18_15_18_690Z-debug.log
</code>```

I tried to reinstall nodejs, and install python, and configure some window's variables. But not, this command is impossible to run. Can anyguy help me? Thanks anyway.

答:
First run "npm install --global windows-build-tools" in Administrator mode on CMD and then after run "npm install brain.js" again.

Best,

Body:
My objetive is to test the brain.js script in nodejs, but I can't. I did this command:

npm install brain.js

And I got this result:

C:\Users\alumno_ciclo\Desktop\papelera>npm install brain.js
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142

> webworker-threads@0.7.17 install C:\Users\alumno_ciclo\node_modules\webworker-threads
> node-gyp rebuild

C:\Users\alumno_ciclo\node_modules\webworker-threads>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
gyp ERR! find Python
gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error
gyp ERR! find Python checking if the py launcher can be used to find Python 2
gyp ERR! find Python - "py.exe" is not in PATH or produced an error
gyp ERR! find Python checking if Python is C:\Python27\python.exe
gyp ERR! find Python - "C:\Python27\python.exe" could not be run
gyp ERR! find Python checking if Python is C:\Python37\python.exe
gyp ERR! find Python - "C:\Python37\python.exe" could not be run
gyp ERR! find Python
gyp ERR! find Python **********************************************************
gyp ERR! find Python You need to install the latest version of Python.
gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
gyp ERR! find Python you can try one of the following options:
gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
gyp ERR! find Python   (accepted by both node-gyp and npm)
gyp ERR! find Python - Set the environment variable PYTHON
gyp ERR! find Python - Set the npm configuration variable python:
gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
gyp ERR! find Python For more information consult the documentation at:
gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
gyp ERR! find Python **********************************************************
gyp ERR! find Python
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Python installation to use
gyp ERR! stack     at PythonFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:307:47)
gyp ERR! stack     at PythonFinder.runChecks (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:136:21)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:225:16)
gyp ERR! stack     at PythonFinder.execFileCallback (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:271:16)
gyp ERR! stack     at exithandler (child_process.js:310:5)
gyp ERR! stack     at ChildProcess.errorhandler (child_process.js:322:5)
gyp ERR! stack     at ChildProcess.emit (events.js:321:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
gyp ERR! stack     at onErrorNT (internal/child_process.js:467:16)
gyp ERR! stack     at processTicksAndRejections (internal/process/task_queues.js:84:21)
gyp ERR! System Windows_NT 10.0.18362
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\alumno_ciclo\node_modules\webworker-threads
gyp ERR! node -v v13.8.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok

> gl@4.4.1 install C:\Users\alumno_ciclo\node_modules\gl
> prebuild-install || node-gyp rebuild

prebuild-install WARN install No prebuilt binaries found (target=13.8.0 runtime=node arch=x64 libc= platform=win32)

C:\Users\alumno_ciclo\node_modules\gl>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
gyp ERR! find Python
gyp ERR! find Python Python is not set from command line or npm configuration
gyp ERR! find Python Python is not set from environment variable PYTHON
gyp ERR! find Python checking if "python" can be used
gyp ERR! find Python - "python" is not in PATH or produced an error
gyp ERR! find Python checking if "python2" can be used
gyp ERR! find Python - "python2" is not in PATH or produced an error
gyp ERR! find Python checking if "python3" can be used
gyp ERR! find Python - "python3" is not in PATH or produced an error
gyp ERR! find Python checking if the py launcher can be used to find Python 2
gyp ERR! find Python - "py.exe" is not in PATH or produced an error
gyp ERR! find Python checking if Python is C:\Python27\python.exe
gyp ERR! find Python - "C:\Python27\python.exe" could not be run
gyp ERR! find Python checking if Python is C:\Python37\python.exe
gyp ERR! find Python - "C:\Python37\python.exe" could not be run
gyp ERR! find Python
gyp ERR! find Python **********************************************************
gyp ERR! find Python You need to install the latest version of Python.
gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
gyp ERR! find Python you can try one of the following options:
gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
gyp ERR! find Python   (accepted by both node-gyp and npm)
gyp ERR! find Python - Set the environment variable PYTHON
gyp ERR! find Python - Set the npm configuration variable python:
gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
gyp ERR! find Python For more information consult the documentation at:
gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
gyp ERR! find Python **********************************************************
gyp ERR! find Python
gyp ERR! configure error
gyp ERR! stack Error: Could not find any Python installation to use
gyp ERR! stack     at PythonFinder.fail (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:307:47)
gyp ERR! stack     at PythonFinder.runChecks (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:136:21)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:225:16)
gyp ERR! stack     at PythonFinder.execFileCallback (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\find-python.js:271:16)
gyp ERR! stack     at exithandler (child_process.js:310:5)
gyp ERR! stack     at ChildProcess.errorhandler (child_process.js:322:5)
gyp ERR! stack     at ChildProcess.emit (events.js:321:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
gyp ERR! stack     at onErrorNT (internal/child_process.js:467:16)
gyp ERR! stack     at processTicksAndRejections (internal/process/task_queues.js:84:21)
gyp ERR! System Windows_NT 10.0.18362
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\alumno_ciclo\node_modules\gl
gyp ERR! node -v v13.8.0
gyp ERR! node-gyp -v v5.0.5
gyp ERR! not ok
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\alumno_ciclo\package.json'
npm WARN alumno_ciclo No description
npm WARN alumno_ciclo No repository field.
npm WARN alumno_ciclo No README data
npm WARN alumno_ciclo No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: webworker-threads@0.7.17 (node_modules\webworker-threads):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: webworker-threads@0.7.17 install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! gl@4.4.1 install: `prebuild-install || node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the gl@4.4.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\alumno_ciclo\AppData\Roaming\npm-cache\_logs\2020-02-19T18_15_18_690Z-debug.log

I tried to reinstall nodejs, and install python, and configure some window's variables. But not, this command is impossible to run. Can anyguy help me? Thanks anyway.


问:
Perl Excel::Writer::XLSX
I'm trying to create an excel file using perl scripting.

  I followed the tutorial and write the following code :

```<code>#!/usr/bin/perl

use strict;
use warnings;
use Excel::Writer::XLSX;
use Excel::Writer::XLSX::Utility;

my $workbook = Excel::Writer::XLSX->new( 'perl.xlsx' );    # Step 1
$worksheet = $workbook->add_worksheet('cc');                   # Step 2
$worksheet->write( 'A1', 'Hi Excel!' );
</code>```

But I got the following error :

```<code>Global symbol "$worksheet" requires explicit package name at test_excel.pl line 10.
Global symbol "$worksheet" requires explicit package name at test_excel.pl line 11.
</code>```

答:
You need to declare the $worksheet variable, like this

```<code>my $worksheet = $workbook->add_worksheet('cc');                   # Step 2
</code>```

Title: Perl Excel::Writer::XLSX

Body:
I'm trying to create an excel file using perl scripting.

  I followed the tutorial and write the following code :

#!/usr/bin/perl

use strict;
use warnings;
use Excel::Writer::XLSX;
use Excel::Writer::XLSX::Utility;

my $workbook = Excel::Writer::XLSX->new( 'perl.xlsx' );    # Step 1
$worksheet = $workbook->add_worksheet('cc');                   # Step 2
$worksheet->write( 'A1', 'Hi Excel!' );

But I got the following error :

Global symbol "$worksheet" requires explicit package name at test_excel.pl line 10.
Global symbol "$worksheet" requires explicit package name at test_excel.pl line 11.

Body:
You need to declare the $worksheet variable, like this

my $worksheet = $workbook->add_worksheet('cc');                   # Step 2


问:
How do I find the last sector of harddisk?
I have not tried to find the last sector by multiplying the number of sectors by 10. I tried to find it by increasing 1 but the system was very tired and took a lot of time. I don't want to filter out the output of ready commands.

How can I find the number of cylinders, heads and sectors. I think I will get the number of sectors by converting from chs system to lba system.

```<code>import os
def main():
    s=1
    if os.name == "nt":
        while True:
            if read_sector(r"\\.\physicaldrive0",s)=='':
                break
            else:
                s=s*10
            print(s)
    else:
        while True:
            if read_sector("/dev/sda",s)=='':
                break
            else:
                s=s*10
            print(s)
def read_sector(disk, sector_no=0):
    f = open(disk, 'rb')
    f.seek(sector_no * 1)
    read = f.read(1)
    return read

if __name__ == "__main__":
    main()
</code>```

or

```<code>import os
def main():
    s=0
    if os.name == "nt":
        while True:
            if read_sector(r"\\.\physicaldrive0",s)=='':
                break
            else:
                s=s+1
            print(s)
    else:
        while True:
            if read_sector("/dev/sda",s)=='':
                break
            else:
                s=s+1
            print(s)
def read_sector(disk, sector_no=0):
    f = open(disk, 'rb')
    f.seek(sector_no * 1)
    read = f.read(1)
    return read

if __name__ == "__main__":
    main()
</code>```

答:
```<code>import os
def end_sector(disk):
    os.system("fdisk -l %s >fdisk.lst"%disk)
    with open("fdisk.lst") as file:
        dosya=file.read()
        dosya=dosya.split()
        j=0
        for i in dosya:
            j=j+1
        for i in range(j):
            if dosya[i]=="sektör":
                max_sector=int(dosya[i-1])
        for i in range(j):
            if dosya[i]=="=" and dosya[i-1]==dosya[i+1]:
                sector_size=int(dosya[i+1])
    return max_sector,sector_size
dizi=end_sector("/dev/sdb")
print(dizi)
</code>```

Body:
I have not tried to find the last sector by multiplying the number of sectors by 10. I tried to find it by increasing 1 but the system was very tired and took a lot of time. I don't want to filter out the output of ready commands.

How can I find the number of cylinders, heads and sectors. I think I will get the number of sectors by converting from chs system to lba system.

import os
def main():
    s=1
    if os.name == "nt":
        while True:
            if read_sector(r"\\.\physicaldrive0",s)=='':
                break
            else:
                s=s*10
            print(s)
    else:
        while True:
            if read_sector("/dev/sda",s)=='':
                break
            else:
                s=s*10
            print(s)
def read_sector(disk, sector_no=0):
    f = open(disk, 'rb')
    f.seek(sector_no * 1)
    read = f.read(1)
    return read

if __name__ == "__main__":
    main()

or

import os
def main():
    s=0
    if os.name == "nt":
        while True:
            if read_sector(r"\\.\physicaldrive0",s)=='':
                break
            else:
                s=s+1
            print(s)
    else:
        while True:
            if read_sector("/dev/sda",s)=='':
                break
            else:
                s=s+1
            print(s)
def read_sector(disk, sector_no=0):
    f = open(disk, 'rb')
    f.seek(sector_no * 1)
    read = f.read(1)
    return read

if __name__ == "__main__":
    main()


问:
RecyclerView remains empty with Paging Library and PositionalDataSource
I am trying to configure the Android Paging library in my project to load a paginated list of messages into a RecyclerView. Since my API uses offset and max, I'm using a PositionalDataSource.

Here is my DataSource implementation, where DataStore is using RetroFit to load the messages, and I can see in the console that messages are being loaded properly, and converted to instances of MessageListItem:

```<code>class MessageDataSource: PositionalDataSource<MessageListItem>() {
    override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<MessageListItem>) {
        DataStore.shared.loadMessages(params.startPosition, params.loadSize) { result, error ->
            if(result != null) {
                callback.onResult(result.items)
            } else {
                callback.onError(MessageDataSourceException(error))
            }
        }
    }

    override fun loadInitial(
        params: LoadInitialParams,
        callback: LoadInitialCallback<MessageListItem>
    ) {
        DataStore.shared.loadMessages(params.requestedStartPosition, params.requestedLoadSize) { response, error ->
            if(response != null) {
                callback.onResult(response.items, response.offset, response.total)
            } else {
                callback.onError(MessageDataSourceException(error))
            }
        }
    }
}

class MessageDataSourceException(rootCause: Throwable? = null): Exception(rootCause)
</code>```

Here is my DataSourceFactory implementation:

```<code>class MessageDataSourceFactory: DataSource.Factory<Int, MessageListItem>() {
    val messageLiveDataSource = MutableLiveData<MessageDataSource>()
    private lateinit var messageDataSource: MessageDataSource

    override fun create(): DataSource<Int, MessageListItem> {
        messageDataSource = MessageDataSource()
        messageLiveDataSource.postValue(messageDataSource)
        return messageDataSource
    }
}
</code>```

Here is my MessageListAdapter implementation:

```<code>object MessageListItemDiff: DiffUtil.ItemCallback<MessageListItem>() {
    override fun areItemsTheSame(oldItem: MessageListItem, newItem: MessageListItem): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: MessageListItem, newItem: MessageListItem): Boolean {
        return oldItem == newItem
    }
}

class MessageListAdapter(private val clickListener: View.OnClickListener):
    PagedListAdapter<MessageListItem, MessageListAdapter.MessageHolder>(MessageListItemDiff) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageHolder {
        val inflatedView = LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false)
        return MessageHolder(inflatedView, clickListener)
    }

    override fun onBindViewHolder(holder: MessageHolder, position: Int) {
        holder.bind(getItem(position)!!)
    }

    class MessageHolder(itemView: View, private val clickListener: View.OnClickListener) : RecyclerView.ViewHolder(itemView) {
        val unreadIndicator = itemView.findViewById<ImageView>(R.id.unreadIndicator)
        val title = itemView.findViewById<TextView>(R.id.title)
        val dateSent = itemView.findViewById<TextView>(R.id.dateSent)
        val cardView = itemView.findViewById<CardView>(R.id.card_view)

        fun bind(message: MessageListItem) {
            cardView.tag = message
            cardView.setOnClickListener(clickListener)
            title.text = message.title
            dateSent.text = TimeAgo.using(message.dateSent.time)
            if(message.isRead) {
                unreadIndicator.setImageResource(0)
            } else {
                unreadIndicator.setImageResource(R.drawable.ic_unread)
            }
        }
    }
}
</code>```

And finally my ViewModel:

```<code>class MessageListViewModel: ViewModel() {
    val messagePagedList: LiveData<PagedList<MessageListItem>>
    val liveDataSource: LiveData<MessageDataSource>

    init {
        val messageDataSourceFactory = MessageDataSourceFactory()
        liveDataSource = messageDataSourceFactory.messageLiveDataSource

        val pagedListConfig = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(30)
            .setPrefetchDistance(90)
            .build()
        messagePagedList = LivePagedListBuilder(messageDataSourceFactory, pagedListConfig).build()
    }
}
</code>```

And here is the onViewCreated implementation in the fragment that is supposed to display the recycler view called messageList:

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        messageList.layoutManager = LinearLayoutManager(context!!)
        messageList.setHasFixedSize(true)

        messageListViewModel = ViewModelProvider(this).get(MessageListViewModel::class.java)
        messageListAdapter = MessageListAdapter(this)

        messageListViewModel.messagePagedList.observe(this, Observer { messages ->
            messageListAdapter.submitList(messages)
        })

        messageList.adapter = messageListAdapter
    }
</code>```

The problem is that I can see that data is being loaded from the server, but it never reaches the recycler view. If I add a breakpoint on the observer line (messageListAdapter.submitList(messages)), I get a call once with an empty message list, and that's it.

I have to admit I'm really confused with all these classes and what they are supposed to do, this is my first Paging implementation in Android, and I had to adapt code I found here and there because I didn't want to use a Room database, RxJava or a PageKeyedDataSource, which most samples out there do.

Any idea what might be going on?

答:
From what I know, for everything to work properly the PagedList instance must be preloaded with initial data as soon as it's dispatched by the LiveData. For this to occur, the data needs to be loaded when the loadInitial() method returns, which means that you need to perform the network call synchronously and call callback.onResult() from within the loadInitial() method call before the method returns, instead of using a callback. It's safe to perform network calls synchronously there because the LivePagedListBuilder will take care of calling the PagedList.Builder() from a background thread.

Also, error handling implementation is pretty much undocumented and incomplete at this point (in version 2.1.1) so calls to the recently added callback.onError() method will fail in many cases. For example, in version 2.1.1 error handling is not implemented at all in TiledPagedList, which is the type of PagedList used for a PositionalDataSource.

Finally, if you return an exact size for the list in loadInitial() (as you do here), then in loadRange() you need to make sure that you always return exactly the number of items that is requested. If the API requests 30 items and you only return 20, your app may crash. One workaround I found out is that you can pad the results list with null values so it always has the requested size, but then you need to enable placeholders. Alternatively, don't return an exact size in loadInitial() and the list will just grow dynamically.

This API is complex and tricky to use so don't blame yourself. Google is currently working on a new version 3.0 written in Kotlin which will hopefully fix all the issues of the old one.

Body:
I am trying to configure the Android Paging library in my project to load a paginated list of messages into a RecyclerView. Since my API uses offset and max, I'm using a PositionalDataSource.

Here is my DataSource implementation, where DataStore is using RetroFit to load the messages, and I can see in the console that messages are being loaded properly, and converted to instances of MessageListItem:

class MessageDataSource: PositionalDataSource<MessageListItem>() {
    override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<MessageListItem>) {
        DataStore.shared.loadMessages(params.startPosition, params.loadSize) { result, error ->
            if(result != null) {
                callback.onResult(result.items)
            } else {
                callback.onError(MessageDataSourceException(error))
            }
        }
    }

    override fun loadInitial(
        params: LoadInitialParams,
        callback: LoadInitialCallback<MessageListItem>
    ) {
        DataStore.shared.loadMessages(params.requestedStartPosition, params.requestedLoadSize) { response, error ->
            if(response != null) {
                callback.onResult(response.items, response.offset, response.total)
            } else {
                callback.onError(MessageDataSourceException(error))
            }
        }
    }
}

class MessageDataSourceException(rootCause: Throwable? = null): Exception(rootCause)

Here is my DataSourceFactory implementation:

class MessageDataSourceFactory: DataSource.Factory<Int, MessageListItem>() {
    val messageLiveDataSource = MutableLiveData<MessageDataSource>()
    private lateinit var messageDataSource: MessageDataSource

    override fun create(): DataSource<Int, MessageListItem> {
        messageDataSource = MessageDataSource()
        messageLiveDataSource.postValue(messageDataSource)
        return messageDataSource
    }
}

Here is my MessageListAdapter implementation:

object MessageListItemDiff: DiffUtil.ItemCallback<MessageListItem>() {
    override fun areItemsTheSame(oldItem: MessageListItem, newItem: MessageListItem): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: MessageListItem, newItem: MessageListItem): Boolean {
        return oldItem == newItem
    }
}

class MessageListAdapter(private val clickListener: View.OnClickListener):
    PagedListAdapter<MessageListItem, MessageListAdapter.MessageHolder>(MessageListItemDiff) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageHolder {
        val inflatedView = LayoutInflater.from(parent.context).inflate(R.layout.item_message, parent, false)
        return MessageHolder(inflatedView, clickListener)
    }

    override fun onBindViewHolder(holder: MessageHolder, position: Int) {
        holder.bind(getItem(position)!!)
    }

    class MessageHolder(itemView: View, private val clickListener: View.OnClickListener) : RecyclerView.ViewHolder(itemView) {
        val unreadIndicator = itemView.findViewById<ImageView>(R.id.unreadIndicator)
        val title = itemView.findViewById<TextView>(R.id.title)
        val dateSent = itemView.findViewById<TextView>(R.id.dateSent)
        val cardView = itemView.findViewById<CardView>(R.id.card_view)

        fun bind(message: MessageListItem) {
            cardView.tag = message
            cardView.setOnClickListener(clickListener)
            title.text = message.title
            dateSent.text = TimeAgo.using(message.dateSent.time)
            if(message.isRead) {
                unreadIndicator.setImageResource(0)
            } else {
                unreadIndicator.setImageResource(R.drawable.ic_unread)
            }
        }
    }
}

And finally my ViewModel:

class MessageListViewModel: ViewModel() {
    val messagePagedList: LiveData<PagedList<MessageListItem>>
    val liveDataSource: LiveData<MessageDataSource>

    init {
        val messageDataSourceFactory = MessageDataSourceFactory()
        liveDataSource = messageDataSourceFactory.messageLiveDataSource

        val pagedListConfig = PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPageSize(30)
            .setPrefetchDistance(90)
            .build()
        messagePagedList = LivePagedListBuilder(messageDataSourceFactory, pagedListConfig).build()
    }
}

And here is the onViewCreated implementation in the fragment that is supposed to display the recycler view called messageList:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        messageList.layoutManager = LinearLayoutManager(context!!)
        messageList.setHasFixedSize(true)

        messageListViewModel = ViewModelProvider(this).get(MessageListViewModel::class.java)
        messageListAdapter = MessageListAdapter(this)

        messageListViewModel.messagePagedList.observe(this, Observer { messages ->
            messageListAdapter.submitList(messages)
        })

        messageList.adapter = messageListAdapter
    }

The problem is that I can see that data is being loaded from the server, but it never reaches the recycler view. If I add a breakpoint on the observer line (messageListAdapter.submitList(messages)), I get a call once with an empty message list, and that's it.

I have to admit I'm really confused with all these classes and what they are supposed to do, this is my first Paging implementation in Android, and I had to adapt code I found here and there because I didn't want to use a Room database, RxJava or a PageKeyedDataSource, which most samples out there do.

Any idea what might be going on?


问:
Custom Level Logging in SLF4J
In my project logging is working perfectly fine. Using Slf4j for logging.
Sample is as follows:

```<code> import org.slf4j.LoggerFactory;
 import org.slf4j.Logger;
 public class MyClass{
   private static Logger logger = LoggerFactory.getLogger(MyClass.class);

   public static void main(String...args){
     logger.error("error log...");
   }
 }
</code>```

we have used log4j2.xml for logging configuration.
Now my requirement is to make a custom level log "VERBOSE" having int value 150. I am trying hard but it seems difficult or I dont know if slf4j has flexibility to provide the custom level logging.
Please assist.

答: The Log4j2 API has that capability. SLF4J does not. However, while not equivalent, you could add a VERBOSE Marker to the events and filter on that.</p>

Title: Custom Level Logging in SLF4J

Body:
In my project logging is working perfectly fine. Using Slf4j for logging.
Sample is as follows:

 import org.slf4j.LoggerFactory;
 import org.slf4j.Logger;
 public class MyClass{
   private static Logger logger = LoggerFactory.getLogger(MyClass.class);

   public static void main(String...args){
     logger.error("error log...");
   }
 }

we have used log4j2.xml for logging configuration.
Now my requirement is to make a custom level log "VERBOSE" having int value 150. I am trying hard but it seems difficult or I dont know if slf4j has flexibility to provide the custom level logging.
Please assist.


问:
Getting error - Unrecognized command "run-android", when running react native,
I get this error when try and run react native on my emulator, react-native run-android

error Unrecognized command "run-android".

My emulator is connected and working, any ideas?

Package.json:

```<code>{
  "name": "iaapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "name": "Inovative Anatomy",
    "flow": "flow",
    "test": "node ./node_modules/jest/bin/jest.js --watchAll"
  },
  "dependencies": {
    "@babel/plugin-proposal-decorators": "^7.4.4",
    "@react-native-community/async-storage": "^1.6.1",
    "react": "16.8.5",
    "react-dom": "^16.8.6",
    "react-native": "0.59.10",
    "react-native-circular-progress": "^1.1.0",
    "react-native-component-fade": "^1.0.2",
    "react-native-elements": "^1.1.0",
    "react-native-fade": "^1.0.3",
    "react-native-fade-in-view": "^1.0.5",
    "react-native-gesture-handler": "^1.3.0",
    "react-native-responsive-image": "^2.3.1",
    "react-native-share": "^1.2.1",
    "react-native-splash-screen": "^3.2.0",
    "react-native-svg": "^9.5.1",
    "react-native-vector-icons": "^6.6.0",
    "react-native-view-shot": "^2.6.0",
    "react-native-webview": "^5.12.1",
    "react-native-webview-bridge": "^0.40.1",
    "react-navigation": "^3.0.9",
    "react-navigation-backhandler": "^1.3.2",
    "react-navigation-transitions": "^1.0.11",
    "react-redux": "^6.0.1",
    "redux": "^4.0.1",
    "redux-persist": "^5.10.0",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.5.5",
    "@babel/core": "^7.5.5",
    "@babel/runtime": "^7.8.4",
    "@react-native-community/eslint-config": "^0.0.7",
    "@types/jest": "^24.0.18",
    "@types/react": "^16.9.2",
    "@types/react-native": "^0.60.14",
    "@types/react-redux": "^7.1.7",
    "@types/react-test-renderer": "^16.9.0",
    "@types/redux-logger": "^3.0.7",
    "@types/redux-persist": "^4.3.1",
    "babel-jest": "^24.1.0",
    "eslint": "^6.8.0",
    "jest": "^24.1.0",
    "metro-react-native-babel-preset": "0.54.1",
    "prettier": "^1.18.2",
    "react-native-dotenv": "^0.2.0",
    "react-test-renderer": "16.8.6",
    "redux-logger": "^3.0.6",
    "tslint-react": "^4.2.0",
    "typescript": "^3.6.3"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}
</code>```

答: try npx react-native run-android

Body:
I get this error when try and run react native on my emulator, react-native run-android

error Unrecognized command "run-android".

My emulator is connected and working, any ideas?

Package.json:

{
  "name": "iaapp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "name": "Inovative Anatomy",
    "flow": "flow",
    "test": "node ./node_modules/jest/bin/jest.js --watchAll"
  },
  "dependencies": {
    "@babel/plugin-proposal-decorators": "^7.4.4",
    "@react-native-community/async-storage": "^1.6.1",
    "react": "16.8.5",
    "react-dom": "^16.8.6",
    "react-native": "0.59.10",
    "react-native-circular-progress": "^1.1.0",
    "react-native-component-fade": "^1.0.2",
    "react-native-elements": "^1.1.0",
    "react-native-fade": "^1.0.3",
    "react-native-fade-in-view": "^1.0.5",
    "react-native-gesture-handler": "^1.3.0",
    "react-native-responsive-image": "^2.3.1",
    "react-native-share": "^1.2.1",
    "react-native-splash-screen": "^3.2.0",
    "react-native-svg": "^9.5.1",
    "react-native-vector-icons": "^6.6.0",
    "react-native-view-shot": "^2.6.0",
    "react-native-webview": "^5.12.1",
    "react-native-webview-bridge": "^0.40.1",
    "react-navigation": "^3.0.9",
    "react-navigation-backhandler": "^1.3.2",
    "react-navigation-transitions": "^1.0.11",
    "react-redux": "^6.0.1",
    "redux": "^4.0.1",
    "redux-persist": "^5.10.0",
    "redux-thunk": "^2.3.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.5.5",
    "@babel/core": "^7.5.5",
    "@babel/runtime": "^7.8.4",
    "@react-native-community/eslint-config": "^0.0.7",
    "@types/jest": "^24.0.18",
    "@types/react": "^16.9.2",
    "@types/react-native": "^0.60.14",
    "@types/react-redux": "^7.1.7",
    "@types/react-test-renderer": "^16.9.0",
    "@types/redux-logger": "^3.0.7",
    "@types/redux-persist": "^4.3.1",
    "babel-jest": "^24.1.0",
    "eslint": "^6.8.0",
    "jest": "^24.1.0",
    "metro-react-native-babel-preset": "0.54.1",
    "prettier": "^1.18.2",
    "react-native-dotenv": "^0.2.0",
    "react-test-renderer": "16.8.6",
    "redux-logger": "^3.0.6",
    "tslint-react": "^4.2.0",
    "typescript": "^3.6.3"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

Body: try npx react-native run-android


问:
npm start errors with ERR! code ENOENT, syscall open
I'm suddenly having a problem with "npm start" in my React application. When I trigger it, this is what I receive:

```<code>npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /mnt/c/Users/pal/Desktop/dev/myApp/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/palnic/.npm/_logs/2020-02-20T11_30_39_463Z-debug.log
</code>```

This is the debug.log:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'start' ]
2 info using npm@6.13.7
3 info using node@v12.13.1
4 verbose stack Error: ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
5 verbose cwd /mnt/c/Users/pal/Desktop/dev/myApp/package.json
6 verbose Linux 4.4.0-18362-Microsoft
7 verbose argv "/usr/bin/node" "/usr/bin/npm" "start"
8 verbose node v12.13.1
9 verbose npm  v6.13.7
10 error code ENOENT
11 error syscall open
12 error path /mnt/c/Users/pal/Desktop/dev/myApp/package.json
13 error errno -2
14 error enoent ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
15 error enoent This is related to npm not being able to find a file.
16 verbose exit [ -2, true ]
</code>```

I tried the following solution:

```<code>sudo npm install -g npm     //(ok!)
sudo npm cache clean   //(not working if not using --force flag)
</code>```

And then npm install returns:

```<code>npm WARN saveError ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
npm WARN enoent ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
npm WARN myApp No description
npm WARN myApp No repository field.
npm WARN myApp No README data
npm WARN myApp No license field.

up to date in 0.454s
found 0 vulnerabilities
</code>```

My npm version is: 6.13.7

This is my package.json

```<code>{
  "name": "myApp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^7.2.1",
    "firebase": "^7.7.0",
    "node-sass": "^4.13.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-redux": "^7.1.3",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.3.0",
    "react-stripe-checkout": "^2.6.3",
    "redux": "^4.0.5",
    "redux-logger": "^3.0.6",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.1.3",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "styled-components": "^5.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

Do you have any ideas on the possible causes and the possible solutions?

答:
Your stated error:

npm WARN saveError ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'

  npm WARN enoent ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'

  npm WARN myApp No description

  npm WARN myApp No repository field.

  npm WARN myApp No README data

  npm WARN myApp No license field.

You can check the bold lines. It explains that you are not in the directory which contains the package.json file.

Most of the times you should run this command in the app directory. So, you need to cd into the directory which holds package.json then there you can run your commands like npm install, npm start etc.

So, before running these commands please check if you are in the correct directory.

Body:
I'm suddenly having a problem with "npm start" in my React application. When I trigger it, this is what I receive:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path /mnt/c/Users/pal/Desktop/dev/myApp/package.json
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/palnic/.npm/_logs/2020-02-20T11_30_39_463Z-debug.log

This is the debug.log:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'start' ]
2 info using npm@6.13.7
3 info using node@v12.13.1
4 verbose stack Error: ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
5 verbose cwd /mnt/c/Users/pal/Desktop/dev/myApp/package.json
6 verbose Linux 4.4.0-18362-Microsoft
7 verbose argv "/usr/bin/node" "/usr/bin/npm" "start"
8 verbose node v12.13.1
9 verbose npm  v6.13.7
10 error code ENOENT
11 error syscall open
12 error path /mnt/c/Users/pal/Desktop/dev/myApp/package.json
13 error errno -2
14 error enoent ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
15 error enoent This is related to npm not being able to find a file.
16 verbose exit [ -2, true ]

I tried the following solution:

sudo npm install -g npm     //(ok!)
sudo npm cache clean   //(not working if not using --force flag)

And then npm install returns:

npm WARN saveError ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
npm WARN enoent ENOENT: no such file or directory, open '/mnt/c/Users/pal/Desktop/dev/myApp/package.json'
npm WARN myApp No description
npm WARN myApp No repository field.
npm WARN myApp No README data
npm WARN myApp No license field.

up to date in 0.454s
found 0 vulnerabilities

My npm version is: 6.13.7

This is my package.json

{
  "name": "myApp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^7.2.1",
    "firebase": "^7.7.0",
    "node-sass": "^4.13.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-redux": "^7.1.3",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.3.0",
    "react-stripe-checkout": "^2.6.3",
    "redux": "^4.0.5",
    "redux-logger": "^3.0.6",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.1.3",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "styled-components": "^5.0.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Do you have any ideas on the possible causes and the possible solutions?


问:
How to insert data to database without login, wordpress?
I create some plugin in Wordpress. This plugin will insert data into the database from the Android App via POST and will return the string message. So my question is how to insert data to the database without login in Wordpress? Because user can register via the Android app, but without login first in Wordpress. Also what about the URL action to send data to Wordpress?

This is my simple code.

```<code>global $wpdb;

$table_name = $wpdb->prefix . 'cte'; // do not forget about tables prefix

$wpdb->insert($table_name, array(
    'name' => 'Alex',
    'email' => 'alex@example.com',
    'age' => 25
));
</code>```

答:
```<code>require_once('../../../wp-load.php');
global $wpdb;

$table_name = $wpdb->prefix . 'cte'; // do not forget about tables prefix

$wpdb->insert($table_name, array(
    'name' => 'Alex',
    'email' => 'alex@example.com',
    'age' => 25
));
</code>```

or probably get the wp-load.php with your path where you are putting the code

Body:
I create some plugin in Wordpress. This plugin will insert data into the database from the Android App via POST and will return the string message. So my question is how to insert data to the database without login in Wordpress? Because user can register via the Android app, but without login first in Wordpress. Also what about the URL action to send data to Wordpress?

This is my simple code.

global $wpdb;

$table_name = $wpdb->prefix . 'cte'; // do not forget about tables prefix

$wpdb->insert($table_name, array(
    'name' => 'Alex',
    'email' => 'alex@example.com',
    'age' => 25
));

Body:
require_once('../../../wp-load.php');
global $wpdb;

$table_name = $wpdb->prefix . 'cte'; // do not forget about tables prefix

$wpdb->insert($table_name, array(
    'name' => 'Alex',
    'email' => 'alex@example.com',
    'age' => 25
));

or probably get the wp-load.php with your path where you are putting the code


问:
Is there a list of JSON parse error codes?
I'm trying to provide a good experience to users that are using JSON and the parser is on the backend (Ruby).

Most of the time, when you get a badly formatted JSON payload the error is of the format XXX unexpected token at '<entire payload here>'. That's not very user-friendly nor practical.

My question is: Is there a list of the XXX error codes that could help create better error messages that could be understood by beginners and not-really-tech-people?

Thanks!

答: XXX in this kind of errors is not a special code of the error. It is just a line number from the file where this error was raised. For example, for Ruby 2.5.1 you'll get JSON::ParserError (765: unexpected token at https://github.com/ruby/ruby/blob/v2_5_1/ext/json/parser/parser.rl#L765


问:
Creating a Function That Automaticaly Knows Whether to Insert or Update in Flask, SqlAlchemy, Python
I currently have two seperate sections of code, one that inserts an entirely new row into mySQL database. The second one just updates a row if it already exists.

I am trying to combine these two into one function that automatically checks if the id is in the table, and if so updates, otherwise inserts a new row? This is what I have so far:

```<code>class Example(db.Model):
        __tablename__ = 'schools'
        _id = db.Column('_id', db.Unicode, primary_key=True)
        establishmentNumber = db.Column('establishmentNumber', db.Unicode)
        laCode = db.Column('laCode', db.Unicode)
        urn = db.Column('urn', db.Unicode)
        name = db.Column('name', db.Unicode)
        phaseOfEducation = db.Column('phaseOfEducation', db.Unicode)
        wondeID = db.Column('wondeID', db.Unicode)

        def __init__(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
            self._id = _id
            self.establishmentNumber = establishmentNumber
            self.laCode = laCode
            self.urn = urn
            self.name = name
            self.phaseOfEducation = phaseOfEducation
            self.wondeID = wondeID

            def add_or_update(cls, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
                entity = cls.query.filter_by(_id=school._id.iloc[0]).first()
                print(entity)

                if not entity:
                    entity = cls(school._id.iloc[0], school.establishmentNumber.iloc[0], school.laCode.iloc[0], school.urn.iloc[0], school.name.iloc[0], school.phaseOfEducation.iloc[0], school.wondeID.iloc[0])
                    db.session.add(entity)
                    db.session.commit()

                else:
                    entity.establishmentNumber = 'hello'
                    db.session.commit()
                    print (entity.establishmentNumber)

                return entity
</code>```

It doesn't produce any errors, but it also doesn't add or update either. Can anyone see what I've done wrong?

答:
you have indentation error. Reindent like:</p>

```<code>def __init__(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
    self._id = _id
    self.establishmentNumber = establishmentNumber
    self.laCode = laCode
    self.urn = urn
    self.name = name
    self.phaseOfEducation = phaseOfEducation
    self.wondeID = wondeID

@classmethod
def add_or_update(cls, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
    entity = cls.query.filter_by(_id=school._id.iloc[0]).first()
    print(entity)

    if not entity:
        entity = cls(school._id.iloc[0], school.establishmentNumber.iloc[0], school.laCode.iloc[0],
                     school.urn.iloc[0], school.name.iloc[0], school.phaseOfEducation.iloc[0],
                     school.wondeID.iloc[0])
        db.session.add(entity)
        db.session.commit()

    else:
        entity.establishmentNumber = 'hello'
        db.session.commit()
        print(entity.establishmentNumber)

    return entity
</code>```

Body:
I currently have two seperate sections of code, one that inserts an entirely new row into mySQL database. The second one just updates a row if it already exists.

I am trying to combine these two into one function that automatically checks if the id is in the table, and if so updates, otherwise inserts a new row? This is what I have so far:

class Example(db.Model):
        __tablename__ = 'schools'
        _id = db.Column('_id', db.Unicode, primary_key=True)
        establishmentNumber = db.Column('establishmentNumber', db.Unicode)
        laCode = db.Column('laCode', db.Unicode)
        urn = db.Column('urn', db.Unicode)
        name = db.Column('name', db.Unicode)
        phaseOfEducation = db.Column('phaseOfEducation', db.Unicode)
        wondeID = db.Column('wondeID', db.Unicode)

        def __init__(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
            self._id = _id
            self.establishmentNumber = establishmentNumber
            self.laCode = laCode
            self.urn = urn
            self.name = name
            self.phaseOfEducation = phaseOfEducation
            self.wondeID = wondeID

            def add_or_update(cls, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
                entity = cls.query.filter_by(_id=school._id.iloc[0]).first()
                print(entity)

                if not entity:
                    entity = cls(school._id.iloc[0], school.establishmentNumber.iloc[0], school.laCode.iloc[0], school.urn.iloc[0], school.name.iloc[0], school.phaseOfEducation.iloc[0], school.wondeID.iloc[0])
                    db.session.add(entity)
                    db.session.commit()

                else:
                    entity.establishmentNumber = 'hello'
                    db.session.commit()
                    print (entity.establishmentNumber)

                return entity

It doesn't produce any errors, but it also doesn't add or update either. Can anyone see what I've done wrong?

Body:
you have indentation error. Reindent like:

def __init__(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
    self._id = _id
    self.establishmentNumber = establishmentNumber
    self.laCode = laCode
    self.urn = urn
    self.name = name
    self.phaseOfEducation = phaseOfEducation
    self.wondeID = wondeID

@classmethod
def add_or_update(cls, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
    entity = cls.query.filter_by(_id=school._id.iloc[0]).first()
    print(entity)

    if not entity:
        entity = cls(school._id.iloc[0], school.establishmentNumber.iloc[0], school.laCode.iloc[0],
                     school.urn.iloc[0], school.name.iloc[0], school.phaseOfEducation.iloc[0],
                     school.wondeID.iloc[0])
        db.session.add(entity)
        db.session.commit()

    else:
        entity.establishmentNumber = 'hello'
        db.session.commit()
        print(entity.establishmentNumber)

    return entity


答:
Using Aliaseseseseseses</p>

```<code>using Foo.Uber;
using FooUberBar = Foo.Uber.Bar

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = FooUberBar();
        }
    }
}
</code>```

Title: Absolute/outer and inner namespace confusion in C#

Body:
using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}

How could I solve this? Just moving the using statement inside my namespace doesn't help.

Body:
Using Aliaseseseseseses

using Foo.Uber;
using FooUberBar = Foo.Uber.Bar

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = FooUberBar();
        }
    }
}


问:
Iterate blocks of struct in memory using pointer
Good day,

    I am trying to create dynamic list of struct using malloc function. For each block of struct, i want to set the struct fields and then i would like to loop through each memory. Below is the code that i wrote :-

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int id;
    int portnum;
    int baudrate;
} port_t;

int main()
{

    port_t *port_pt = (port_t *)malloc(sizeof(port_t) * 2); //allocate two blocks

    port_pt->id = 1;
    port_pt->portnum = 9;
    port_pt->baudrate = 4800;

    printf("id : %i, port :COM%i baud : %i\n\n", port_pt->id, port_pt->portnum, port_pt->baudrate);

    port_pt++; //try make pointer point to next block
    port_pt->id = 2;
    port_pt->portnum = 9;
    port_pt->baudrate = 4800;
    port_pt--; //try to make pointer point to prev block

    int count = 0;
    while (port_pt != NULL)
    {
        printf("DEBUG id : %i, port :COM%i baud : %i\n", port_pt->id, port_pt->portnum, port_pt->baudrate);
        port_pt++;
    }

    return 0;
}

```

    However, when i compile and run this code. I get this lines output instead of two lines only : -

    Can anyone show me where i did wrong? I am really struggling with pointers.

答:
What you have written is an array (with incorrect usage as mentioned by Sri), not a linked list.

To create a linked list, you need to add a pointer to your struct to your struct (<- not a grammar error!), but as your code currently is, that is not possible. You have to change the declaration as well:

```<code>typedef struct
{
    int id;
    int portnum;
    int baudrate;
} port_t;
</code>```

to:

```<code>typedef struct port_t
{
    struct port_t *next;
    int id;
    int portnum;
    int baudrate;
} port_t;
</code>```

struct tag puts tag into a special namespace that is immediately (before even the opening {), and this namespace is accessible only via struct (in C. C++ puts tag into the parent namespace as well, so the above will give a redeclaration error, thus why modern headers tend to use typedef struct tag_s {...} tag_t;).

From there, you would allocate single element blocks using malloc, assigning each new block pointer to the next field in the previous block, and set the final next field to NULL (or 0). Of course, you will want to keep track of the first block, and you will need to free each block individually too.

Body:
Good day,

    I am trying to create dynamic list of struct using malloc function. For each block of struct, i want to set the struct fields and then i would like to loop through each memory. Below is the code that i wrote :-

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int id;
    int portnum;
    int baudrate;
} port_t;

int main()
{

    port_t *port_pt = (port_t *)malloc(sizeof(port_t) * 2); //allocate two blocks

    port_pt->id = 1;
    port_pt->portnum = 9;
    port_pt->baudrate = 4800;

    printf("id : %i, port :COM%i baud : %i\n\n", port_pt->id, port_pt->portnum, port_pt->baudrate);

    port_pt++; //try make pointer point to next block
    port_pt->id = 2;
    port_pt->portnum = 9;
    port_pt->baudrate = 4800;
    port_pt--; //try to make pointer point to prev block

    int count = 0;
    while (port_pt != NULL)
    {
        printf("DEBUG id : %i, port :COM%i baud : %i\n", port_pt->id, port_pt->portnum, port_pt->baudrate);
        port_pt++;
    }

    return 0;
}

    However, when i compile and run this code. I get this lines output instead of two lines only : -

    Can anyone show me where i did wrong? I am really struggling with pointers.

Body:
What you have written is an array (with incorrect usage as mentioned by Sri), not a linked list.

To create a linked list, you need to add a pointer to your struct to your struct (<- not a grammar error!), but as your code currently is, that is not possible. You have to change the declaration as well:

typedef struct
{
    int id;
    int portnum;
    int baudrate;
} port_t;

to:

typedef struct port_t
{
    struct port_t *next;
    int id;
    int portnum;
    int baudrate;
} port_t;

struct tag puts tag into a special namespace that is immediately (before even the opening {), and this namespace is accessible only via struct (in C. C++ puts tag into the parent namespace as well, so the above will give a redeclaration error, thus why modern headers tend to use typedef struct tag_s {...} tag_t;).

From there, you would allocate single element blocks using malloc, assigning each new block pointer to the next field in the previous block, and set the final next field to NULL (or 0). Of course, you will want to keep track of the first block, and you will need to free each block individually too.


答:
Use:

```<code>#convert values to DataFrame
df = pd.DataFrame(a)
#convert column to datetimes
d = pd.to_datetime(df['time'], unit='s')
#change format of datetimes
df['time'] = d.dt.strftime('%Y-%m-%d')
#create DatetimeIndex
df.index = d

#create nested dictionaries
d = {k.strftime('%Y-%m-%d'): v.to_dict('r') for k, v in df.groupby(pd.Grouper(freq='2D'))}
</code>```

Or:

```<code>d = {k.strftime('%Y-%m-%d'): v.to_dict('r') for k, v in df.resample('2D')}
</code>```

```<code>print (d)
{'2020-01-01': [{'content': '11', 'time': '2020-01-01'},
                {'content': '44', 'time': '2020-01-01'},
                {'content': '66', 'time': '2020-01-02'}],
'2020-01-03': [{'content': '22', 'time': '2020-01-03'},
               {'content': '33', 'time': '2020-01-04'}],
 '2020-01-05': [{'content': '44', 'time': '2020-01-05'},
                {'content': '55', 'time': '2020-01-06'}]}
</code>```

Title: pandas group by three day or two week or four month for timestamp

Body:
I'm a pandas beginner. i want to three day or two week or four month

I have the following data:

a = [{"content": '11', "time": 1577870427},
     {"content": '44', "time": 1577870427},
     {"content": '22', "time": 1578043227},
     {"content": '33', "time": 1578129627},
     {"content": '44', "time": 1578216027},
     {"content": '55', "time": 1578302427},
     {"content": '66', "time": 1577956827}]

And I want:

2020-01-01: [
     {"content": '11', "time": '2020-01-01'},
     {"content": '44', "time": '2020-01-01'},
     {"content": '22', "time": '2020-01-02'},
    ]

 2020-01-03: [
     {"content": '33', "time": '2020-01-03'},
     {"content": '44', "time": '2020-01-04'},
    ]

2020-01-05: [
     {"content": '55', "time": '2020-01-05'},
     {"content": '66', "time": '2020-01-06'}
    ]

my code

index = pd.to_datetime([i['time'] for i in a], unit='s')
df = pd.Series(a,index)

d1 = {k: v.to_dict('r') for k, v in df.groupby('2d')}
print(d1)

Body:
Use:

#convert values to DataFrame
df = pd.DataFrame(a)
#convert column to datetimes
d = pd.to_datetime(df['time'], unit='s')
#change format of datetimes
df['time'] = d.dt.strftime('%Y-%m-%d')
#create DatetimeIndex
df.index = d

#create nested dictionaries
d = {k.strftime('%Y-%m-%d'): v.to_dict('r') for k, v in df.groupby(pd.Grouper(freq='2D'))}

Or:

d = {k.strftime('%Y-%m-%d'): v.to_dict('r') for k, v in df.resample('2D')}

print (d)
{'2020-01-01': [{'content': '11', 'time': '2020-01-01'},
                {'content': '44', 'time': '2020-01-01'},
                {'content': '66', 'time': '2020-01-02'}],
'2020-01-03': [{'content': '22', 'time': '2020-01-03'},
               {'content': '33', 'time': '2020-01-04'}],
 '2020-01-05': [{'content': '44', 'time': '2020-01-05'},
                {'content': '55', 'time': '2020-01-06'}]}