问:
How do I calculate the ADI and COV of time series data using SQL?
I'm trying to classify time series data using SQL. I have data for a reference data point that occurs over 3 years. So the reference occurs 36 times, one for each month. Sometimes the quantity is 0, other times it may be 25 or even higher for each row. What I want to know is how to calculate these equations using SQL (MSSQL in particular).

Then, similarly, I want to classify the data into Erratic, Smooth, Lumpy, and/or Intermittent as seen here.

Smooth demand (ADI < 1.32 and CV² < 0.49). The demand is very regular
in time and in quantity. It is therefore easy to forecast and you
won’t have trouble reaching a low forecasting error level.

Intermittent demand (ADI >= 1.32 and CV² < 0.49). The demand history
shows very little variation in demand quantity but a high variation in
the interval between two demands. Though specific forecasting methods
tackle intermittent demands, the forecast error margin is considerably
higher.

Erratic demand (ADI < 1.32 and CV² >= 0.49). The demand has
regular occurrences in time with high quantity variations. Your
forecast accuracy remains shaky.

Lumpy demand (ADI >= 1.32 and CV² >=
0.49). The demand is characterized by a large variation in quantity and in time. It is actually impossible to produce a reliable forecast,
no matter which forecasting tools you use. This particular type of
demand pattern is unforecastable.

Here is the query that produces the table that I am working with.

```<code>SELECT
distinct
CHAN_ID
,PROD_CD
,CP_REF
,PARENT
,ORDERED_DATE
,QUANTITY
FROM DF_ALL_DEMAND_BY_ROW_V
where parent is not null
</code>```

CP_REF is the ID that I am focusing on.

Here is an example of the top 12 rows.

Please ask if you need more clarity. My SQL skills are barely basic.

答:
```<code>with data as (
    select
        CP_REF,
        count(*) * 1.0 /
          nullif(count(case when QUANTITY > 0 then 1 end), 0) as ADI,
          stdevp(QUANTITY) / nullif(avg(QUANTITY), 0) as COV
    from DF_ALL_DEMAND_BY_ROW_V
    where parent is not null
    group by CP_REF
)
select
    CP_REF, ADI, COV,
    case
        when ADI <  1.32 and COV <  0.49 then 'Smooth'
        when ADI >= 1.32 and COV <  0.49 then 'Intermittent'
        when ADI <  1.32 and COV >= 0.49 then 'Erratic'
        when ADI >= 1.32 and COV >= 0.49 then 'Lumpy'
        else 'Smooth'
    end as DEMAND
from data;
</code>```

Double check that you want to use stdevp() and not stdev. I wish I were more knowledgeable about statistics.

Body:
I'm trying to classify time series data using SQL. I have data for a reference data point that occurs over 3 years. So the reference occurs 36 times, one for each month. Sometimes the quantity is 0, other times it may be 25 or even higher for each row. What I want to know is how to calculate these equations using SQL (MSSQL in particular).

Then, similarly, I want to classify the data into Erratic, Smooth, Lumpy, and/or Intermittent as seen here.

Smooth demand (ADI < 1.32 and CV² < 0.49). The demand is very regular
in time and in quantity. It is therefore easy to forecast and you
won’t have trouble reaching a low forecasting error level.

Intermittent demand (ADI >= 1.32 and CV² < 0.49). The demand history
shows very little variation in demand quantity but a high variation in
the interval between two demands. Though specific forecasting methods
tackle intermittent demands, the forecast error margin is considerably
higher.

Erratic demand (ADI < 1.32 and CV² >= 0.49). The demand has
regular occurrences in time with high quantity variations. Your
forecast accuracy remains shaky.

Lumpy demand (ADI >= 1.32 and CV² >=
0.49). The demand is characterized by a large variation in quantity and in time. It is actually impossible to produce a reliable forecast,
no matter which forecasting tools you use. This particular type of
demand pattern is unforecastable.

Here is the query that produces the table that I am working with.

SELECT
distinct
CHAN_ID
,PROD_CD
,CP_REF
,PARENT
,ORDERED_DATE
,QUANTITY
FROM DF_ALL_DEMAND_BY_ROW_V
where parent is not null

CP_REF is the ID that I am focusing on.

Here is an example of the top 12 rows.

Please ask if you need more clarity. My SQL skills are barely basic.

Body:
with data as (
    select
        CP_REF,
        count(*) * 1.0 /
          nullif(count(case when QUANTITY > 0 then 1 end), 0) as ADI,
          stdevp(QUANTITY) / nullif(avg(QUANTITY), 0) as COV
    from DF_ALL_DEMAND_BY_ROW_V
    where parent is not null
    group by CP_REF
)
select
    CP_REF, ADI, COV,
    case
        when ADI <  1.32 and COV <  0.49 then 'Smooth'
        when ADI >= 1.32 and COV <  0.49 then 'Intermittent'
        when ADI <  1.32 and COV >= 0.49 then 'Erratic'
        when ADI >= 1.32 and COV >= 0.49 then 'Lumpy'
        else 'Smooth'
    end as DEMAND
from data;

Double check that you want to use stdevp() and not stdev. I wish I were more knowledgeable about statistics.


来源: stackexchange

问:
Click inside Loop issue - Remove dynamically created elements
The following code takes all the links onto the page that contains "https" and not "google.com" and turns them into iFrames. While that works, the close button that each is iFrame is supposed to be paired with does not work. When you click close, it only closes the last iFrame element on the page. I prefer to be able to do this in vanilla JavaScript, as opposed to jQuery.

total = []
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
  var link = links[i];
  if (link.href.indexOf("https") != -1 &&
 link.href.indexOf("google.com") == -1) {
    var hey = (links[i].href);
    console.log(link.href);
    total.push(links[i].href);
    var iframe = document.createElement('iframe');
    iframe.src = hey;
    document.body.appendChild(iframe);
    var close = document.createElement('button');
    document.body.appendChild(close);
    close.innerHTML = "close";
    close.addEventListener('click',function(){
      console.log("click");
      document.body.removeChild(iframe);
      document.body.removeChild(close);
    })
  }
}
```

答:
JS is not my primary language, but try this:</p>
```<code>total = []
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
    var link = links[i];
    if (link.href.indexOf("https") != -1 && link.href.indexOf("google.com") == -1) {
        var hey = (links[i].href);
        console.log(link.href);
        total.push(links[i].href);
        var iframe = document.createElement('iframe');
        iframe.src = hey;
        document.body.appendChild(iframe);
        var close = document.createElement('button');
        document.body.appendChild(close);
        close.innerHTML = "close";
        close.addEventListener('click',function(){
            console.log("click");
            document.body.removeChild(iframe);
            document.body.removeChild(close);
            document.body.removeChild(document.getElementById("iframe"));
        });
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
JS is not my primary language, but try this:

total = []
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
    var link = links[i];
    if (link.href.indexOf("https") != -1 && link.href.indexOf("google.com") == -1) {
        var hey = (links[i].href);
        console.log(link.href);
        total.push(links[i].href);
        var iframe = document.createElement('iframe');
        iframe.src = hey;
        document.body.appendChild(iframe);
        var close = document.createElement('button');
        document.body.appendChild(close);
        close.innerHTML = "close";
        close.addEventListener('click',function(){
            console.log("click");
            document.body.removeChild(iframe);
            document.body.removeChild(close);
            document.body.removeChild(document.getElementById("iframe"));
        });
    }
}


问:
How can I print a grep result with the matched word?
I have two files, "file A":

```<code>Adygei
Albanian
Armenia_C
Armenia_Caucasus
Armenia_EBA
Armenia_LBA
Armenia_MBA
Armenian.DG
Austria_EN_HG_LBK
Austria_EN_LBK
</code>```

And "fileB":

```<code>HG01880.SG Aygei_o1.SG
HG01988.SG Adygei_o2.SG
HG02419.SG Albanian_o2.SG
HG01879.SG Albanian.SG
HG01882.SG Armenia_C.SG
HG01883.SG Armenia_C.SG
HG01885.SG Armenia_EBA.SG
HG01886.SG Armenia_EBA.SG
HG01889.SG Armenia_LBA.SG
HG01890.SG Armenia_MBA.SG
</code>```

What I want at the end is create a new columne (doesn't matter the position of the column) with the grep word with the word that matched. Like This:

```<code>HG01880.SG Aygei_o1.SG Adygei
HG01988.SG Adygei_o2.SG Adygei
HG02419.SG Albanian_o2.SG Albanian
HG01879.SG Albanian.SG Albanian
HG01882.SG Armenia_C.SG Armenia_C
HG01883.SG Armenia_C.SG Armenia_C
HG01885.SG Armenia_EBA.SG Armenia_EBA
HG01886.SG Armenia_EBA.SG Armenia_EBA
HG01889.SG Armenia_LBA.SG Armenia_LBA
HG01890.SG Armenia_MBA.SG Armenia_MBA
</code>```

What I used to match both files in bash is grep -wFf fileA fileB > newfileA_B.txt. This can be both in python or bash

答:
You can try something like that:</p>
```<code>for line in $(cat fileA.txt)
do
  echo "$line $(grep $line fileB.txt)"
done
</code>```

Body:
I have two files, "file A":

Adygei
Albanian
Armenia_C
Armenia_Caucasus
Armenia_EBA
Armenia_LBA
Armenia_MBA
Armenian.DG
Austria_EN_HG_LBK
Austria_EN_LBK

And "fileB":

HG01880.SG Aygei_o1.SG
HG01988.SG Adygei_o2.SG
HG02419.SG Albanian_o2.SG
HG01879.SG Albanian.SG
HG01882.SG Armenia_C.SG
HG01883.SG Armenia_C.SG
HG01885.SG Armenia_EBA.SG
HG01886.SG Armenia_EBA.SG
HG01889.SG Armenia_LBA.SG
HG01890.SG Armenia_MBA.SG

What I want at the end is create a new columne (doesn't matter the position of the column) with the grep word with the word that matched. Like This:

HG01880.SG Aygei_o1.SG Adygei
HG01988.SG Adygei_o2.SG Adygei
HG02419.SG Albanian_o2.SG Albanian
HG01879.SG Albanian.SG Albanian
HG01882.SG Armenia_C.SG Armenia_C
HG01883.SG Armenia_C.SG Armenia_C
HG01885.SG Armenia_EBA.SG Armenia_EBA
HG01886.SG Armenia_EBA.SG Armenia_EBA
HG01889.SG Armenia_LBA.SG Armenia_LBA
HG01890.SG Armenia_MBA.SG Armenia_MBA

What I used to match both files in bash is grep -wFf fileA fileB > newfileA_B.txt. This can be both in python or bash

Body:
You can try something like that:

for line in $(cat fileA.txt)
do
  echo "$line $(grep $line fileB.txt)"
done


问:
Convert columns of R dataframe to JSON
I have this dataframe:

```<code>df <- data.frame(
  option_label_1 = c("thickness", "strength", "color"),
  option_value_1 = c("0.5 in", "2 lb" , "red"),
  option_label_2 = c("size", "color", "thickness"),
  option_value_2 = c("0.5 Inches x 7200 Feet", "blue" , "1 in"),
  option_label_3 = c("stretch", NA, NA),
  option_value_3 = c("wide", NA , NA)
  )
</code>```
```<code>  option_label_1 option_value_1 option_label_2         option_value_2 option_label_3 option_value_3
1      thickness         0.5 in           size 0.5 Inches x 7200 Feet        stretch           wide
2       strength           2 lb          color                   blue           <NA>           <NA>
3          color            red      thickness                   1 in           <NA>           <NA>
</code>```

I want this data frame:

```<code>  option_label_1 option_value_1 option_label_2         option_value_2 option_label_3 option_value_3
1      thickness         0.5 in           size 0.5 Inches x 7200 Feet        stretch           wide
2       strength           2 lb          color                   blue           <NA>           <NA>
3          color            red      thickness                   1 in           <NA>           <NA>
                                                                       json
1 {"thickness":"0.5 in","size":"0.5 Inches x 7200 Feet","stretch":"wide"}
2                                       {"strength":"2 lb","color":"blue"}
3                                        {"color":"red","thickness":"1 in"}
</code>```

Essentially I want a JSON column added to the original df built off of the original columns using the option labels and option values. Please note I do not want a solution that converts the whole dataframe to JSON using toJSON. I have a much larger dataframe with other fields I do not want in JSON. I just want the option_labels and their respective option_values to be in JSON.

I have tried using list and paste functions nested in toJSON, but the "option_labels" are static and don't change accordingly in the resulting JSON column.

Thanks for your help!

答:
This solution ultimately worked for me. Thanks to everyone who contributed.</p>
```<code>df_1 <- df %>%
  rowwise() %>%
  dplyr::mutate(
    options_json = ifelse(!is.na(option_value_3),
      paste(toJSON(setNames(list(option_label_1 = paste(option_value_1), option_label_2 = paste(option_value_2), option_label_3 = paste(option_value_3)), c(option_label_1, option_label_2, option_label_3)), auto_unbox = T)),
      ifelse(!is.na(option_value_2),
        paste(toJSON(setNames(list(option_label_1 = paste(option_value_1), option_label_2 = paste(option_value_2)), c(option_label_1, option_label_2)), auto_unbox = T)),
        paste(toJSON(setNames(list(option_label_1 = paste(option_value_1)), option_label_1), auto_unbox = T))
      )
    )
  )
</code>```

Title: Convert columns of R dataframe to JSON

Body:
I have this dataframe:

df <- data.frame(
  option_label_1 = c("thickness", "strength", "color"),
  option_value_1 = c("0.5 in", "2 lb" , "red"),
  option_label_2 = c("size", "color", "thickness"),
  option_value_2 = c("0.5 Inches x 7200 Feet", "blue" , "1 in"),
  option_label_3 = c("stretch", NA, NA),
  option_value_3 = c("wide", NA , NA)
  )

  option_label_1 option_value_1 option_label_2         option_value_2 option_label_3 option_value_3
1      thickness         0.5 in           size 0.5 Inches x 7200 Feet        stretch           wide
2       strength           2 lb          color                   blue           <NA>           <NA>
3          color            red      thickness                   1 in           <NA>           <NA>

I want this data frame:

  option_label_1 option_value_1 option_label_2         option_value_2 option_label_3 option_value_3
1      thickness         0.5 in           size 0.5 Inches x 7200 Feet        stretch           wide
2       strength           2 lb          color                   blue           <NA>           <NA>
3          color            red      thickness                   1 in           <NA>           <NA>
                                                                       json
1 {"thickness":"0.5 in","size":"0.5 Inches x 7200 Feet","stretch":"wide"}
2                                       {"strength":"2 lb","color":"blue"}
3                                        {"color":"red","thickness":"1 in"}

Essentially I want a JSON column added to the original df built off of the original columns using the option labels and option values. Please note I do not want a solution that converts the whole dataframe to JSON using toJSON. I have a much larger dataframe with other fields I do not want in JSON. I just want the option_labels and their respective option_values to be in JSON.

I have tried using list and paste functions nested in toJSON, but the "option_labels" are static and don't change accordingly in the resulting JSON column.

Thanks for your help!

Body:
This solution ultimately worked for me. Thanks to everyone who contributed.

df_1 <- df %>%
  rowwise() %>%
  dplyr::mutate(
    options_json = ifelse(!is.na(option_value_3),
      paste(toJSON(setNames(list(option_label_1 = paste(option_value_1), option_label_2 = paste(option_value_2), option_label_3 = paste(option_value_3)), c(option_label_1, option_label_2, option_label_3)), auto_unbox = T)),
      ifelse(!is.na(option_value_2),
        paste(toJSON(setNames(list(option_label_1 = paste(option_value_1), option_label_2 = paste(option_value_2)), c(option_label_1, option_label_2)), auto_unbox = T)),
        paste(toJSON(setNames(list(option_label_1 = paste(option_value_1)), option_label_1), auto_unbox = T))
      )
    )
  )


问:
Filter imaginary numbers
In this task, you will be filtering out complex elements from an array.

Create a (4,) array with values 3, 4.5, 3 + 5j and 0 using
  "np.array()". Save it to a variable array

Create a boolean condition real to retain only a real number using
  .isreal(array). (Note: .isreal(array) returns a Boolean value
  which is True if the number inside the array is a real number and
  False otherwise)

Now apply this Boolean condition i.e. real on array using Boolean
  indexing (explained in the topic) by array[real] and store it in
  variable real_array.

Similarly, create a Boolean condition imag to retain only complex
  numbers which you can do it using .iscomplex(array). This time create
  an array imag_array which contains only complex numbers using the
  Boolean condition array[imag] Test Cases: imag_array[0] == (3+5j)
  real_array[0] == (3 +0j) and real_array[1]== (4.5+0j)

My Code:

```<code># Code starts here
import numpy as np

# initialize array
array = np.array([3, 4.5, 3 + 5j, 0])

# boolean filter
real = array.isreal(array)
real_array = array[True, True, False, True]

# boolean filter
imag = array.iscomplex[array]
imag_array = array[False, False, True, False]

# Code ends here
</code>```

What is the error ??

答:
In case you came here looking for how to filter out imaginary numbers and get a list of the real values, this does that to array.

```<code>array[np.isreal(array)].real
</code>```

Title: Filter imaginary numbers

Body:
In this task, you will be filtering out complex elements from an array.

Create a (4,) array with values 3, 4.5, 3 + 5j and 0 using
  "np.array()". Save it to a variable array

Create a boolean condition real to retain only a real number using
  .isreal(array). (Note: .isreal(array) returns a Boolean value
  which is True if the number inside the array is a real number and
  False otherwise)

Now apply this Boolean condition i.e. real on array using Boolean
  indexing (explained in the topic) by array[real] and store it in
  variable real_array.

Similarly, create a Boolean condition imag to retain only complex
  numbers which you can do it using .iscomplex(array). This time create
  an array imag_array which contains only complex numbers using the
  Boolean condition array[imag] Test Cases: imag_array[0] == (3+5j)
  real_array[0] == (3 +0j) and real_array[1]== (4.5+0j)

My Code:

# Code starts here
import numpy as np

# initialize array
array = np.array([3, 4.5, 3 + 5j, 0])

# boolean filter
real = array.isreal(array)
real_array = array[True, True, False, True]

# boolean filter
imag = array.iscomplex[array]
imag_array = array[False, False, True, False]

# Code ends here

What is the error ??

Body:
In case you came here looking for how to filter out imaginary numbers and get a list of the real values, this does that to array.

array[np.isreal(array)].real


问:
Jackson : custom collection serialization to JSON
I am trying to json-serialize a class MyRootClass with a property that is a collection of elements of a second class MyClass:

```<code>public class MyRootClass {
   private List<MyInterface> list = new ArrayList<MyInterface>();
   // getter / setter
}

public class MyClass implements MyInterface {
   private String value = "test";
   // getter / setter
}
</code>```

The following code:

```<code>MyRootClass root = new MyRootClass();
root.getList().add(new MyClass());
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, root);
</code>```

Generates this JSON output:

```<code>{"list": [ {"value":"test"} ] }
</code>```

instead of what I need, every object in the collection serialized with a name:

```<code>{"list": [ {"myclass": {"value":"test"}} ] }
</code>```

Is there any way to achieve it using Jackson?  I thought about writing a custom serializer, but I've not found anything related to a collection of objects.

答:
You can use a helper object like this:</p>

```<code>public static class MyObject {
    public int i;
    public MyObject(int i) { this.i = i; }
    public MyObject() {}
}

@JsonDeserialize(contentAs=MyObject.class)
public static class MyHelperClass extends ArrayList<MyObject> {

}

@Test
public void testCollection() throws JsonGenerationException, JsonMappingException, IOException {
    final Collection<MyObject> l = new ArrayList<MyObject>();
    l.add(new MyObject(1));
    l.add(new MyObject(2));
    l.add(new MyObject(3));

    final ObjectMapper mapper = new ObjectMapper();

    final String s = mapper.writeValueAsString(l);
    final Collection<MyObject> back = mapper.readValue(s, MyHelperClass.class);

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to json-serialize a class MyRootClass with a property that is a collection of elements of a second class MyClass:

public class MyRootClass {
   private List<MyInterface> list = new ArrayList<MyInterface>();
   // getter / setter
}

public class MyClass implements MyInterface {
   private String value = "test";
   // getter / setter
}

The following code:

MyRootClass root = new MyRootClass();
root.getList().add(new MyClass());
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, root);

Generates this JSON output:

{"list": [ {"value":"test"} ] }

instead of what I need, every object in the collection serialized with a name:

{"list": [ {"myclass": {"value":"test"}} ] }

Is there any way to achieve it using Jackson?  I thought about writing a custom serializer, but I've not found anything related to a collection of objects.

Body:
You can use a helper object like this:

public static class MyObject {
    public int i;
    public MyObject(int i) { this.i = i; }
    public MyObject() {}
}

@JsonDeserialize(contentAs=MyObject.class)
public static class MyHelperClass extends ArrayList<MyObject> {

}

@Test
public void testCollection() throws JsonGenerationException, JsonMappingException, IOException {
    final Collection<MyObject> l = new ArrayList<MyObject>();
    l.add(new MyObject(1));
    l.add(new MyObject(2));
    l.add(new MyObject(3));

    final ObjectMapper mapper = new ObjectMapper();

    final String s = mapper.writeValueAsString(l);
    final Collection<MyObject> back = mapper.readValue(s, MyHelperClass.class);

}

ContentLicense: CC BY-SA 3.0


问:
“TypeError: null is not an object (Evaluating ‘RCTVideoInstance.Constants’)”
I’m having a problem where I get this error: “TypeError: null is not an object (Evaluating ‘RCTVideoInstance.Constants’)” for the react-native-video library. I am trying it on an android. What can I do to solve this problem? I have also tried the manual installation but it didn't work. Also I have noticed that I get a similar problem with react-native-image-crop-picker. I'll be very grateful if somebody can help me.</p>

答:
jcenter() was removed in favor of mavenCentral() in 0.65, add it back to allprojects.repositories and it'll magically work again in android/build.gradle.

Original Answer: https://github.com/react-native-video/react-native-video/issues/2468#issuecomment-911368291


问:
electron-builder, how to set node environmental variables
Node.js in windows system can be set environmental before the server is started, like this:

```<code>set NODE_ENV=production
</code>```

That NODE_ENV parameter can be using in node.js or electron by process.env.NODE_ENV.

But when I builder electron by electron-builder, like this:

```<code>electron-builder build --windows
</code>```

How do I set the environmental variables?

Update:

May be cannot pass a fixed environment variable to an executable by electron-builder.

Maybe you can only manually load an environment file, modify it when you package it, or preset the parameters to the dev state. When there is no state, it is production.

答:
I'm posting this in the hopes that it helps other people in my situation. I have three environments (development, staging, and production), and I wanted my Electron main process to be aware of which environment it was running on.

Now, for development it's quite easy to expose an environment variable to Electron inline using the CLI:

export NODE_ENV=development && electron desktop/main.js
```
<p>Then, Electron's main process can access this environment variable like so:</p>
<pre class="lang-js prettyprint-override"><code>const isDev = process.env.NODE_ENV === 'development';
</code>```

However, being able to distinguish between the staging and production environments was slightly trickier. My staging and production environments are both packaged and deployed using electron-builder, with package.json scripts like so:

```<code>"desktop-build": "webpack --config config/webpack/webpack.prod.js && electron-builder --config config/electron.config.js",
"desktop-build-staging": "webpack --config config/webpack/webpack.staging.js && electron-builder --config config/electron.config.js",
</code>```

NOTE: The webpack configs above expose configs to the renderer process (website), but not the main process.

So my solution to expose the environment to the Electron main process for staging and production was as follows:

Set NODE_ENV=staging or NODE_ENV=production to electron-builder via command line invocation:

# Production
export NODE_ENV=production && webpack --config config/webpack/webpack.prod.js && electron-builder --config config/electron.config.js

# Staging
export NODE_ENV=staging && webpack --config config/webpack/webpack.staging.js && electron-builder --config config/electron.config.js
```
</li>
<li><p>In my <code>electron.config.js</code> file (configs for <code>electron-builder</code>) use the <code>extraMetadata</code> parameter (docs) to inject a variable into my <code>package.json</code>:</p>
<pre class="lang-js prettyprint-override"><code>extraMetadata: {
    isProduction: Boolean(process.env.NODE_ENV === 'production'),
},
</code>```

Then you can access that from your Electron main process:

// This variable is injected into package.json by electron-builder via the extraMetadata field (specified in electron.config.js)
const {isProduction} = Boolean(require('./package.json'));
```

Body:
Node.js in windows system can be set environmental before the server is started, like this:

set NODE_ENV=production

That NODE_ENV parameter can be using in node.js or electron by process.env.NODE_ENV.

But when I builder electron by electron-builder, like this:

electron-builder build --windows

How do I set the environmental variables?

Update:

May be cannot pass a fixed environment variable to an executable by electron-builder.

Maybe you can only manually load an environment file, modify it when you package it, or preset the parameters to the dev state. When there is no state, it is production.

Body:
I'm posting this in the hopes that it helps other people in my situation. I have three environments (development, staging, and production), and I wanted my Electron main process to be aware of which environment it was running on.

Now, for development it's quite easy to expose an environment variable to Electron inline using the CLI:

export NODE_ENV=development && electron desktop/main.js

Then, Electron's main process can access this environment variable like so:

const isDev = process.env.NODE_ENV === 'development';

However, being able to distinguish between the staging and production environments was slightly trickier. My staging and production environments are both packaged and deployed using electron-builder, with package.json scripts like so:

"desktop-build": "webpack --config config/webpack/webpack.prod.js && electron-builder --config config/electron.config.js",
"desktop-build-staging": "webpack --config config/webpack/webpack.staging.js && electron-builder --config config/electron.config.js",

NOTE: The webpack configs above expose configs to the renderer process (website), but not the main process.

So my solution to expose the environment to the Electron main process for staging and production was as follows:

Set NODE_ENV=staging or NODE_ENV=production to electron-builder via command line invocation:

# Production
export NODE_ENV=production && webpack --config config/webpack/webpack.prod.js && electron-builder --config config/electron.config.js

# Staging
export NODE_ENV=staging && webpack --config config/webpack/webpack.staging.js && electron-builder --config config/electron.config.js

In my electron.config.js file (configs for electron-builder) use the extraMetadata parameter (docs) to inject a variable into my package.json:

extraMetadata: {
    isProduction: Boolean(process.env.NODE_ENV === 'production'),
},

Then you can access that from your Electron main process:

// This variable is injected into package.json by electron-builder via the extraMetadata field (specified in electron.config.js)
const {isProduction} = Boolean(require('./package.json'));


问:
Pandas str, int, and float columns concatenation
```<code>import pandas as pd
import numpy as np

text1 = ['22211', '1111', np.NaN]
Int1 = ['5555', np.NaN, '4444']
Float1 = [np.NaN, '3333.0', '231.0']
Text2 = ['222115555', '11113333', '4444231']

df = pd.DataFrame({'Text1': text1, 'Int1': Int1, 'Float1': Float1})
df_result = pd.DataFrame({'Text1': text1, 'Int1': Int1, 'Float1': Float1, 'Result': Text2})
</code>```

Need to concatenate cols with NaN and different types.

Need help understanding how to do this properly. I run into it over and over again and keep having issues.

I have tried to set each column as a 'str' when using pd.read_csv or pd.read_excel

Also tried this from other questions I have seen on here.

df = df.fillna("") (so astype('int') will work)

```<code>df['Float1'] = df['Float1'].astype('int').astype('str')
</code>```

Get this usually -- ValueError: invalid literal for int() with base 10: ''

The df['Results'] are usually keys in mapping dictionaries (more cols in df above) for other datasets, so getting them in str format is usually best--open to other opinions and spend hours on it.

Just looking for 'How to do this, conceptually and concretely', since I continually run into this when trying to analyze/manipulate data from our legacy excel/csv sheets.

答:
IIUC, you could cast to dtype str, join, then use str.replace to get rid of 'nan' values. Then perhaps use str.rstrip to get rid of the trailing ".0"s:

```<code>df['Result'] = df.astype(str).apply(''.join, axis=1).str.replace('nan','').str.rstrip('.0')
</code>```

Output:

```<code>   Text1  Int1  Float1     Result
0  22211  5555     NaN  222115555
1   1111   NaN  3333.0   11113333
2    NaN  4444   231.0    4444231
</code>```

Body:
import pandas as pd
import numpy as np

text1 = ['22211', '1111', np.NaN]
Int1 = ['5555', np.NaN, '4444']
Float1 = [np.NaN, '3333.0', '231.0']
Text2 = ['222115555', '11113333', '4444231']

df = pd.DataFrame({'Text1': text1, 'Int1': Int1, 'Float1': Float1})
df_result = pd.DataFrame({'Text1': text1, 'Int1': Int1, 'Float1': Float1, 'Result': Text2})

Need to concatenate cols with NaN and different types.

Need help understanding how to do this properly. I run into it over and over again and keep having issues.

I have tried to set each column as a 'str' when using pd.read_csv or pd.read_excel

Also tried this from other questions I have seen on here.

df = df.fillna("") (so astype('int') will work)

df['Float1'] = df['Float1'].astype('int').astype('str')

Get this usually -- ValueError: invalid literal for int() with base 10: ''

The df['Results'] are usually keys in mapping dictionaries (more cols in df above) for other datasets, so getting them in str format is usually best--open to other opinions and spend hours on it.

Just looking for 'How to do this, conceptually and concretely', since I continually run into this when trying to analyze/manipulate data from our legacy excel/csv sheets.

Body:
IIUC, you could cast to dtype str, join, then use str.replace to get rid of 'nan' values. Then perhaps use str.rstrip to get rid of the trailing ".0"s:

df['Result'] = df.astype(str).apply(''.join, axis=1).str.replace('nan','').str.rstrip('.0')

Output:

   Text1  Int1  Float1     Result
0  22211  5555     NaN  222115555
1   1111   NaN  3333.0   11113333
2    NaN  4444   231.0    4444231


问:
int issue in g++/mysql/redhat
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

```
int some_int;
printf("%i",some_int);
```

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

```
int some_int;
printf("%s",some_int);
```

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

```
int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);
```

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

答: If you don't initialize your variables, there's no guarantee of a default 0/NULL/whatever value. Some compilers MIGHT initialize it to 0 for you (IIRC, MSVC++ 6.0 would be kind enough to do so), and others might not. So don't rely on it. Never use a variable without first giving it some sort of sane value.</p>

OwnerDisplayName: hcmk

LastEditorDisplayName: FreeMemory

Title: int issue in g++/mysql/redhat

Body:
I haven't written C in quite some time and am writing an app using the MySQL C API, compiling in g++ on redhat.

So i start outputting some fields with printfs... using the oracle api, with PRO*C, which i used to use (on suse, years ago), i could select an int and output it as:

int some_int;
printf("%i",some_int);

I tried to do that with mysql ints and i got 8 random numbers displayed... i thought this was  a mysql api issue and some config issue with my server, and i wasted a few hours trying to fix it, but couldn't, and found that i could do:

int some_int;
printf("%s",some_int);

and it would print out the integer properly. Because i'm not doing computations on the values i am extracting, i thought this an okay solution.

UNTIL I TRIED TO COUNT SOME THINGS....

I did a simple:

int rowcount;
for([stmt]){
rowcount++;
}
printf("%i",rowcount);

i am getting an 8 digit random number again... i couldn't figure out what the deal is with ints on this machine.

then i realized that if i initialize the int to zero, then i get a proper number.

can someone please explain to me under what conditions you need to initialize int variables to zero? i don't recall doing this every time in my old codebase, and i didn't see it in the example that i was modeling my mysql_stmt code from...

is there something i'm missing? also, it's entirely possible i've forgotten this is required each time

thanks...

OwnerDisplayName: FreeMemory


问:
Windows batch: echo without new line
What is the Windows batch equivalent of the Linux shell command echo -n which suppresses the newline at the end of the output?

The idea is to write on the same line inside a loop.

答:
Using set and the /p parameter you can echo without newline:

```<code>C:\> echo Hello World
Hello World

C:\> echo|set /p="Hello World"
Hello World
C:\>
</code>```

Source

Title: Windows batch: echo without new line

Body:
Using set and the /p parameter you can echo without newline:

C:\> echo Hello World
Hello World

C:\> echo|set /p="Hello World"
Hello World
C:\>

Source


问:
React Text Fade in/out on click
I am using React. When a button is clicked, the text changes. I would like to have the current text fade out and then the new text fade in when the button is clicked.

I tried implementing solutions from other stack overflow posts, but to no avail.

Here is the codepen https://codepen.io/Jamece/pen/PoObBEN

```<code>const duration =1000;

//creating main React component with state being random numbers that will be an index for the quotes and color array.
class QuoteMachine extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      randomIndexQuote: 0,
      randomIndexColor: 0,
      fadeTransition: null,
      fadeState: "fade-in"
    };
    this.handleClick = this.handleClick.bind(this);
  }

  //upon click, a random number will be generates and state will be updated

  handleClick() {
    const timeout = setTimeout(() => {
      this.setState({
        randomIndexQuote: Math.floor(Math.random() * quotes.length),
        randomIndexColor: Math.floor(Math.random() * colors.length),
        fadeTransition: null,
        fadeState: 'fade-in'
      });
    }, duration);

    clearTimeout(this.state.fadeTransition);

    this.setState({
      fadeState: "fade-out",
      fadeTransition: timeout
    });
  }

  render() {
    //variables holding state index
    const quoteOutput = quotes[this.state.randomIndexQuote].quote;
    const authorOutput = quotes[this.state.randomIndexQuote].author;
    //variables for random color styles
    const textStyle = {
      color: colors[this.state.randomIndexColor],
      transition: "all 2s ease"
    };
    const backgroundStyle = {
      backgroundColor: colors[this.state.randomIndexColor],
      transition: "all 2s ease"
    };

    return (
      <div className="container-fluid px-0">
        <div
          className="d-flex justify-content-center align-items-center main"
          id="quote-box"
          style={backgroundStyle}
        >
          <div className="white-box">
            <div
              className={"fade-wrapper ${this.state.fadeState}"}
              style={{ transitionDuration: "${duration}ms" }}
            >
              <p id="text" style={textStyle} className="text-center">
                "{quoteOutput}"
              </p>
              <p id="author" style={textStyle} className="text-end">
                {authorOutput}
              </p>
            </div>
</code>```

CSS

```<code>.fade-wrapper {
  transition: opacity ease-in-out;
}
.fade-out {
  opacity: 0;
}
.fade-in {
  opacity: 1;
}
</code>```

Thank you.

答:
You could simply set the opacity to go from 1 to 0 and back to 1. You have everything ready with the color animation, all you need to do is add the opacity alongside the colors - (https://codepen.io/Brisingr_1/pen/NWwjWLx)</p>
```<code>this.state = {
  ...,
  opacity: 1
};

const timeout = setTimeout(() => {
  this.setState({
    ...,
    opacity: 1
  });
}, duration);

clearTimeout(this.state.fadeTransition);

this.setState({
  ...,
  opacity: 0,
});

const textStyle = {
  ...,
  opacity: this.state.opacity,
};
</code>```

Title: React Text Fade in/out on click

Body:
I am using React. When a button is clicked, the text changes. I would like to have the current text fade out and then the new text fade in when the button is clicked.

I tried implementing solutions from other stack overflow posts, but to no avail.

Here is the codepen https://codepen.io/Jamece/pen/PoObBEN

const duration =1000;

//creating main React component with state being random numbers that will be an index for the quotes and color array.
class QuoteMachine extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      randomIndexQuote: 0,
      randomIndexColor: 0,
      fadeTransition: null,
      fadeState: "fade-in"
    };
    this.handleClick = this.handleClick.bind(this);
  }

  //upon click, a random number will be generates and state will be updated

  handleClick() {
    const timeout = setTimeout(() => {
      this.setState({
        randomIndexQuote: Math.floor(Math.random() * quotes.length),
        randomIndexColor: Math.floor(Math.random() * colors.length),
        fadeTransition: null,
        fadeState: 'fade-in'
      });
    }, duration);

    clearTimeout(this.state.fadeTransition);

    this.setState({
      fadeState: "fade-out",
      fadeTransition: timeout
    });
  }

  render() {
    //variables holding state index
    const quoteOutput = quotes[this.state.randomIndexQuote].quote;
    const authorOutput = quotes[this.state.randomIndexQuote].author;
    //variables for random color styles
    const textStyle = {
      color: colors[this.state.randomIndexColor],
      transition: "all 2s ease"
    };
    const backgroundStyle = {
      backgroundColor: colors[this.state.randomIndexColor],
      transition: "all 2s ease"
    };

    return (

                "{quoteOutput}"

                {authorOutput}

CSS

.fade-wrapper {
  transition: opacity ease-in-out;
}
.fade-out {
  opacity: 0;
}
.fade-in {
  opacity: 1;
}

Thank you.

Body:
You could simply set the opacity to go from 1 to 0 and back to 1. You have everything ready with the color animation, all you need to do is add the opacity alongside the colors - (https://codepen.io/Brisingr_1/pen/NWwjWLx)

this.state = {
  ...,
  opacity: 1
};

const timeout = setTimeout(() => {
  this.setState({
    ...,
    opacity: 1
  });
}, duration);

clearTimeout(this.state.fadeTransition);

this.setState({
  ...,
  opacity: 0,
});

const textStyle = {
  ...,
  opacity: this.state.opacity,
};


问:
How should bug tracking and help tickets integrate?
I have a little experience with bug tracking systems such as FogBugz where help tickets are issues are (or can be) bugs, and I have some experience using a bug tracking system internally completely separate from a help center system.

My question is, in a company with an existing (home-grown) help center system where replacing it is not an option, how should a bug tracking system (probably Mantis) be integrated into the process?

Right now help tickets get put in for issues, questions, etc and they get assigned to the appropriate person (PC Tech, Help Desk staff, or if it's an application issue they can't solve in the help desk it gets assigned to a developer). A user can put a request for small modifications or fixes to an application in a help ticket and the developer it gets assigned to will make the change at some point, apply their time to that ticket, and then close the ticket when it goes to production.

We don't currently have a bug tracking system, so I'm looking into the best way to integrate one. Should we just take the help tickets and put it into the bug tracking system if it's a bug (or issue or feature request) and then close the ticket if it's not an emergency fix? We probably don't want to expose the bug tracking system to anyone else as they wouldn't know what to put in the help center system and what to put in the bug tracker... right?

Any thoughts? Suggestions? Tips? Advice? To-dos? Not to-dos? etc...

答:
For anyone in 2022 (and beyond) looking to integrate a help desk system and bug tracker, DoneDone does this well.

We use a DoneDone mailbox for general customer support (both via our support email address and the contact form on our website). It lets you have private discussion on emails, along with allowing you to assign, prioritize, tag, and create/change statuses on them (e.g. "Open", "In Progress", etc.)

We use DoneDone projects to manage internal bugs/issues/tasks.

DoneDone lets you connect support emails (the helpdesk part) to internal tasks (the bug tracking part) as well. So, if your company has distinct support and client-facing people while also having internal devs and you want to separate their work, you can create any number of subtasks from an incoming conversation.

Even if your company isn't that stratified, it's nice to be able to create bugs with their own workflows separate from a helpdesk ticket (which has its own workflow).

More info at https://www.donedone.com

OwnerDisplayName: Max Schmeling


问:
Android Studio - showing new activity over other apps results in a blackscreen
I'm trying to develop an android app for the SDK version 30 that (when a button is clicked) starts listening to what apps are opened on the phone. If it detects the user opening Whatsapp, it is supposed to show a LockScreen activity over Whatsapp that makes you answer a math question before being able to use Whatsapp.

I know this can be done as their are apps like QualityTime or Forest that have similar features to restrict you from using certain apps, but I am a newbie when it comes to programming (probably obvious from my code) and feel totally stuck.

I have already figured out how to detect what app the user opened in the last second with code from stack overflow:

```<code>public String getCurrentApp() {
    String topPackageName = "None";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService("usagestats");
        long time = System.currentTimeMillis();
        List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1, time);
        // Sort the stats by the last time used
        if (stats != null) {
            SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
            for (UsageStats usageStats : stats) {
                mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
            }
            if (!mySortedMap.isEmpty())
            {
                topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
            }
        }
    }
    return topPackageName;
}
</code>```

I have another function that is started when the user clicks the button in my app to "activate" the listening process. This function keeps checking if the user opens Whatsapp and is then supposed to display the Lockscreen activity on top:

```<code>public void startListening(View view)
{
    System.out.println("Lock activated.");
    while (activated) {
        String currentlyRunningApp;
        currentlyRunningApp = getCurrentApp();
        if (currentlyRunningApp.equals("com.whatsapp"))
        {
            System.out.println("Whatsapp detected. Showing Lockscreen...");
            Intent i = new Intent(this,LockScreen.class);
            startActivity(i);
        }

        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
</code>```

(All of the code I have shown is in my MainActivity btw.)

I have the following permissions granted to my app:

android.permission.PACKAGE_USAGE_STATS (for the getCurrentApp() function)

android.permission.SYSTEM_ALERT_WINDOW (as suggested here)

android.permission.ACTION_MANAGE_OVERLAY_PERMISSION (although I am not sure I even need this one)

My problem is, that instead of showing the Lockscreen activity I created, it only shows a blackscreen for the user. The Lockscreen activity itself works fine if I let the user open it through a button on the mainActivity, so the issue seems to really be that I can not properly show an activity if my app is running in the background and I want to display it on top of Whatsapp.

I have tried to look through similar questions, but all of the posts on here with similar use cases seem to be very old and outdated (i.e. this or this), as the newer versions seem to have way tighter security restrictions.

I also tried to do it with a screen overlay instead of an activity (using this source), but this doesn't even give me a blackscreen - just does nothing...

I am also aware that there are probably better ways to program the whole "listening and checking for whatsapp" part - i.e. with a service instead of a while-loop or something, but I only found out about services while researching this problem and I'd like to fix the blackscreen issue first.

答:
After lots of trial and error I figured out that the issues was indeed caused by a missing permission, but one that I could not find on any stack overflow answer related to black screen problems. On top of that, I believe it's an issue that only occurred because I used a Xiaomi device for testing.

There are currently two separate permissions for displaying screens over other apps that you will need to grant:

Display over other apps, also called Display pop-up window. This is the android.permission.ACTION_MANAGE_OVERLAY_PERMISSION that I wasn't sure was even needed. So to emphasize, I definetly do need this permission.

Display pop-up windows while running in the background. This is the permission I was missing.

After I allowed them both (which you can do under Settings > Apps > Manage Apps > Your App > Other Permissions) everything worked fine.

To direct the user directly to the settings menu where they can allow these permissions, I used the code from this stack overflow answer. This is also where I got the info that it's a xiaomi-specific "issue".

Body:
I'm trying to develop an android app for the SDK version 30 that (when a button is clicked) starts listening to what apps are opened on the phone. If it detects the user opening Whatsapp, it is supposed to show a LockScreen activity over Whatsapp that makes you answer a math question before being able to use Whatsapp.

I know this can be done as their are apps like QualityTime or Forest that have similar features to restrict you from using certain apps, but I am a newbie when it comes to programming (probably obvious from my code) and feel totally stuck.

I have already figured out how to detect what app the user opened in the last second with code from stack overflow:

public String getCurrentApp() {
    String topPackageName = "None";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService("usagestats");
        long time = System.currentTimeMillis();
        List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1, time);
        // Sort the stats by the last time used
        if (stats != null) {
            SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
            for (UsageStats usageStats : stats) {
                mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
            }
            if (!mySortedMap.isEmpty())
            {
                topPackageName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
            }
        }
    }
    return topPackageName;
}

I have another function that is started when the user clicks the button in my app to "activate" the listening process. This function keeps checking if the user opens Whatsapp and is then supposed to display the Lockscreen activity on top:

public void startListening(View view)
{
    System.out.println("Lock activated.");
    while (activated) {
        String currentlyRunningApp;
        currentlyRunningApp = getCurrentApp();
        if (currentlyRunningApp.equals("com.whatsapp"))
        {
            System.out.println("Whatsapp detected. Showing Lockscreen...");
            Intent i = new Intent(this,LockScreen.class);
            startActivity(i);
        }

        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

(All of the code I have shown is in my MainActivity btw.)

I have the following permissions granted to my app:

android.permission.PACKAGE_USAGE_STATS (for the getCurrentApp() function)

android.permission.SYSTEM_ALERT_WINDOW (as suggested here)

android.permission.ACTION_MANAGE_OVERLAY_PERMISSION (although I am not sure I even need this one)

My problem is, that instead of showing the Lockscreen activity I created, it only shows a blackscreen for the user. The Lockscreen activity itself works fine if I let the user open it through a button on the mainActivity, so the issue seems to really be that I can not properly show an activity if my app is running in the background and I want to display it on top of Whatsapp.

I have tried to look through similar questions, but all of the posts on here with similar use cases seem to be very old and outdated (i.e. this or this), as the newer versions seem to have way tighter security restrictions.

I also tried to do it with a screen overlay instead of an activity (using this source), but this doesn't even give me a blackscreen - just does nothing...

I am also aware that there are probably better ways to program the whole "listening and checking for whatsapp" part - i.e. with a service instead of a while-loop or something, but I only found out about services while researching this problem and I'd like to fix the blackscreen issue first.


问:
Run function every x seconds - dearpygui
I have a window application in which I am trying to refresh a table every x seconds after running my function. However I could not find any suitable method to rerun the function within the event loop of the app. This is my code and the function I'm trying to rerun is FLAS(I'm returning a list of objects).</p>
```<code>flights = FLAS()

with dpg.window(width=785, height=600, no_collapse=True, no_move=True, no_title_bar=True, no_resize=True):
    with dpg.table(header_row=True, policy=dpg.mvTable_SizingFixedFit, row_background=True, reorderable=True,
                resizable=False, no_host_extendX=False, hideable=True,
                borders_innerV=True, delay_search=True, borders_outerV=True, borders_innerH=True,
                borders_outerH=True):
        dpg.add_table_column(label="Callsign", width_fixed=True)
        dpg.add_table_column(label="FIX", width_fixed=True)
        dpg.add_table_column(label="Exit FIR", width_fixed=True)
        dpg.add_table_column(label="Next FIR", width_fixed=True)
        dpg.add_table_column(label="Entry FL", width_fixed=True)
        dpg.add_table_column(label="Exit FL", width_fixed=True)

        print(len(flights))
        if len(flights) == 0:
            flights.append(Flight("No flights in range", 000000, "XXX", 0, "XXXX", "XXXX",0,0,0,0))
        for flight in flights:
            with dpg.table_row():
                dpg.add_text(flight.callsign)
                dpg.add_text(flight.fix)
                dpg.add_text(flight.cFIR)
                dpg.add_text(flight.xFIR)
                dpg.add_text(flight.efl)
                dpg.add_text(flight.xfl)
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()
</code>```

答:
You can easy do it within the render loop:

https://dearpygui.readthedocs.io/en/latest/documentation/render-loop.html

The only thing you need now is to define a timer class.

The otherway would be to work with the Thread module.

DPG is not that popular so far, to ask on Stackoverflow. A better source to ask is on github or on the DPG Discord Server ( you will find some examples in the #support channel how to build a timer class and how to use it.

Body:
I have a window application in which I am trying to refresh a table every x seconds after running my function. However I could not find any suitable method to rerun the function within the event loop of the app. This is my code and the function I'm trying to rerun is FLAS(I'm returning a list of objects).

flights = FLAS()

with dpg.window(width=785, height=600, no_collapse=True, no_move=True, no_title_bar=True, no_resize=True):
    with dpg.table(header_row=True, policy=dpg.mvTable_SizingFixedFit, row_background=True, reorderable=True,
                resizable=False, no_host_extendX=False, hideable=True,
                borders_innerV=True, delay_search=True, borders_outerV=True, borders_innerH=True,
                borders_outerH=True):
        dpg.add_table_column(label="Callsign", width_fixed=True)
        dpg.add_table_column(label="FIX", width_fixed=True)
        dpg.add_table_column(label="Exit FIR", width_fixed=True)
        dpg.add_table_column(label="Next FIR", width_fixed=True)
        dpg.add_table_column(label="Entry FL", width_fixed=True)
        dpg.add_table_column(label="Exit FL", width_fixed=True)

        print(len(flights))
        if len(flights) == 0:
            flights.append(Flight("No flights in range", 000000, "XXX", 0, "XXXX", "XXXX",0,0,0,0))
        for flight in flights:
            with dpg.table_row():
                dpg.add_text(flight.callsign)
                dpg.add_text(flight.fix)
                dpg.add_text(flight.cFIR)
                dpg.add_text(flight.xFIR)
                dpg.add_text(flight.efl)
                dpg.add_text(flight.xfl)
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()


问:
How do I add canvas drawings to an array and determine if an array value is an image or canvas drawing?
I need an array which can include canvas drawings and/or images.

Drawing example below:

```<code>function drawCircle() {
ctx.beginPath();
ctx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
ctx.fillStyle = 'black;
ctx.fill();
ctx.strokeStyle = 'orange';
ctx.stroke();
ctx.closePath();
}
</code>```

Image example below:

```<code>const LIFE_IMG=new Image();
LIFE_IMG.src="images/life.png"
</code>```

Array;

```<code>let LIFE_ARRAY=[LIFE_IMG,LIFE_IMG,LIFE_IMG];
</code>```

Draw:

```<code>function drawLife(imgY2,imgWidth,imgHeight){
LIFE_ARRAY.forEach(function(item, index) {

let offsetY,imgX,imgY;
offsetY=(imgHeight+5)*(index+1)
imgX=(SCOREBOARD_WIDTH/2)-(imgWidth/2)
imgY=imgY2
    }
ctx.drawImage(item, imgX, imgY+offsetY, imgWidth, imgHeight);
  })
}
</code>```

I need to be able to

push the canvas drawing to the array

determine if the array value is an image or canvas drawing

draw the canvas drawing or the image

Part 2 was answered on an old stack overflow thread with:

```<code>function isImage(i) {return i instanceof HTMLImageElement;}
</code>```

but I can't figure out how to tie it into my code.

Any help would be greatly appreciated!

答:
Usually you just have one on-screen <canvas> element. So your sample code:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let Life = {
  x: 100,
  y: 100,
  radius: 50
};

function drawCircle() {
  ctx.beginPath();
  ctx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
  ctx.fillStyle = 'black';
  ctx.fill();
  ctx.strokeStyle = 'orange';
  ctx.stroke();
  ctx.closePath();
}

drawCircle();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas></code>```

draws a circle on the on-screen canvas' context. This is just a drawing operation though, so there is no reference to it making it sort of an object. In the end it's just pixel data somewhere on the canvas.

Although I don't see an use-case, what you want to achieve can be done of course. The trick here is to create individual off-screen canvases for all canvas drawings you want to store in the array.

A <canvas> element can be created at runtime using:

```<code>document.createElement('canvas')
</code>```

If we modify your drawCircle() function a little so it draws to an off-screen canvas and returns it, you can even call this function from within your array to push it's reference into.

```<code>function drawCircle() {
  let tempCanvas=document.createElement('canvas');
  let tempCtx=tempCanvas.getContext('2d');
    tempCtx.beginPath();
    tempCtx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
    tempCtx.fillStyle = 'black';
    tempCtx.fill();
    tempCtx.strokeStyle = 'orange';
    tempCtx.stroke();
    tempCtx.closePath();
  return tempCanvas;
}
</code>```

As you already figured yourself an image is an instance of HTMLImageElement. Likewise a canvas is of HTMLCanvasElement. This can be used in the forEach loop to distinct one from the other.

Here's an example:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let Life = {
    x: 100,
    y: 100,
    radius: 50
};

function drawCircle() {
    let tempCanvas = document.createElement('canvas');
    let tempCtx = tempCanvas.getContext('2d');
    tempCtx.beginPath();
    tempCtx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
    tempCtx.fillStyle = 'black';
    tempCtx.fill();
    tempCtx.strokeStyle = 'orange';
    tempCtx.stroke();
    tempCtx.closePath();
    return tempCanvas;
}

drawCircle();

const LIFE_IMG = new Image();
LIFE_IMG.src = "images/life.png";

let LIFE_ARRAY = [LIFE_IMG, drawCircle(), LIFE_IMG];

LIFE_ARRAY.forEach(function(item, index) {
    if (item instanceof HTMLImageElement) {
        console.log("an Image");
    }
    if (item instanceof HTMLCanvasElement) {
        console.log("a Canvas");
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <canvas id="canvas"></canvas></code>```

Body:
I need an array which can include canvas drawings and/or images.

Drawing example below:

function drawCircle() {
ctx.beginPath();
ctx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
ctx.fillStyle = 'black;
ctx.fill();
ctx.strokeStyle = 'orange';
ctx.stroke();
ctx.closePath();
}

Image example below:

const LIFE_IMG=new Image();
LIFE_IMG.src="images/life.png"

Array;

let LIFE_ARRAY=[LIFE_IMG,LIFE_IMG,LIFE_IMG];

Draw:

function drawLife(imgY2,imgWidth,imgHeight){
LIFE_ARRAY.forEach(function(item, index) {

let offsetY,imgX,imgY;
offsetY=(imgHeight+5)*(index+1)
imgX=(SCOREBOARD_WIDTH/2)-(imgWidth/2)
imgY=imgY2
    }
ctx.drawImage(item, imgX, imgY+offsetY, imgWidth, imgHeight);
  })
}

I need to be able to

push the canvas drawing to the array

determine if the array value is an image or canvas drawing

draw the canvas drawing or the image

Part 2 was answered on an old stack overflow thread with:

function isImage(i) {return i instanceof HTMLImageElement;}

but I can't figure out how to tie it into my code.

Any help would be greatly appreciated!

Body:
Usually you just have one on-screen <canvas> element. So your sample code:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let Life = {
  x: 100,
  y: 100,
  radius: 50
};

function drawCircle() {
  ctx.beginPath();
  ctx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
  ctx.fillStyle = 'black';
  ctx.fill();
  ctx.strokeStyle = 'orange';
  ctx.stroke();
  ctx.closePath();
}

drawCircle();

<canvas id="canvas"></canvas>

draws a circle on the on-screen canvas' context. This is just a drawing operation though, so there is no reference to it making it sort of an object. In the end it's just pixel data somewhere on the canvas.

Although I don't see an use-case, what you want to achieve can be done of course. The trick here is to create individual off-screen canvases for all canvas drawings you want to store in the array.

A <canvas> element can be created at runtime using:

document.createElement('canvas')

If we modify your drawCircle() function a little so it draws to an off-screen canvas and returns it, you can even call this function from within your array to push it's reference into.

function drawCircle() {
  let tempCanvas=document.createElement('canvas');
  let tempCtx=tempCanvas.getContext('2d');
    tempCtx.beginPath();
    tempCtx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
    tempCtx.fillStyle = 'black';
    tempCtx.fill();
    tempCtx.strokeStyle = 'orange';
    tempCtx.stroke();
    tempCtx.closePath();
  return tempCanvas;
}

As you already figured yourself an image is an instance of HTMLImageElement. Likewise a canvas is of HTMLCanvasElement. This can be used in the forEach loop to distinct one from the other.

Here's an example:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let Life = {
    x: 100,
    y: 100,
    radius: 50
};

function drawCircle() {
    let tempCanvas = document.createElement('canvas');
    let tempCtx = tempCanvas.getContext('2d');
    tempCtx.beginPath();
    tempCtx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
    tempCtx.fillStyle = 'black';
    tempCtx.fill();
    tempCtx.strokeStyle = 'orange';
    tempCtx.stroke();
    tempCtx.closePath();
    return tempCanvas;
}

drawCircle();

const LIFE_IMG = new Image();
LIFE_IMG.src = "images/life.png";

let LIFE_ARRAY = [LIFE_IMG, drawCircle(), LIFE_IMG];

LIFE_ARRAY.forEach(function(item, index) {
    if (item instanceof HTMLImageElement) {
        console.log("an Image");
    }
    if (item instanceof HTMLCanvasElement) {
        console.log("a Canvas");
    }
});

 <canvas id="canvas"></canvas>


问:
Using secureTextInput with multiple TextInput fields causes UI problems on iOS
I have two secureTextEntry fields, one for password and one for retype-password.  Testing this on iOS emulator I get the jumping behaviour demonstrated in this video.

If I turn off secureTextEntry in just the second password field, the jumping behaviour stops, and everything works normally.

Has anybody else seen this or know why it's happening?

Relevant code snippets below:

```<code><TextInput
  placeholder="Password"
  value={passwordVal}
  onChangeText={setPasswordValue}
  secureTextEntry={true}
/>
Password
<TextInput/>

<TextInput
  placeholder="Retype Password"
  value={retypeVal}
  onChangeText={setRetypeVal}
  secureTextEntry={true}
/>
Retype Password
<TextInput/>

</code>```

答: I don't think that is related to secureTextEntry. Maybe you are using some custom third-party components that they are causing this problem.

Body:
I have two secureTextEntry fields, one for password and one for retype-password.  Testing this on iOS emulator I get the jumping behaviour demonstrated in this video.

If I turn off secureTextEntry in just the second password field, the jumping behaviour stops, and everything works normally.

Has anybody else seen this or know why it's happening?

Relevant code snippets below:

<TextInput
  placeholder="Password"
  value={passwordVal}
  onChangeText={setPasswordValue}
  secureTextEntry={true}
/>
Password
<TextInput/>

<TextInput
  placeholder="Retype Password"
  value={retypeVal}
  onChangeText={setRetypeVal}
  secureTextEntry={true}
/>
Retype Password
<TextInput/>


问:
SQL query to get multiple records into multiple columns
I have a CSV that I am trying to create and pull data for. The CSV template has multiple columns for Status (IE: Status1, Status2, Status3). Some locations have only one status and some can have up to 3. I am trying to find a way in SQL that I can have 3 status columns and populate those based on the number of records for a location. For example, a location called John's Office could have a status of Ready. Another location called IT Workroom may have 3 statuses, Ready, In-Repair, and In-Use. The columns in the SQL query would look something like this:

```<code>Location          Status1         Status2        Status3
----------------------------------------------------------
John's Office     Ready
IT Workroom       Ready           In-Repair       In-Use
</code>```

The column names Status1, Status2, etc would be column names that are just made up. I would want to populate Status1 with the first record that returns, regardless of the actual status name. So Status1 would always be populated. Status2 will only be populated if their is a second status.

In the original table that holds this information, it looks like this:

```<code>LocationName           StatusName
------------------------------------
IT Workroom            In-Repair
IT Workroom            Ready
John's Office          Ready
IT Workroom            In-Use
</code>```

I have tried PIVOT, but I realized that this is not what I need as I am not technically aggregating the data.

答:
you can use row number with max case when like this:</p>
```<code>select LocationName, MAX(CASE WHEN RowNum = 1 THEN StatusName ELSE NULL END) Status1
    , MAX(CASE WHEN RowNum = 2 THEN StatusName ELSE NULL END) Status2
    , MAX(CASE WHEN RowNum = 3 THEN StatusName ELSE NULL END) Status3
from (
    select *, ROW_NUMBER() OVER (PARTITION BY LocationName ORDER BY LocationName, StatusName) RowNum
    from #data
) Recs
group by LocationName
</code>```

Body:
I have a CSV that I am trying to create and pull data for. The CSV template has multiple columns for Status (IE: Status1, Status2, Status3). Some locations have only one status and some can have up to 3. I am trying to find a way in SQL that I can have 3 status columns and populate those based on the number of records for a location. For example, a location called John's Office could have a status of Ready. Another location called IT Workroom may have 3 statuses, Ready, In-Repair, and In-Use. The columns in the SQL query would look something like this:

Location          Status1         Status2        Status3
----------------------------------------------------------
John's Office     Ready
IT Workroom       Ready           In-Repair       In-Use

The column names Status1, Status2, etc would be column names that are just made up. I would want to populate Status1 with the first record that returns, regardless of the actual status name. So Status1 would always be populated. Status2 will only be populated if their is a second status.

In the original table that holds this information, it looks like this:

LocationName           StatusName
------------------------------------
IT Workroom            In-Repair
IT Workroom            Ready
John's Office          Ready
IT Workroom            In-Use

I have tried PIVOT, but I realized that this is not what I need as I am not technically aggregating the data.

Body:
you can use row number with max case when like this:

select LocationName, MAX(CASE WHEN RowNum = 1 THEN StatusName ELSE NULL END) Status1
    , MAX(CASE WHEN RowNum = 2 THEN StatusName ELSE NULL END) Status2
    , MAX(CASE WHEN RowNum = 3 THEN StatusName ELSE NULL END) Status3
from (
    select *, ROW_NUMBER() OVER (PARTITION BY LocationName ORDER BY LocationName, StatusName) RowNum
    from #data
) Recs
group by LocationName


答: Here is an example (probably inefficient) algorithm in Python (using strings instead of files) https://colab.research.google.com/drive/1bUnFXJg0m6FvXRkPybUqWux_reaJRt1c?usp=sharing</p>

Title: How can I print a grep result with the matched word?

Body:
I have two files, "file A":

Adygei
Albanian
Armenia_C
Armenia_Caucasus
Armenia_EBA
Armenia_LBA
Armenia_MBA
Armenian.DG
Austria_EN_HG_LBK
Austria_EN_LBK

And "fileB":

HG01880.SG Aygei_o1.SG
HG01988.SG Adygei_o2.SG
HG02419.SG Albanian_o2.SG
HG01879.SG Albanian.SG
HG01882.SG Armenia_C.SG
HG01883.SG Armenia_C.SG
HG01885.SG Armenia_EBA.SG
HG01886.SG Armenia_EBA.SG
HG01889.SG Armenia_LBA.SG
HG01890.SG Armenia_MBA.SG

What I want at the end is create a new columne (doesn't matter the position of the column) with the grep word with the word that matched. Like This:

HG01880.SG Aygei_o1.SG Adygei
HG01988.SG Adygei_o2.SG Adygei
HG02419.SG Albanian_o2.SG Albanian
HG01879.SG Albanian.SG Albanian
HG01882.SG Armenia_C.SG Armenia_C
HG01883.SG Armenia_C.SG Armenia_C
HG01885.SG Armenia_EBA.SG Armenia_EBA
HG01886.SG Armenia_EBA.SG Armenia_EBA
HG01889.SG Armenia_LBA.SG Armenia_LBA
HG01890.SG Armenia_MBA.SG Armenia_MBA

What I used to match both files in bash is grep -wFf fileA fileB > newfileA_B.txt. This can be both in python or bash


问:
How to pass type from parent to child component?
I'm trying to create an abstract table component which will use the MatTable component. The abstract table will be used as a child element and I want to pass the custom interface (which acts like type) from parent to that child.

So far I decided to pass data and table settings through one object like this:

//inside the parent component

<app-abstract-table [tableProperties]="tableProperties"></app-abstract-table>
```
<p>The <code>tableProperties</code> object is created based on the following interface:</p>
<pre class="lang-js prettyprint-override"><code>export interface TableProperties {
    columnsWithCaptions?: any[];
    dataSource?: any[];
}
</code>```

And in app-abstract-table I have a field which holds data for the table:

dataSource: MatTableDataSource<Fruit> = new MatTableDataSource<Fruit>();

and its generic type is Fruit.

I'd like to pass this type somehow from parent so the whole abstract table component will be completely reusable. Is this even achievable at all? Or should I just put any as a generic and forget the problem?

答:
I came across a similar requirement today and I did not find many resources for this, so I tried the way of C# generics and it worked. So I am posting the findings below with a small example.

So to make this work, we need to add the generic type holder to the child component like below, so that we can pass the type from the parent:

```<code>
    import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.css']
    })
    export class ChildComponent<TType> {
      @Input() genericType?: TType;
      @Output() selected: EventEmitter<TType> = new EventEmitter<TType>();

      onClick(): void {
        if (this.genericType) {
          this.selected.emit(this.genericType);
        }
      }
    }

</code>```

then from the parent, we need to pass the desired type of the object. Here I am passing the number and string for the sample.

```<code>
    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent implements OnInit {
      genericTypeNumber: number= 2022;
      genericTypeString: string= "Hello World!!";
      constructor() { }

      ngOnInit(): void {
      }

      onSelectedNumber(numberType: number){
        console.log(numberType);
      }

      onSelectedString(stringType: string){
        console.log(stringType);
      }

    }

</code>```

And in the parent HTML, do the normal assignment of the property to the child component :

```<code>
    <app-child [genericType]="genericTypeNumber" (selected)="onSelectedNumber($event)"></app-child>
    <app-child [genericType]="genericTypeString" (selected)="onSelectedString($event)"></app-child>

</code>```

This will ensure type safety as well.
If you require a generic type inside an existing interface, then you could do something like the below.

```<code>
    export interface IGenericModel<TCustomType> {
        id: number;
        customValue: TCustomType;
    }

</code>```

and the child component will be like this:

```<code>
    import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
    import { IGenericModel } from './genericModel';

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.css']
    })
    export class ChildComponent<TType> {
      @Input() genericType?: IGenericModel<TType>;
      @Output() selected: EventEmitter<IGenericModel<TType>> = new EventEmitter<IGenericModel<TType>>();

      onClick(): void {
        if (this.genericType) {
          this.selected.emit(this.genericType);
        }
      }
    }

</code>```

Body:
I'm trying to create an abstract table component which will use the MatTable component. The abstract table will be used as a child element and I want to pass the custom interface (which acts like type) from parent to that child.

So far I decided to pass data and table settings through one object like this:

//inside the parent component

<app-abstract-table [tableProperties]="tableProperties"></app-abstract-table>

The tableProperties object is created based on the following interface:

export interface TableProperties {
    columnsWithCaptions?: any[];
    dataSource?: any[];
}

And in app-abstract-table I have a field which holds data for the table:

dataSource: MatTableDataSource<Fruit> = new MatTableDataSource<Fruit>();

and its generic type is Fruit.

I'd like to pass this type somehow from parent so the whole abstract table component will be completely reusable. Is this even achievable at all? Or should I just put any as a generic and forget the problem?

Body:
I came across a similar requirement today and I did not find many resources for this, so I tried the way of C# generics and it worked. So I am posting the findings below with a small example.

So to make this work, we need to add the generic type holder to the child component like below, so that we can pass the type from the parent:

    import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.css']
    })
    export class ChildComponent<TType> {
      @Input() genericType?: TType;
      @Output() selected: EventEmitter<TType> = new EventEmitter<TType>();

      onClick(): void {
        if (this.genericType) {
          this.selected.emit(this.genericType);
        }
      }
    }

then from the parent, we need to pass the desired type of the object. Here I am passing the number and string for the sample.

    import { Component, OnInit } from '@angular/core';

    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.css']
    })
    export class ParentComponent implements OnInit {
      genericTypeNumber: number= 2022;
      genericTypeString: string= "Hello World!!";
      constructor() { }

      ngOnInit(): void {
      }

      onSelectedNumber(numberType: number){
        console.log(numberType);
      }

      onSelectedString(stringType: string){
        console.log(stringType);
      }

    }

And in the parent HTML, do the normal assignment of the property to the child component :

    <app-child [genericType]="genericTypeNumber" (selected)="onSelectedNumber($event)"></app-child>
    <app-child [genericType]="genericTypeString" (selected)="onSelectedString($event)"></app-child>

This will ensure type safety as well.
If you require a generic type inside an existing interface, then you could do something like the below.

    export interface IGenericModel<TCustomType> {
        id: number;
        customValue: TCustomType;
    }

and the child component will be like this:

    import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';
    import { IGenericModel } from './genericModel';

    @Component({
      selector: 'app-child',
      templateUrl: './child.component.html',
      styleUrls: ['./child.component.css']
    })
    export class ChildComponent<TType> {
      @Input() genericType?: IGenericModel<TType>;
      @Output() selected: EventEmitter<IGenericModel<TType>> = new EventEmitter<IGenericModel<TType>>();

      onClick(): void {
        if (this.genericType) {
          this.selected.emit(this.genericType);
        }
      }
    }


问:
SPFarm.Local is return null
SPFarm.Local is return null

I have googled.

x64 and x86 problem - No

Access issue - No

Additional
1. Database server is up
2. Sites are opening
3. CA is opening

The account is 'System Account' under which the code is running. Always worked before. Now suddenly it started returning null.

Any ideas?

Thanks in advance.

答:
Quote from here:

SPFarm.Local = null.
  SPFarm.Local wants to create a connection to the
  configuration database. In order to do so, you'll need to have
  permissions on the configuration database. Usually the service account
  and the application pool accounts can read the configuration database.
  If you don't have the right to read the configuration database,
  SPFarm.Local will be null!

Title: SPFarm.Local is return null


问:
Error in order(desc(var3), .by_group = TRUE) : argument lengths differ
I get this error (Error in order(desc(var3), .by_group = TRUE) :
argument lengths differ) when I ran the code below. Any quick tip on how to solve this error?

```<code>df_final <- df_merged %>%
  group_by(var1, var2) %>%
  arrange(desc(var3), .by_group = TRUE ) %>%
  slice(1L) %>%
  ungroup()
</code>```

答:
Try this:</p>
```<code>df_final <- df_merged %>%
  arrange(var1, var2, desc(var3)) %>%
 # group_by(whatever you want to group) %>%
  slice(1L) # %>%
 # ungroup()
</code>```

Body:
I get this error (Error in order(desc(var3), .by_group = TRUE) :
argument lengths differ) when I ran the code below. Any quick tip on how to solve this error?

df_final <- df_merged %>%
  group_by(var1, var2) %>%
  arrange(desc(var3), .by_group = TRUE ) %>%
  slice(1L) %>%
  ungroup()

Body:
Try this:

df_final <- df_merged %>%
  arrange(var1, var2, desc(var3)) %>%
 # group_by(whatever you want to group) %>%
  slice(1L) # %>%
 # ungroup()


问:
npm ERR! code ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC
I tried to create React app in VS Code by using below code. I got this error "npm ERR! code ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC"
Node version: v14.18.1
npm version: 8.1.0
OS: windows 10
VS code: 1.16.0

PS D:\React-Projects> npx create-react-app first-app

Creating a new React app in D:\React-Projects\first-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

npm ERR! code ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC
npm ERR! 10796:error:1408F119:SSL routines:ssl3_get_record:decryption failed or bad record mac:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:677:
npm ERR!

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\bizwe\AppData\Local\npm-cache_logs\2021-10-16T08_13_20_686Z-debug.log

Aborting installation.
npm install --save --save-exact --loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file... node_modules
Deleting generated file... package.json
Deleting first-app/ from D:\React-Projects
Done.

I tried all solutions given in stack overflow, but none of them is worked, Anybody help me please.

答:
I had the same problem and I solved it by deleting my SSH key from Github (in my case) and from my machine, then I generated a new SSH key.

Adding a new SSH key to your GitHub account


问:
Google Sheets most frequent and just one value
I'm trying to count the number of most frequent text in a column, I have this formula that I used before in excel...

```<code>=INDEX(E9:E18,MODE(IF((E9:E18<>"")*ISNA(MATCH(E9:E18,$B$1:$B1,0)),MATCH(E9:E18,E9:E18,0))))
</code>```

This works, but when I get some repited value shows #N/A
Here is an capture from this I would like to know how can I resolve this I tried with

```<code>=INDEX(E9:E18,MODE(IF(AND(E9:E18<>"")*ISNA(MATCH(E9:E18,$B$1:$B1,0)),MATCH(E9:E18,E9:E18,0))))
</code>```

But I get lost trying to put a condition like only one value = value
Some help or code that I could use?

So this is my problem

答:
try:</p>
```<code>=QUERY({A:A};
 "select Col1,count(Col1)
  where Col1 is not null
  group by Col1
  label count(Col1)''")
</code>```

Body:
I'm trying to count the number of most frequent text in a column, I have this formula that I used before in excel...

=INDEX(E9:E18,MODE(IF((E9:E18<>"")*ISNA(MATCH(E9:E18,$B$1:$B1,0)),MATCH(E9:E18,E9:E18,0))))

This works, but when I get some repited value shows #N/A
Here is an capture from this I would like to know how can I resolve this I tried with

=INDEX(E9:E18,MODE(IF(AND(E9:E18<>"")*ISNA(MATCH(E9:E18,$B$1:$B1,0)),MATCH(E9:E18,E9:E18,0))))

But I get lost trying to put a condition like only one value = value
Some help or code that I could use?

So this is my problem

Body:
try:

=QUERY({A:A};
 "select Col1,count(Col1)
  where Col1 is not null
  group by Col1
  label count(Col1)''")


问:
Anchor: variable number of accounts in instruction wrapper
How can one set a variable number of input accounts for a an instruction wrapper?

i.e. given this:

```<code>#[derive(Accounts)]
pub struct Initialize<'info> {
   ...I'd like to specify here a random number of accounts
}
</code>```

This is useful when you would want to refer to all creators of a digital asset (say NFT), but you don't know in advance how many there are.

答:
Oh, I have just found out you can use something like this:</p>
```<code>pub fn do_something(ctx: Context<Initialize>) -> ProgramResult {
    let vec: Vec<AccountInfo> = ctx.remaining_accounts.into_vec();

    // do something with the accounts

    Ok(())
}
</code>```

Body:
How can one set a variable number of input accounts for a an instruction wrapper?

i.e. given this:

#[derive(Accounts)]
pub struct Initialize<'info> {
   ...I'd like to specify here a random number of accounts
}

This is useful when you would want to refer to all creators of a digital asset (say NFT), but you don't know in advance how many there are.

Body:
Oh, I have just found out you can use something like this:

pub fn do_something(ctx: Context<Initialize>) -> ProgramResult {
    let vec: Vec<AccountInfo> = ctx.remaining_accounts.into_vec();

    // do something with the accounts

    Ok(())
}


问:
How to outer-join two CSV files, using shell script?
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"
```
<p><strong>file2.csv</strong></p>
<pre class="lang-none prettyprint-override"><code>label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"
</code>```

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"
```
<p>Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:</p>
```awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv
```

答:
This solution prints exactly the wished result with any AWK.
Please note that the sorting algorithm is taken from the mawk manual.

```<code># SO71053039.awk

#-------------------------------------------------
# insertion sort of A[1..n]
function isort( A,A_SWAP,           n,i,j,hold ) {
  n = 0
  for (j in A)
    A_SWAP[++n] = j
  for( i = 2 ; i <= n ; i++)
  {
    hold = A_SWAP[j = i]
    while ( A_SWAP[j-1] "" > "" hold )
    { j-- ; A_SWAP[j+1] = A_SWAP[j] }
    A_SWAP[j] = hold
  }
  # sentinel A_SWAP[0] = "" will be created if needed
  return n
}

BEGIN {
  FS = OFS = ","
  out = "Output.csv"

  # read file 1
  fnr = 0
  while ((getline < ARGV[1]) > 0) {
    ++fnr
    if (fnr == 1) {
      for (i=1; i<=NF; i++)
        FIELDBYNAME1[$i] = i # e.g. FIELDBYNAME1["label"] = 1
    }
    else {
      LABEL_KEY[$FIELDBYNAME1["label"]]
      LABEL_KEY1[$FIELDBYNAME1["label"]] = $FIELDBYNAME1["\"Part-A\""]
    }
  }
  close(ARGV[1])

  # read file2
  fnr = 0
  while ((getline < ARGV[2]) > 0) {
    ++fnr
    if (fnr == 1) {
      for (i=1; i<=NF; i++)
        FIELDBYNAME2[$i] = i # e.g. FIELDBYNAME2["label"] = 1
    }
    else {
      LABEL_KEY[$FIELDBYNAME2["label"]]
      LABEL_KEY2[$FIELDBYNAME2["label"]] = $FIELDBYNAME2["\"Part-B\""]
    }
  }
  close(ARGV[2])

  # print the header
  print "label" OFS "\"Part-A\"" OFS "\"Part-B\"" > out

  # get the result
  z = isort(LABEL_KEY, LABEL_KEY_SWAP)
  for (i = 1; i <= z; i++) {
    result_string = sprintf("%s", LABEL_KEY_SWAP[i])
    if (LABEL_KEY_SWAP[i] in LABEL_KEY1)
      result_string = sprintf("%s", result_string OFS LABEL_KEY1[LABEL_KEY_SWAP[i]] OFS (LABEL_KEY_SWAP[i] in LABEL_KEY2 ? LABEL_KEY2[LABEL_KEY_SWAP[i]] : "NA"))
    else
      result_string = sprintf("%s", result_string OFS "NA" OFS LABEL_KEY2[LABEL_KEY_SWAP[i]])
    print result_string > out
  }
}
</code>```

Call:

```<code>awk -f SO71053039.awk file1.csv file2.csv
=> result file Output.csv with content:
label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"
</code>```

Body:
I have two CSV files, like the following:

file1.csv

label,"Part-A"
"ABC mn","2.0"
"XYZ","3.0"
"PQR SN","6"

file2.csv

label,"Part-B"
"XYZ","4.0"
"LMN Wv","8"
"PQR SN","6"
"EFG","1.0"

Desired Output.csv

label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"

Currently with the below awk command i am able to combine the matching one's which have entries for label in both the files like PQR and XYZ but unable to append the ones that are not having label values present in both the files:

awk -F, 'NR==FNR{a[$1]=substr($0,length($1)+2);next} ($1 in a){print $0","a[$1]}' file1.csv file2.csv

Body:
This solution prints exactly the wished result with any AWK.
Please note that the sorting algorithm is taken from the mawk manual.

# SO71053039.awk

#-------------------------------------------------
# insertion sort of A[1..n]
function isort( A,A_SWAP,           n,i,j,hold ) {
  n = 0
  for (j in A)
    A_SWAP[++n] = j
  for( i = 2 ; i <= n ; i++)
  {
    hold = A_SWAP[j = i]
    while ( A_SWAP[j-1] "" > "" hold )
    { j-- ; A_SWAP[j+1] = A_SWAP[j] }
    A_SWAP[j] = hold
  }
  # sentinel A_SWAP[0] = "" will be created if needed
  return n
}

BEGIN {
  FS = OFS = ","
  out = "Output.csv"

  # read file 1
  fnr = 0
  while ((getline < ARGV[1]) > 0) {
    ++fnr
    if (fnr == 1) {
      for (i=1; i<=NF; i++)
        FIELDBYNAME1[$i] = i # e.g. FIELDBYNAME1["label"] = 1
    }
    else {
      LABEL_KEY[$FIELDBYNAME1["label"]]
      LABEL_KEY1[$FIELDBYNAME1["label"]] = $FIELDBYNAME1["\"Part-A\""]
    }
  }
  close(ARGV[1])

  # read file2
  fnr = 0
  while ((getline < ARGV[2]) > 0) {
    ++fnr
    if (fnr == 1) {
      for (i=1; i<=NF; i++)
        FIELDBYNAME2[$i] = i # e.g. FIELDBYNAME2["label"] = 1
    }
    else {
      LABEL_KEY[$FIELDBYNAME2["label"]]
      LABEL_KEY2[$FIELDBYNAME2["label"]] = $FIELDBYNAME2["\"Part-B\""]
    }
  }
  close(ARGV[2])

  # print the header
  print "label" OFS "\"Part-A\"" OFS "\"Part-B\"" > out

  # get the result
  z = isort(LABEL_KEY, LABEL_KEY_SWAP)
  for (i = 1; i <= z; i++) {
    result_string = sprintf("%s", LABEL_KEY_SWAP[i])
    if (LABEL_KEY_SWAP[i] in LABEL_KEY1)
      result_string = sprintf("%s", result_string OFS LABEL_KEY1[LABEL_KEY_SWAP[i]] OFS (LABEL_KEY_SWAP[i] in LABEL_KEY2 ? LABEL_KEY2[LABEL_KEY_SWAP[i]] : "NA"))
    else
      result_string = sprintf("%s", result_string OFS "NA" OFS LABEL_KEY2[LABEL_KEY_SWAP[i]])
    print result_string > out
  }
}

Call:

awk -f SO71053039.awk file1.csv file2.csv
=> result file Output.csv with content:
label,"Part-A","Part-B"
"ABC mn","2.0",NA
"EFG",NA,"1.0"
"LMN Wv",NA,"8"
"PQR SN","6","6"
"XYZ","3.0","4.0"


问:
Use Google Apps Script to import multiple .CSV files from Google Drive into BigQuery
I've downloaded a year's worth of .CSV files from my portal with American Express.  I want to use Google Apps script to take this data and put it into Google BigQuery.  Can't really do this interactively because the BigQuery UX doesn't provide a mechanism to appending data to a table.  So, I have written a script to do it:

```<code>      var firstFileData = firstFile.getBlob().setContentType('application/octet-stream')
      var firstFileDataString = firstFileData.getDataAsString()
      var firstFileDataCSV = Utilities.parseCsv(firstFileDataString)
</code>```

The variable firstFileDataString ends up with the contents of the CSV, but what I'm noticing is that the newline character does not exist.  Therefore, logic further down in the program sees many columns instead of the desired 3.  Some of the reading that I've done suggests that the contemporary ways for creating .CSV files do not use the newline character \n, favoring the carriage return \r instead.

Implementing a RegExp to look for (and replace) the carriage return also doesn't seem to work around the issue.

答:
Perhaps you can use just:

```<code>t_record_sub.push([t_db_date, firstFileDataCSV[j][1], firstFileDataCSV[j][2]])
</code>```

instead of:

```<code>t_record_sub.push([t_db_date],[firstFileDataCSV[j][1]],[firstFileDataCSV[j][2]] + "\n")
</code>```

Then, probably, you don't need to make the replaces with regexp.

If you want to make a string from 2D array it can be something like this:

```<code>var string = t_record_sub.map(x => x.join(',')).join('\n');
</code>```

Here is the snippet to convert the flat array to the 2D array (3 columns) and then to the string:

var flat_array = [1,2,3,4,5,6,7,8,9];

var t_record_sub = [];
var i = 0;
while (i < flat_array.length) {
    t_record_sub.push([flat_array[i++], flat_array[i++], flat_array[i++]]);
}

var string = t_record_sub.map(x => x.join(',')).join('\n');

console.log(string);

// output:
// 1,2,3
// 4,5,6
// 7,8,9```
</div>
</div>
</p>
<p>Or even simpler: directly from the flat array to the string:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [1,2,3,4,5,6,7,8,9];

var i = 0;
var string = '';
while (i < flat_array.length) {
    string += array[i++] + ',' + array[i++] + ',' + array[i++] + '\n'
}

console.log(string.slice(0,-1)); // slice to remove the last '\n'

// the same output</code>```

Body:
I've downloaded a year's worth of .CSV files from my portal with American Express.  I want to use Google Apps script to take this data and put it into Google BigQuery.  Can't really do this interactively because the BigQuery UX doesn't provide a mechanism to appending data to a table.  So, I have written a script to do it:

      var firstFileData = firstFile.getBlob().setContentType('application/octet-stream')
      var firstFileDataString = firstFileData.getDataAsString()
      var firstFileDataCSV = Utilities.parseCsv(firstFileDataString)

The variable firstFileDataString ends up with the contents of the CSV, but what I'm noticing is that the newline character does not exist.  Therefore, logic further down in the program sees many columns instead of the desired 3.  Some of the reading that I've done suggests that the contemporary ways for creating .CSV files do not use the newline character \n, favoring the carriage return \r instead.

Implementing a RegExp to look for (and replace) the carriage return also doesn't seem to work around the issue.

Body:
Perhaps you can use just:

t_record_sub.push([t_db_date, firstFileDataCSV[j][1], firstFileDataCSV[j][2]])

instead of:

t_record_sub.push([t_db_date],[firstFileDataCSV[j][1]],[firstFileDataCSV[j][2]] + "\n")

Then, probably, you don't need to make the replaces with regexp.

If you want to make a string from 2D array it can be something like this:

var string = t_record_sub.map(x => x.join(',')).join('\n');

Here is the snippet to convert the flat array to the 2D array (3 columns) and then to the string:

var flat_array = [1,2,3,4,5,6,7,8,9];

var t_record_sub = [];
var i = 0;
while (i < flat_array.length) {
    t_record_sub.push([flat_array[i++], flat_array[i++], flat_array[i++]]);
}

var string = t_record_sub.map(x => x.join(',')).join('\n');

console.log(string);

// output:
// 1,2,3
// 4,5,6
// 7,8,9

Or even simpler: directly from the flat array to the string:

var array = [1,2,3,4,5,6,7,8,9];

var i = 0;
var string = '';
while (i < flat_array.length) {
    string += array[i++] + ',' + array[i++] + ',' + array[i++] + '\n'
}

console.log(string.slice(0,-1)); // slice to remove the last '\n'

// the same output


问:
Removal of strings after a term and not before
I'm looking at removing specific terms before certain words in a dataframe column.

```<code>data = {'Code':['001', '002', '003', '004', '005', '006','007'],
        'Territory':['Kinshasa West', 'West Kivu', 'East Tamaki', 'Sydney North','Sydney South','Brisbane East Suburb','Wattle Downs East']}

df = pd.DataFrame(data)
df

  Code             Territory
0  001         Kinshasa West
1  002             West Kivu
2  003           East Tamaki
3  004          Sydney North
4  005          Sydney South
5  006  Brisbane East Suburb
6  007     Wattle Downs East
</code>```

I'm interested in removing words "West", "East", "North", "South" only if they are the last words in the column value. However, they should not be removed if they come before the last word.

Expected output:

```<code>  Code             Territory
0  001              Kinshasa
1  002             West Kivu
2  003           East Tamaki
3  004                Sydney
4  005                Sydney
5  006  Brisbane East Suburb
6  007          Wattle Downs
</code>```

I'm able to filter out the specific terms from the column values but making use of word positions is the issue at the moment.

答:
You can use regex and .apply().

```<code>import re
def remove_nsew(territory):
    return re.sub(" (North|South|East|West)$", "", territory)
df["Territory"] = df["Territory"].apply(remove_nsew)
</code>```

Body:
I'm looking at removing specific terms before certain words in a dataframe column.

data = {'Code':['001', '002', '003', '004', '005', '006','007'],
        'Territory':['Kinshasa West', 'West Kivu', 'East Tamaki', 'Sydney North','Sydney South','Brisbane East Suburb','Wattle Downs East']}

df = pd.DataFrame(data)
df

  Code             Territory
0  001         Kinshasa West
1  002             West Kivu
2  003           East Tamaki
3  004          Sydney North
4  005          Sydney South
5  006  Brisbane East Suburb
6  007     Wattle Downs East

I'm interested in removing words "West", "East", "North", "South" only if they are the last words in the column value. However, they should not be removed if they come before the last word.

Expected output:

  Code             Territory
0  001              Kinshasa
1  002             West Kivu
2  003           East Tamaki
3  004                Sydney
4  005                Sydney
5  006  Brisbane East Suburb
6  007          Wattle Downs

I'm able to filter out the specific terms from the column values but making use of word positions is the issue at the moment.

Body:
You can use regex and .apply().

import re
def remove_nsew(territory):
    return re.sub(" (North|South|East|West)$", "", territory)
df["Territory"] = df["Territory"].apply(remove_nsew)


问:
Simple operation to waste time?
I'm looking for a simple operation / routine which can "waste" time if repeated continuously.

I'm researching how gprof profiles applications, so this "time waster" needs to waste time in the user space and should not require external libraries. IE, calling sleep(20) will "waste" 20 seconds of time, but gprof will not record this time because it occurred within another library.

Any recommendations for simple tasks which can be repeated to waste time?

答: Another variant on Tomalak's solution is to set up an alarm, and so in your busy-wait loop, you don't need to keep issuing a system call, but instead just check if the signal has been sent.</p>

Title: Simple operation to waste time?