问:
React - Extra table row printing incorrectly
I am looping through an array of objects, then based on a condition I am display that row in one Table or the other. However, when i call that condition, the object reacts how I would like (it displays in Table1) but in Table2 a number is being printed out also. The following is a snippit example. files contains and array of objects, person. If the person is male, they are added to an array and that array is passed to a seperate componenet and rendered elsewhere, This works. If the person is not male, they are returned in the table underneath the condiditon.

```<code><tbody>
{props.files.map(person=> (
    <div>
        {(person.gender === "male") ? maleArray.push(person) :
            <tr>
                <td>{person.name}</td>
                <td>{person.age}</td>
            </tr>
         }
    </div>
))}
</tbody>

</code>```

The problem is, everytime a male is detected, they are not displayed in the female table but a number is printed instead. For example,

Name
Age

Mary
51

1

Jane
19

The male table works as expected but if a male is detected in the loop, i get this output in the female table.

EDIT: Table is printing weird in final version. It would look something like this

Name    Age

Mary    51

1

Jane    19

答: In JSX you use ternary operator, it ALWAYS returns value when execution is finished, and that returned value is passed to a markup. So when a loop executes on "female" table, along with female names it shows the result of execution push method on an array in place of male names, which is an array length, that's why you see integers in a table. Try to separate male and female names in a component, not in JSX, and then there is no need to put a condition in JSX</p>

Body:
I am looping through an array of objects, then based on a condition I am display that row in one Table or the other. However, when i call that condition, the object reacts how I would like (it displays in Table1) but in Table2 a number is being printed out also. The following is a snippit example. files contains and array of objects, person. If the person is male, they are added to an array and that array is passed to a seperate componenet and rendered elsewhere, This works. If the person is not male, they are returned in the table underneath the condiditon.

{props.files.map(person=> (

        {(person.gender === "male") ? maleArray.push(person) :

                {person.name}
                {person.age}

         }

))}

The problem is, everytime a male is detected, they are not displayed in the female table but a number is printed instead. For example,

Name
Age

Mary
51

1

Jane
19

The male table works as expected but if a male is detected in the loop, i get this output in the female table.

EDIT: Table is printing weird in final version. It would look something like this

Name    Age

Mary    51

1

Jane    19


来源: stackexchange

问:
Is it possible to match a nested pair with regex?
Im attempting to parse some BBCode with regex, but the nested structures are giving me a headache

What I'm trying to parse is the following:

```<code>[COLOR="Red"]Red [COLOR="Green"]Green[/COLOR][/COLOR]
</code>```

I've come up with the following pattern, which I need to deal with the quotation marks around the color attribute, but it only matches the first leading COLOR and the first closing COLOR.  Its not matching in a proper nested arrangement

```<code>\[COLOR=(\"?)(.*?)(\"?)]([\s\S]*?)\[\/COLOR\]\
</code>```

Its being done in dart, as follows, but really I believe the problem might be with my regex pattern rather then the dart implementation

```<code>  text = text.replaceAllMapped(RegExp(r'\[COLOR=(\"?)(.*?)(\"?)]([\s\S]*?)\[\/COLOR\]', caseSensitive: false, multiLine: true), (match) {
    return '<font style="color: ${match.group(2)}">${match.group(4)}</font>';
  });
</code>```

答:
Matching braces (of any kind) are not regular. It's known to be a problem which is context free (can be solved by a stack machine or specified by a context free grammar), but not regular (can be solved by a finite state machine or specified by a regular expression).
While the commonly implemented "regular expressions" can do some non-regular things (due to backreferences), this is not one of those things.

In general, I'd recommend using a RegExp to tokenize the input, then build the stack based machine yourself on top.

Here, because it's simple enough, I'd just match the start and end markers and replace them individually, and not try to match the text between.

var re = RegExp(r'\[COLOR="(\w+)"\]|\[/COLOR\]');
text = text.replaceAllMapped(re, (m) {
  var color = m[1]; // The color of a start tag, null if not start tag.
  return color == null ? "" : "";
});
```
<p>If you want to <em>check</em> that the tags are balanced, we're back to having a stack (in this case so simple it's just a counter):</p>
<pre class="lang-dart prettyprint-override"><code>var re = RegExp(r'\[COLOR="(\w+)"\]|\[/COLOR\]');
var nesting = 0;
text = text.replaceAllMapped(re, (m) {
  var color = m[1];
  if (color == null) {
    if (nesting == 0) {
      throw ArgumentError.value(text, "text", "Bad nesting");
    }
    nesting--; // Decrement on close tag.
    return "</span>";
  }
  nesting++; // Increment on open-tag.
  return "<span style='color:$color'>";
});
if (nesting != 0) {
  throw ArgumentError.value(text, "text", "Bad nesting");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im attempting to parse some BBCode with regex, but the nested structures are giving me a headache

What I'm trying to parse is the following:

[COLOR="Red"]Red [COLOR="Green"]Green[/COLOR][/COLOR]

I've come up with the following pattern, which I need to deal with the quotation marks around the color attribute, but it only matches the first leading COLOR and the first closing COLOR.  Its not matching in a proper nested arrangement

\[COLOR=(\"?)(.*?)(\"?)]([\s\S]*?)\[\/COLOR\]\

Its being done in dart, as follows, but really I believe the problem might be with my regex pattern rather then the dart implementation

  text = text.replaceAllMapped(RegExp(r'\[COLOR=(\"?)(.*?)(\"?)]([\s\S]*?)\[\/COLOR\]', caseSensitive: false, multiLine: true), (match) {
    return '${match.group(4)}';
  });

Body:
Matching braces (of any kind) are not regular. It's known to be a problem which is context free (can be solved by a stack machine or specified by a context free grammar), but not regular (can be solved by a finite state machine or specified by a regular expression).
While the commonly implemented "regular expressions" can do some non-regular things (due to backreferences), this is not one of those things.

In general, I'd recommend using a RegExp to tokenize the input, then build the stack based machine yourself on top.

Here, because it's simple enough, I'd just match the start and end markers and replace them individually, and not try to match the text between.

var re = RegExp(r'\[COLOR="(\w+)"\]|\[/COLOR\]');
text = text.replaceAllMapped(re, (m) {
  var color = m[1]; // The color of a start tag, null if not start tag.
  return color == null ? "</span>" : "<span style='color:$color'>";
});

If you want to check that the tags are balanced, we're back to having a stack (in this case so simple it's just a counter):

var re = RegExp(r'\[COLOR="(\w+)"\]|\[/COLOR\]');
var nesting = 0;
text = text.replaceAllMapped(re, (m) {
  var color = m[1];
  if (color == null) {
    if (nesting == 0) {
      throw ArgumentError.value(text, "text", "Bad nesting");
    }
    nesting--; // Decrement on close tag.
    return "</span>";
  }
  nesting++; // Increment on open-tag.
  return "<span style='color:$color'>";
});
if (nesting != 0) {
  throw ArgumentError.value(text, "text", "Bad nesting");
}


问:
How to continue in nested loops in Python
How can you continue the parent loop of say two nested loops in Python?

```<code>for a in b:
    for c in d:
        for e in f:
            if somecondition:
                <continue the for a in b loop?>
</code>```

I know you can avoid this in the majority of cases but can it be done in Python?

答:
```<code>lista = ["hello1", "hello2" , "world"]

for index,word in enumerate(lista):
    found = False
    for i in range(1,3):
        if word == "hello"+str(i):
            found = True
            break
        print(index)
    if found == True:
        continue
    if word == "world":
        continue
    print(index)

</code>```

Now what's printed :

```<code>>> 1
>> 2
>> 2
</code>```

This means that the word no.1 ( index = 0 ) appeard first (there's no way for something to be printed before the continue statement). The word no.2 ( index = 1 ) appeared second ( the word "hello1" managed to be printed but not the rest ) and the word no.3 appeard third what mean's that the words "hello1" and "hello2" managed to be printed before the for loop reached this said third word.

To sum up it's just using the found = False / True boolean and the break statement.

Hope it helps!

ContentLicense: CC BY-SA 3.0

Body:
How can you continue the parent loop of say two nested loops in Python?

for a in b:
    for c in d:
        for e in f:
            if somecondition:
                <continue the for a in b loop?>

I know you can avoid this in the majority of cases but can it be done in Python?

Body:
lista = ["hello1", "hello2" , "world"]

for index,word in enumerate(lista):
    found = False
    for i in range(1,3):
        if word == "hello"+str(i):
            found = True
            break
        print(index)
    if found == True:
        continue
    if word == "world":
        continue
    print(index)

Now what's printed :

>> 1
>> 2
>> 2

This means that the word no.1 ( index = 0 ) appeard first (there's no way for something to be printed before the continue statement). The word no.2 ( index = 1 ) appeared second ( the word "hello1" managed to be printed but not the rest ) and the word no.3 appeard third what mean's that the words "hello1" and "hello2" managed to be printed before the for loop reached this said third word.

To sum up it's just using the found = False / True boolean and the break statement.

Hope it helps!


问:
Separating Date and Time
I have a table displaying in my angular component and one of the columns is the date but it mashes the date and time together. I've tried separating them but I haven't had much luck doing so. the loop for placing each row of the csv data into my array obj is as follows:

```<code>let lines = csv.split("\n")
let headers = lines[0].split(/,/)
for(let i = 1; i < lines.length; i++) {
        let currLine = lines[i].split(",")
</code>```

then i try to manipulate the date element:

I've tried to separate the the date column into different array pieces for each char then put them back together but when I try to separate the date string it throws an error.

let jObj = currLine[1].split("")

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'split')

I've also tried to do the .replace("T", " ") so that way I could just split it by a " " but again it throws an error.

let jObj = currLine[1].replace("T", " ")

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'replace')

not sure if its a problem trying to separate an array element or my typescript coding. Can someone give me some suggestions please?

答:
As an alternative, rather than worry about splitting the date and time whilst reading it in from the file, you could always use the Angular date pipe to format the datetime however you like.

https://angular.io/api/common/DatePipe

Here are some examples on how you might see different date formats based on different parameters to the date pipe.

```<code>{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mm:ss' }}       // output is '43:11'
</code>```

Title: Separating Date and Time

Body:
I have a table displaying in my angular component and one of the columns is the date but it mashes the date and time together. I've tried separating them but I haven't had much luck doing so. the loop for placing each row of the csv data into my array obj is as follows:

let lines = csv.split("\n")
let headers = lines[0].split(/,/)
for(let i = 1; i < lines.length; i++) {
        let currLine = lines[i].split(",")

then i try to manipulate the date element:

I've tried to separate the the date column into different array pieces for each char then put them back together but when I try to separate the date string it throws an error.

let jObj = currLine[1].split("")

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'split')

I've also tried to do the .replace("T", " ") so that way I could just split it by a " " but again it throws an error.

let jObj = currLine[1].replace("T", " ")

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'replace')

not sure if its a problem trying to separate an array element or my typescript coding. Can someone give me some suggestions please?

Body:
As an alternative, rather than worry about splitting the date and time whilst reading it in from the file, you could always use the Angular date pipe to format the datetime however you like.

https://angular.io/api/common/DatePipe

Here are some examples on how you might see different date formats based on different parameters to the date pipe.

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mm:ss' }}       // output is '43:11'


问:
How to efficiently generate, in C, x random numbers in a given interval such the sum is constant?
To randomly generate nbValue in the interval [average-delta,average+delta] such that the sum of these values is equal to fullSum, I use this program

1 :  nbValue-1 are randomly generated

2 : the last value is calculated (fullSum - Sum of nbValue)

3 : If the last value is not in the interval, this loop is restarted.

This is the code :

```<code>int main()
{

    int fullSum = 4096, nbValue = 16;
    int average = round(fullSum / nbValue);
    int delta = round(average*0.125);
    int tryCounter = 0;
    int lastStep;

    srand(time(0));

    do {
      int currentSum = 0;
      for (int i=0;i<nbValue-1;i++)
        currentSum+=rand()%(delta*2+1)-delta+average ;
      tryCounter ++;
      lastStep = fullSum - currentSum;
    }
    while ( (lastStep < average - delta) || (lastStep > average + delta) );

    printf("Total tries : %d\n",tryCounter);
}
</code>```

Is there a better solution to be more efficient (That means, to reduce the number of tries) ? (Rq : I want a uniform distribution on the intervall)

Thanks for answer.

答:
One possible improvement (depends of cost of check vs. cost of rand()):

Rather than iterate nbValue-1 times and then check if a possible solution exist, also check after each iteration.

```<code>  // Re-start here
  sum = 0;
  for (int i=0; i < nbValue-1; i++) {
    currentSum += rand()%(delta*2+1)-delta+average ;
    int diff = (fullSum - currentSum)/(nbValue - i - 1);
    if (diff < average - delta) || (diff > average + delta) {
      start for loop again
    }
  }
  ...
</code>```

Body:
To randomly generate nbValue in the interval [average-delta,average+delta] such that the sum of these values is equal to fullSum, I use this program

1 :  nbValue-1 are randomly generated

2 : the last value is calculated (fullSum - Sum of nbValue)

3 : If the last value is not in the interval, this loop is restarted.

This is the code :

int main()
{

    int fullSum = 4096, nbValue = 16;
    int average = round(fullSum / nbValue);
    int delta = round(average*0.125);
    int tryCounter = 0;
    int lastStep;

    srand(time(0));

    do {
      int currentSum = 0;
      for (int i=0;i<nbValue-1;i++)
        currentSum+=rand()%(delta*2+1)-delta+average ;
      tryCounter ++;
      lastStep = fullSum - currentSum;
    }
    while ( (lastStep < average - delta) || (lastStep > average + delta) );

    printf("Total tries : %d\n",tryCounter);
}

Is there a better solution to be more efficient (That means, to reduce the number of tries) ? (Rq : I want a uniform distribution on the intervall)

Thanks for answer.

Body:
One possible improvement (depends of cost of check vs. cost of rand()):

Rather than iterate nbValue-1 times and then check if a possible solution exist, also check after each iteration.

  // Re-start here
  sum = 0;
  for (int i=0; i < nbValue-1; i++) {
    currentSum += rand()%(delta*2+1)-delta+average ;
    int diff = (fullSum - currentSum)/(nbValue - i - 1);
    if (diff < average - delta) || (diff > average + delta) {
      start for loop again
    }
  }
  ...


问:
Ansible: ec2 aws plugin - How to associate ec2 host to ansible group based on aws_profile?
I'm sure there must be a simple answer, but, when I use the aws_ec2 plugin to create a dynamic inventory for Ansible, I use the following setup so that I can pass the profile in to the inventory (to get the correct credentials):

plugin: aws_ec2
aws_profile: "{{ lookup('env', 'AWS_PROFILE') | default('dev-profile', true) }}"
regions:
  - us-east-1
```
<p>Now, I want all of these hosts to be associated with a group which has the name of the AWS_PROFILE passed in.  How do I do this?</p>
<p>I tried:</p>
<pre class="lang-yaml prettyprint-override"><code>groups:
    dev_group: aws_profile == 'dev-profile'
    test_group: aws_profile == 'test-profile'
</code>```

but was unsuccessful (no groups were created).

答:
The fact that you sets a value to the parameter aws_profile in your inventory does not makes it available in a variable.

So what you have to do is to reuse the same lookup in your groups conditions:

groups:
  dev_group: lookup('env', 'AWS_PROFILE') | default('dev-profile', true) == 'dev-profile'
  test_group: lookup('env', 'AWS_PROFILE') | default('dev-profile', true) == 'test-profile'
```

Body:
I'm sure there must be a simple answer, but, when I use the aws_ec2 plugin to create a dynamic inventory for Ansible, I use the following setup so that I can pass the profile in to the inventory (to get the correct credentials):

plugin: aws_ec2
aws_profile: "{{ lookup('env', 'AWS_PROFILE') | default('dev-profile', true) }}"
regions:
  - us-east-1

Now, I want all of these hosts to be associated with a group which has the name of the AWS_PROFILE passed in.  How do I do this?

I tried:

groups:
    dev_group: aws_profile == 'dev-profile'
    test_group: aws_profile == 'test-profile'

but was unsuccessful (no groups were created).


问:
pip install ngrok ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output
im trying to pip install ngrok but i got the error.
i use ubuntu server
I haven't been able to solve it for hours :(
please help me</p>
```<code>pip install ngrok
/usr/local/lib/python3.8/dist-packages/pkg_resources/__init__.py:122: PkgResourcesDeprecationWarning: 0.1.36ubuntu1 is an invalid version and will not be supported in a future release
  warnings.warn(
/usr/local/lib/python3.8/dist-packages/pkg_resources/__init__.py:122: PkgResourcesDeprecationWarning: 0.23ubuntu1 is an invalid version and will not be supported in a future release
  warnings.warn(
Collecting ngrok
  Using cached ngrok-0.1.6.tar.gz (3.5 kB)
Collecting ping
  Using cached ping-0.2.tar.gz (10 kB)
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-qanhr0lu/ping/setup.py'"'"'; __file__='"'"'/tmp/pip-install-qanhr0lu/ping/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-qanhr0lu/ping/pip-egg-info
         cwd: /tmp/pip-install-qanhr0lu/ping/
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-qanhr0lu/ping/setup.py", line 23, in <module>
        from ping import __version__
      File "/tmp/pip-install-qanhr0lu/ping/ping.py", line 196
        except socket.error, (errno, msg):
                           ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

答:
I'm not sure which python ngrok library you are trying to install, but I suspect it's probably pyngrok which is installed using: pip install pyngrok

source: https://pyngrok.readthedocs.io/en/latest/index.html

Body:
im trying to pip install ngrok but i got the error.
i use ubuntu server
I haven't been able to solve it for hours :(
please help me

pip install ngrok
/usr/local/lib/python3.8/dist-packages/pkg_resources/__init__.py:122: PkgResourcesDeprecationWarning: 0.1.36ubuntu1 is an invalid version and will not be supported in a future release
  warnings.warn(
/usr/local/lib/python3.8/dist-packages/pkg_resources/__init__.py:122: PkgResourcesDeprecationWarning: 0.23ubuntu1 is an invalid version and will not be supported in a future release
  warnings.warn(
Collecting ngrok
  Using cached ngrok-0.1.6.tar.gz (3.5 kB)
Collecting ping
  Using cached ping-0.2.tar.gz (10 kB)
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-qanhr0lu/ping/setup.py'"'"'; __file__='"'"'/tmp/pip-install-qanhr0lu/ping/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-qanhr0lu/ping/pip-egg-info
         cwd: /tmp/pip-install-qanhr0lu/ping/
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-qanhr0lu/ping/setup.py", line 23, in <module>
        from ping import __version__
      File "/tmp/pip-install-qanhr0lu/ping/ping.py", line 196
        except socket.error, (errno, msg):
                           ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.


问:
How can I submit unsubmitted Moodle attempt via SQL
Hello I ma trying to submit unsubmitted quiz attempts so I can grade them. So far I have set the timefinish column in mdl_quiz_attempts which changes the attempt status to "Not yet graded", then setting fraction to 0 from NULL and state to "gradewrong" from "complete" in mdl_question_attempt_steps to simulate submission but this seems to break the site. What am I missing?</p>

答: Thanks. The trick is to set the timefinish column in mdl_quiz_attempts which changes the attempt status to "Not yet graded", then setting the state to "gradewrong" from "complete" in mdl_question_attempt_steps for unsubmitted responses to simulate submission. Then set a fake 0 grade to sumgrades where grades are NULL in mdl_quiz_attempts and then running a regrade in the admin panel.


问:
Making webpack and CRA emit files in watch mode
I'm, trying to make CRA's start script to emit files on changes instead of keeping them in memory.

I'm working to implement Google Chrome Extension so I need files to be flushed to the file system so that Chrome could pick them up. And building each change is not as convenient as an automatic compilation.

I've tried to use react-app-rewired to override a bunch of props in webpack config, including mode, watch, and to see 'output.path' but no luck so far.

Or CRA's 'start' script will never emit underlying because the loaders are not tuned to do that?

Appreciate your help!

答:
I know this question is already answered and yeah a couple of months ago this worked for me as well

but recently I started a new project where I wanted to couple a react app with express and I tried using the same setup and suddenly got the error below:

```<code>Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'writeToDisk'. These properties are valid:
   object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
error Command failed with exit code 1.
</code>```

Since this QA has helped me back then I decided to share what I found here for anyone who is reading this in future and is getting the same error.

Solution

There seems to be some changes to webpack config "devserver" structure which you can find here: https://webpack.js.org/configuration/dev-server/

Where you can not use writeToDisk directly anymore and need to put it in a devMiddleware object like below:

    module.exports = {
        devServer: {
            devMiddleware: {
                writeToDisk: true,
            },
        },
        //...
    }

```

I am using: craco: ^6.4.3

I hope this helps someone who faced the same issue as me

Body:
I know this question is already answered and yeah a couple of months ago this worked for me as well

but recently I started a new project where I wanted to couple a react app with express and I tried using the same setup and suddenly got the error below:

Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'writeToDisk'. These properties are valid:
   object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
error Command failed with exit code 1.

Since this QA has helped me back then I decided to share what I found here for anyone who is reading this in future and is getting the same error.

Solution

There seems to be some changes to webpack config "devserver" structure which you can find here: https://webpack.js.org/configuration/dev-server/

Where you can not use writeToDisk directly anymore and need to put it in a devMiddleware object like below:

    module.exports = {
        devServer: {
            devMiddleware: {
                writeToDisk: true,
            },
        },
        //...
    }

I am using: craco: ^6.4.3

I hope this helps someone who faced the same issue as me


问:
halaxa/json-machine is deprecated! What can we use now?
"message": "Class 'JsonMachine\JsonMachine' not found",
"exception": "Error",

Root composer.json requires halaxa/json-machine ^0.8.0@dev, dev-master, found halaxa/json-machine[dev-syntax-check, dev-ext, dev-master, dev-issue-62, dev-0_4, dev-push-parsing, v0.1.0, ..., 0.8.0] but it does not match the constraint.

答:
CHANGELOG.md keeps track of all the important changes such as the one you've described along with the hint to what to use instead. Also, if you skip no minor version when upgrading, you will be notified of any deprecations beforehand.

JSON Machine is not deprecated and there are no plans to do so.

Edit:
Also, no version matching 0.8.0@dev was ever released. The closest would be 0.8.0-BETA2 which would be matched by constraint 0.8.0@beta. That's why Composer complains about it.


问:
Is there a way that I can make the second animation not get overwritten?
So I've tried separating the animations with a comma and having them on the same transform but it still doesn't work.

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  background: silver;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 20%;
  height: 20%;
  background-color: pink;
  transform: rotate(0deg) translatey(0px);
  animation: wavy 3s linear infinite alternate,
  float 3s linear infinite alternate;
}

@keyframes wavy {
  0% {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(-10deg);
  }
  100% {
    transform: rotate(10deg);
  }
}

@keyframes float {
  0% {
    transform: translatey(0px);
  }
  50% {
    transform: translatey(-20px);
  }
  100% {
    transform: translatey(0px);
  }
} ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
</div></code>```

And here's a link to the codepen:

https://codepen.io/FaroukHamadi/pen/OJOWWKW

答:
Yes - add an id to the div and set that animation on the specified id. For your example, I called it #box

EDIT ~ the id solution I had previously worked flawlessly UNLESS there are two transforms being used in the keyframe which is your case. What I would suggest is just combining the two animations into one animation and using more % increments. So instead of 0, 50, and 100, you can use 0, 25, 50, 75, 100 - to combine the two and have it seem like they are "alternating"

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  background: silver;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 20%;
  height: 20%;
  background-color: pink;
  transform: rotate(0deg) translatey(0px);
  animation: wavy-float 3s linear infinite alternate;
}

@keyframes wavy-float {
  0% {
    transform: rotate(0deg):
  }
  25% {
    transform: rotate(-20deg);
  }
  50% {
    transform: translateY(-20px);
  }
  75% {
    transform: rotate(20deg);
  }
  100% {
    transform: translateY(20px)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
</div></code>```

Body:
So I've tried separating the animations with a comma and having them on the same transform but it still doesn't work.

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  background: silver;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 20%;
  height: 20%;
  background-color: pink;
  transform: rotate(0deg) translatey(0px);
  animation: wavy 3s linear infinite alternate,
  float 3s linear infinite alternate;
}

@keyframes wavy {
  0% {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(-10deg);
  }
  100% {
    transform: rotate(10deg);
  }
}

@keyframes float {
  0% {
    transform: translatey(0px);
  }
  50% {
    transform: translatey(-20px);
  }
  100% {
    transform: translatey(0px);
  }
}

And here's a link to the codepen:

https://codepen.io/FaroukHamadi/pen/OJOWWKW

Body:
Yes - add an id to the div and set that animation on the specified id. For your example, I called it #box

EDIT ~ the id solution I had previously worked flawlessly UNLESS there are two transforms being used in the keyframe which is your case. What I would suggest is just combining the two animations into one animation and using more % increments. So instead of 0, 50, and 100, you can use 0, 25, 50, 75, 100 - to combine the two and have it seem like they are "alternating"

* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

html, body {
  width: 100%;
  height: 100%;
}

.container {
  width: 100%;
  height: 100%;
  background: silver;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 20%;
  height: 20%;
  background-color: pink;
  transform: rotate(0deg) translatey(0px);
  animation: wavy-float 3s linear infinite alternate;
}

@keyframes wavy-float {
  0% {
    transform: rotate(0deg):
  }
  25% {
    transform: rotate(-20deg);
  }
  50% {
    transform: translateY(-20px);
  }
  75% {
    transform: rotate(20deg);
  }
  100% {
    transform: translateY(20px)
  }
}

<div class="container">
  <div class="box"></div>
</div>


问:
Write x509 certificate into PEM formatted string in java?
Is there some high level way to write an X509Certificate into a PEM formatted string?
Currently I'm doing x509cert.encode() to write it into a DER formatted string, then base 64 encoding it and appending the header and footer to create a PEM string, but it seems bad. Especially since I have to throw in line breaks too. </p>

答:
Java 11 update:</p>
```<code>System.out.println(X509Factory.BEGIN_CERT);
System.out.println(java.util.Base64.getMimeEncoder(64,
    new byte[] {'\r', '\n'}).encodeToString(cert.getEncoded()));
System.out.println(X509Factory.END_CERT);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Java 11 update:

System.out.println(X509Factory.BEGIN_CERT);
System.out.println(java.util.Base64.getMimeEncoder(64,
    new byte[] {'\r', '\n'}).encodeToString(cert.getEncoded()));
System.out.println(X509Factory.END_CERT);


问:
How to test nextjs endpoint using Jest?
I have an endpoint that handles user signup:

```<code>import { createToken } './token'; // Unable to mock
import { sendEmail } './email'; // Unable to mock

export default async function signUp(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<any> {
  try {
    // Generate a verification token
    const token = await createToken(req.user);

    // Email the token
    await sendEmail(req.user, token);

    return res.status(200).send({ done: true });
  } catch (error: any) {
    console.error(error);
    return res.status(500).end(error.message);
  }
}
</code>```

How do I mock the imported dependencies for my jest unit tests?

```<code>import signup from './signup';

describe('signup', () => {
  it('should return success', async () => {
    const req: IncomingMessage = {} as unknown as IncomingMessage;
    const res: ServerResponse = {
      end: jest.fn(),
    } as unknown as ServerResponse;

    const actual = await signup(req, res);

    ...
  });
});
</code>```

Is it the case that Jest cannot actually mock these nested dependencies and some sort of DI pattern needs to be implemented here in the endpoint? If so, what DI patterns can I use to support unit tests for Nextjs endpoints?

答:
<s>It looks like jest.mock doesn't support mocking dependencies for imports outside of the actual test file (.spec.ts & .test.ts).</s> In my case I have a lot of dependencies in my Next API endpoint.

I opted to use Nextjs's middleware pattern to test my endpoint logic instead.

```<code>// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: Function) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result: any) => {
      if (result instanceof Error) {
        return reject(result)
      }

      return resolve(result)
    })
  })
}
</code>```

Extract the endpoint logic to the function and instead test only the extracted function.

```<code>// We test this function instead of the endpoint
export function post(
  _createToken: Function,
  _sendEmail: Function,
) {
  return async function(req: NextApiRequest, res: NextApiResponse) {
    ...
  }
}
</code>```

Here is an outline for the test. My actual code depends on classes instead of functions but they amount to similar things.

```<code>describe('signup', () => {
  let createToken: Function;
  let sendEmail: Function;

  beforeAll(() => {
    createToken = jest.fn();
    sendEmail = jest.fn();
  });

  it('should complete the happy path', async () => {
    const req: NextApiRequest = {} as unknown as NextApiRequest;
    const res: NextApiResponse = {} as unknown as NextApiResponse;

    await (
      await post(createToken, sendEmail)
    )(req, res);

    // expect
  });
});
</code>```

Title: How to test nextjs endpoint using Jest?

Body:
I have an endpoint that handles user signup:

import { createToken } './token'; // Unable to mock
import { sendEmail } './email'; // Unable to mock

export default async function signUp(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<any> {
  try {
    // Generate a verification token
    const token = await createToken(req.user);

    // Email the token
    await sendEmail(req.user, token);

    return res.status(200).send({ done: true });
  } catch (error: any) {
    console.error(error);
    return res.status(500).end(error.message);
  }
}

How do I mock the imported dependencies for my jest unit tests?

import signup from './signup';

describe('signup', () => {
  it('should return success', async () => {
    const req: IncomingMessage = {} as unknown as IncomingMessage;
    const res: ServerResponse = {
      end: jest.fn(),
    } as unknown as ServerResponse;

    const actual = await signup(req, res);

    ...
  });
});

Is it the case that Jest cannot actually mock these nested dependencies and some sort of DI pattern needs to be implemented here in the endpoint? If so, what DI patterns can I use to support unit tests for Nextjs endpoints?

Body:
<s>It looks like jest.mock doesn't support mocking dependencies for imports outside of the actual test file (.spec.ts & .test.ts).</s> In my case I have a lot of dependencies in my Next API endpoint.

I opted to use Nextjs's middleware pattern to test my endpoint logic instead.

// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req: NextApiRequest, res: NextApiResponse, fn: Function) {
  return new Promise((resolve, reject) => {
    fn(req, res, (result: any) => {
      if (result instanceof Error) {
        return reject(result)
      }

      return resolve(result)
    })
  })
}

Extract the endpoint logic to the function and instead test only the extracted function.

// We test this function instead of the endpoint
export function post(
  _createToken: Function,
  _sendEmail: Function,
) {
  return async function(req: NextApiRequest, res: NextApiResponse) {
    ...
  }
}

Here is an outline for the test. My actual code depends on classes instead of functions but they amount to similar things.

describe('signup', () => {
  let createToken: Function;
  let sendEmail: Function;

  beforeAll(() => {
    createToken = jest.fn();
    sendEmail = jest.fn();
  });

  it('should complete the happy path', async () => {
    const req: NextApiRequest = {} as unknown as NextApiRequest;
    const res: NextApiResponse = {} as unknown as NextApiResponse;

    await (
      await post(createToken, sendEmail)
    )(req, res);

    // expect
  });
});


问:
sdelete.exe is not working with cfexecute
I am trying to run sdelete.exe (http://technet.microsoft.com/en-us/sysinternals/bb897443.aspx) using cfexecute, but I think cfexecute is not even running that command.

It's not giving me any permission error. And I have given all admin privileges to ColdFusion service -> logon tab.

The following is the line that I have in my .cfm page that run successfully but doesn't delete the file:

```<code><Cfexecute name="C:\Inetpub\wwwroot\sdelete.exe" arguments="-p 2 C:\Inetpub\wwwroot\Deepak\testP\removeme.txt" outputfile="C:\Inetpub\wwwroot\Deepak\testP\out.txt"></Cfexecute>
</code>```

I am able to execute it in command prompt writing:

```<code>>C:\Inetpub\wwwroot\sdelete.exe -p 2 C:\Inetpub\wwwroot\Deepak\testP\removeme.txt
</code>```

And remove.txt is gone!

I have checked all the windows and ColdFusion logs, and didn't found anything useful.

答:
Add a timeout value to cfexecute

ie timeout="100"

Body:
I am trying to run sdelete.exe (http://technet.microsoft.com/en-us/sysinternals/bb897443.aspx) using cfexecute, but I think cfexecute is not even running that command.

It's not giving me any permission error. And I have given all admin privileges to ColdFusion service -> logon tab.

The following is the line that I have in my .cfm page that run successfully but doesn't delete the file:

<Cfexecute name="C:\Inetpub\wwwroot\sdelete.exe" arguments="-p 2 C:\Inetpub\wwwroot\Deepak\testP\removeme.txt" outputfile="C:\Inetpub\wwwroot\Deepak\testP\out.txt"></Cfexecute>

I am able to execute it in command prompt writing:

>C:\Inetpub\wwwroot\sdelete.exe -p 2 C:\Inetpub\wwwroot\Deepak\testP\removeme.txt

And remove.txt is gone!

I have checked all the windows and ColdFusion logs, and didn't found anything useful.


问:
Laravel Livewire Select Field gets empty on render, but array still holds the selected value
I have a strange behaviour on my Livewire Component Select Field,
I am using an array which expands on click on button "add item".
When I select in the  field on my form a value it gets selected but disappears after calling the change function in my livewire script.
If I select the value a second time it works.
What I have:
Blade:

```<code>     @foreach ($positions as $index => $position)
            <div class="col-sm-6" >
           <!-- abk -->
           <label for="pos "> </label><br>   <label for="auftrag">Auftrag:</label>
        @if(($positions[$index]['part_id']>0) && ($positions[$index]['part_id'] != 9999))
        @if(isset($positions[$index]['abks']) && count($positions[$index]['abks'])>0)
          <!-- true if there are abks -->
         <select class="form-control"   id="positions[{{$index}}]['abk_id']" wire:change="abkChanged({{$index}},$event.target.value)" >
                                               <option value="0" >-</option>
                                               @foreach($positions[$index]['abks'] as $abk)
                                                   <option value="{{$abk['id']}}">
                                                   {{$abk['auftragsnummer']}} -Fert.menge: {{$abk['fertigungsmenge']}} - geänd.: {{\Carbon\Carbon::parse($abk['updated_at'])->format('d.m.Y - H:i') }}</option>
                                               @endforeach
                                               <option value="9999" >eigene Beschreibung</option>
                                           </select>
                                    @else
                                        <!-- todo what to do if there are no abks... -->

                                    @endif

                                @endif <!-- if part_id >0 & not 9999-->
                                    @if(isset($position['showabktext']) && $position['showabktext'] == 1)

                                        <input type="text" class="form-control" name="positions[{{$index}}]['abktext']" wire:model="positions.{{$index}}.abktext" placeholder="ABK/AB # ..."/>
                                @endif
                                   @if (isset($position['abk_id'])) {{$position['abk_id']}}
                                     positions:   {{$positions[$index]['abk_id']}}
                                   @endif
  @endforeach
</code>```

the Component:

```<code>public function partChanged($indexPosition) { //if part is selected
 //   dd($indexPosition); // holds $this->positions[$indexPosition]
    if($this->positions[$indexPosition]['part_id'] == 9999) { //own description
        $this->positions[$indexPosition]['showartikeltext']=1; //own artikelbezeichnung
        $this->positions[$indexPosition]['showlszustandtext']=1; //own bearbeitet nach zeichnung etc
        $this->positions[$indexPosition]['showabktext']=1; //own abk text

    } else { //part from db
        $this->positions[$indexPosition]['showartikeltext']=0;
        $this->positions[$indexPosition]['showlszustandtext']=0;
        $this->positions[$indexPosition]['abks']= Abk::where('part_id','=',$this->positions[$indexPosition]['part_id'])->orderBy('updated_at')->get();//client_id
        $this->positions[$indexPosition]['showabktext']=0;
        if(empty($this->positions[$indexPosition]['abks'])|| count($this->positions[$indexPosition]['abks'])<1) {
            $this->positions[$indexPosition]['showabktext']=1;
        }
    }
    //zustand

}

public function abkChanged($indexPosition, $value) {
    $this->positions[$indexPosition]['abk_id'] = $value;
    if($this->positions[$indexPosition]['abk_id'] === 9999) {
        $this->positions[$indexPosition]['showabktext']=1;
    }

   // dd($this->positions[$indexPosition]['abk_id']);
 //   dd($this->positions);
 //dd($value);

}

public function addPos(){
    $counter = count($this->positions);
    $this->positions[] = ['position'=>$counter, 'part_id'=>0];

}

public function removePos($index){
    unset($this->positions[$index]); //lösche ag aus array
    $this->positions = array_values($this->positions); //reorder Array!

}
</code>```

short for understanding what has to happen:
I select a client -> then render the clients parts  after selecting a part render the abks which belong to the parts.
And then select the abk.

Selecting a client and then selecting a part works perfectly - but if I select an abk the selection disappears ($positions.$index.['abk_id]) - but if I add another item  to the list (another part) the abk selection renders as expected. on the first item, if I select the second one same behaviour as before on the first one.

I think I have a id / name DOM problem but I can't see it...

Please help :(

Thank you!
Stev

答: ... oh man what a baaad "bug", if I remove the Carbon->parse method from the Select field option it works as expected - I don't know why ... but it works now.</p>

Body:
I have a strange behaviour on my Livewire Component Select Field,
I am using an array which expands on click on button "add item".
When I select in the  field on my form a value it gets selected but disappears after calling the change function in my livewire script.
If I select the value a second time it works.
What I have:
Blade:

     @foreach ($positions as $index => $position)

   Auftrag:
        @if(($positions[$index]['part_id']>0) && ($positions[$index]['part_id'] != 9999))
        @if(isset($positions[$index]['abks']) && count($positions[$index]['abks'])>0)

         <select class="form-control"   id="positions[{{$index}}]['abk_id']" wire:change="abkChanged({{$index}},$event.target.value)" >
                                               <option value="0" >-</option>
                                               @foreach($positions[$index]['abks'] as $abk)
                                                   <option value="{{$abk['id']}}">
                                                   {{$abk['auftragsnummer']}} -Fert.menge: {{$abk['fertigungsmenge']}} - geänd.: {{\Carbon\Carbon::parse($abk['updated_at'])->format('d.m.Y - H:i') }}</option>
                                               @endforeach
                                               <option value="9999" >eigene Beschreibung</option>
                                           </select>
                                    @else

                                    @endif

                                @endif
                                    @if(isset($position['showabktext']) && $position['showabktext'] == 1)

                                        <input type="text" class="form-control" name="positions[{{$index}}]['abktext']" wire:model="positions.{{$index}}.abktext" placeholder="ABK/AB # ..."/>
                                @endif
                                   @if (isset($position['abk_id'])) {{$position['abk_id']}}
                                     positions:   {{$positions[$index]['abk_id']}}
                                   @endif
  @endforeach

the Component:

public function partChanged($indexPosition) { //if part is selected
 //   dd($indexPosition); // holds $this->positions[$indexPosition]
    if($this->positions[$indexPosition]['part_id'] == 9999) { //own description
        $this->positions[$indexPosition]['showartikeltext']=1; //own artikelbezeichnung
        $this->positions[$indexPosition]['showlszustandtext']=1; //own bearbeitet nach zeichnung etc
        $this->positions[$indexPosition]['showabktext']=1; //own abk text

    } else { //part from db
        $this->positions[$indexPosition]['showartikeltext']=0;
        $this->positions[$indexPosition]['showlszustandtext']=0;
        $this->positions[$indexPosition]['abks']= Abk::where('part_id','=',$this->positions[$indexPosition]['part_id'])->orderBy('updated_at')->get();//client_id
        $this->positions[$indexPosition]['showabktext']=0;
        if(empty($this->positions[$indexPosition]['abks'])|| count($this->positions[$indexPosition]['abks'])<1) {
            $this->positions[$indexPosition]['showabktext']=1;
        }
    }
    //zustand

}

public function abkChanged($indexPosition, $value) {
    $this->positions[$indexPosition]['abk_id'] = $value;
    if($this->positions[$indexPosition]['abk_id'] === 9999) {
        $this->positions[$indexPosition]['showabktext']=1;
    }

   // dd($this->positions[$indexPosition]['abk_id']);
 //   dd($this->positions);
 //dd($value);

}

public function addPos(){
    $counter = count($this->positions);
    $this->positions[] = ['position'=>$counter, 'part_id'=>0];

}

public function removePos($index){
    unset($this->positions[$index]); //lösche ag aus array
    $this->positions = array_values($this->positions); //reorder Array!

}

short for understanding what has to happen:
I select a client -> then render the clients parts  after selecting a part render the abks which belong to the parts.
And then select the abk.

Selecting a client and then selecting a part works perfectly - but if I select an abk the selection disappears ($positions.$index.['abk_id]) - but if I add another item  to the list (another part) the abk selection renders as expected. on the first item, if I select the second one same behaviour as before on the first one.

I think I have a id / name DOM problem but I can't see it...

Please help :(

Thank you!
Stev


问:
Is there a proper time to clean data when importing into a Pandas dataframe?
I am scraping the CIA Worldbook for country data as a learning exercise.  I scrape the data and clean it up during import and then later convert to Pandas dataframe.

I have two choices - clean the data as it is being read in, as I am doing now, or just read everything into the dataframe and clean it up after the fact.
Here are two examples of what I am doing now:

```<code>raw data
info = "$2,000 note: data are in 2017 dollars (2020 est.)"
int(info.text[:info.text.find(' ')].replace(',', '').replace('$', ''))
result  2000
</code>```
```<code>raw data
info = "36.08 births/1,000 population (2021 est.)"
float(info.text[:info.text.find(' ')].replace(',', ''))
result 36.08
</code>```

I suspect that cleaning in the dataframe after downloading would be a better solution but the only way I can think to do that is using Regular Expressions - which at the moment I am not too well versed in. Would that be the "correct" way to do it, or does it even matter?  If cleaning up the dataframe is the solution, what might these look like?

Thanks

答:
There are some things that are important depending on your case:

Do you want it to be highly reproducible or extendable?

Should it be highly performant?

Is readability more important than performance/extendability?

I've found that in the far majority of the cases, the performance doesn't matter that much. As long as you're not dealing with enormous amount of data to process or you're not working on low-performing infrastructure, it should run sufficiently fast. Again, this depends on your use case.

What I find way more annoying/time-consuming is over-complex functions that you won't know how they work afterwards, or having severely nested functionality. Those can take enormous amount of time to fix once your data-format changes or you need to alter some small parts in the code.

I would therefore agree that the ideal workflow would be to first download and store the raw data for reproducibility. Then you should write a processing function that makes them 'DataFrame' ready. Whenever your raw data then changes, you only have to rewrite this single function and assert the processed data comes out the same format it used to.
Moreover, whenever you decide that you don't want to use pandas anymore (because you want to use regular numpy arrays for example), it is an easier fix to exclude pandas from your code than when it is completely knitted in your workflow since the very beginning.

This would be my motivation to do the processing before reading into a DataFrame.

Body:
I am scraping the CIA Worldbook for country data as a learning exercise.  I scrape the data and clean it up during import and then later convert to Pandas dataframe.

I have two choices - clean the data as it is being read in, as I am doing now, or just read everything into the dataframe and clean it up after the fact.
Here are two examples of what I am doing now:

raw data
info = "$2,000 note: data are in 2017 dollars (2020 est.)"
int(info.text[:info.text.find(' ')].replace(',', '').replace('$', ''))
result  2000

raw data
info = "36.08 births/1,000 population (2021 est.)"
float(info.text[:info.text.find(' ')].replace(',', ''))
result 36.08

I suspect that cleaning in the dataframe after downloading would be a better solution but the only way I can think to do that is using Regular Expressions - which at the moment I am not too well versed in. Would that be the "correct" way to do it, or does it even matter?  If cleaning up the dataframe is the solution, what might these look like?

Thanks


问:
How to check if a value in the list exists in the dataframe?
Got a data frame that has 5 columns and a list that contains 20 values.

if the value in the list exactly matches any value in the columns then it has to append the value (list value) to an empty column.

```<code>list=["siper","glock","tip",............]
</code>```

INPUT (DATAFRAME ) DF1:

DESIRED OUTPUT:

My code to check if the value in the list exist in data frame.

```<code>list=["siper","glock","tip",............]
df2=[]
for i in list:
  mask=np.column_stack([df[col]==i for col in df])
  df2.append(df.loc[mask.any(axis=1)])
</code>```

The above code gives a list of all rows in the data frame if the value in the list matches any column but I am not sure how to append values in the list to column1 if there is any match. Also, I want to add "Unknow" to column1 if there is no match.

答:
Try this:</p>
```<code>df['column1'] = np.array(['unknown', *l])[np.max([df.apply(lambda col: col.str.contains(item)).mul(i+1).sum(axis=1) for i, item in enumerate(list)], axis=0)]
</code>```

Body:
Got a data frame that has 5 columns and a list that contains 20 values.

if the value in the list exactly matches any value in the columns then it has to append the value (list value) to an empty column.

list=["siper","glock","tip",............]

INPUT (DATAFRAME ) DF1:

DESIRED OUTPUT:

My code to check if the value in the list exist in data frame.

list=["siper","glock","tip",............]
df2=[]
for i in list:
  mask=np.column_stack([df[col]==i for col in df])
  df2.append(df.loc[mask.any(axis=1)])

The above code gives a list of all rows in the data frame if the value in the list matches any column but I am not sure how to append values in the list to column1 if there is any match. Also, I want to add "Unknow" to column1 if there is no match.

Body:
Try this:

df['column1'] = np.array(['unknown', *l])[np.max([df.apply(lambda col: col.str.contains(item)).mul(i+1).sum(axis=1) for i, item in enumerate(list)], axis=0)]


问:
Is there a way to stop the "Source" block from generating agents after a specific time in AnyLogic?
Utilizing a source generating agents on an Interarrival time basis, I would like to stop the source block from generating agents after a certain amount of time passing so that the model can continue to process the agents.

答: One option to encapsulate all the logic inside the source block, without external events or variables, would be to select Multiple agents per arrival as true and then have a conditional statement for the number of agents, for example time() > 10 ? 0 : 1, so that after 10 model time units there will no agents arriving


问:
Postgres subquery with a separate aggregate?
I have a feeling that the answer here is something to do with pivot tables... however, this is what I am struggling to do. The source table has many report ids and more landcover and data types but I think this illustrates things...

here is part of the table I am querying.

report_id
landcover_type
data_type
mean
area

615
Acid grassland
canopyheight
2
493.9125

615
Arable and horticulture
canopyheight
4
0.86

615
Acid grassland
carbonstoragewoodlands
8
493.9125

615
Arable and horticulture
carbonstoragewoodlands
16
0.86

Is there a simple way to query the data and get the following...

report_id
landcover_type
mean_canopy_height
mean_carbonstorage

615
Acid grassland
2
8

615
Arable and horticulture
4
16

答:
I am not sure the following gives you what you want, but it does give you what you asked for. All that it requires is simple MIN/MAX values of the mean column.

```<code>with dataset(report_id, landcover_type, data_type,  mean, area) as
    ( values ( 615, 'Acid grassland',            'canopyheight',                2,  493.9125 )
           , ( 615, 'Arable and horticulture',   'canopyheight',                4,  0.86 )
           , ( 615, 'Acid grassland',            'carbonstoragewoodlands',      8,  493.9125 )
           , ( 615, 'Arable and horticulture',   'carbonstoragewoodlands',     16,  0.86)
    )
select report_id
     , landcover_type
     , min(mean) mean_canopy_height
     , max(mean) mean_carbonstorage
  from dataset
 group by report_id, landcover_type
 order by landcover_type;
</code>```

If not what you actually want, then you need to clarify what you want and/or modify the expected results given the same imput.

Body:
I am not sure the following gives you what you want, but it does give you what you asked for. All that it requires is simple MIN/MAX values of the mean column.

with dataset(report_id, landcover_type, data_type,  mean, area) as
    ( values ( 615, 'Acid grassland',            'canopyheight',                2,  493.9125 )
           , ( 615, 'Arable and horticulture',   'canopyheight',                4,  0.86 )
           , ( 615, 'Acid grassland',            'carbonstoragewoodlands',      8,  493.9125 )
           , ( 615, 'Arable and horticulture',   'carbonstoragewoodlands',     16,  0.86)
    )
select report_id
     , landcover_type
     , min(mean) mean_canopy_height
     , max(mean) mean_carbonstorage
  from dataset
 group by report_id, landcover_type
 order by landcover_type;

If not what you actually want, then you need to clarify what you want and/or modify the expected results given the same imput.


问:
Is there a way to not inherit "virtualness" of a function in a subclass?
Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?

The reason for wanting this is that I have two classes which both expose a flush() function. The vast majority of the time in my program, I am calling flush() directly on a subclass object that I know the type of, so I don't need virtual dispatch. However I want to add a superclass into the mix so that very infrequently I can pass a reference to an instance of either one of the classes into a doSomethingThenFlush() function, which would call flush() virtually.

I know I could use templates instead of virtual functions, and I know I could have two different functions (eg. flushVirtual() which just called flushNonVirtual(), and call flushNonVirtual() everywhere I don't need virtual dispatch). But these both seem a bit like throwing code at a problem which is largely syntactical. Is there any more elegant way to achieve this?

Perhaps more importantly, does anyone know why virtualness is inherited in C++?

```<code>struct Base
{
  virtual ~Base(){}
  virtual void func();
};

struct Derived : public Base
{
  void func(){}
};

void callVirtually(Base &base)
{
  base.func();//this will use virtual dispatch
}

void callStatically(Derived &derived)
{
  derived.func();//I don't want/need this to use virtual dispatch
}

int main()
{
  Derived derived;
  callVirtually(derived);
  callStatically(derived);
}
</code>```

答:
The answer lies in your question.

```<code>derived.func();  // no virtual dispatch
</code>```

When you call a virtual function using object, there is no virtual dispatch. It calls the function using the static-type of the object.

virtual function comes into the picture only when you try to call a function using a pointer or a reference.

Edit: In your updated question, you are using Derived& to call func(). Calling by reference will make sure that virtual dispatch happens. So there is no language facility (like final in Java), which will stop virtual dispatch.

Body:
Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?

The reason for wanting this is that I have two classes which both expose a flush() function. The vast majority of the time in my program, I am calling flush() directly on a subclass object that I know the type of, so I don't need virtual dispatch. However I want to add a superclass into the mix so that very infrequently I can pass a reference to an instance of either one of the classes into a doSomethingThenFlush() function, which would call flush() virtually.

I know I could use templates instead of virtual functions, and I know I could have two different functions (eg. flushVirtual() which just called flushNonVirtual(), and call flushNonVirtual() everywhere I don't need virtual dispatch). But these both seem a bit like throwing code at a problem which is largely syntactical. Is there any more elegant way to achieve this?

Perhaps more importantly, does anyone know why virtualness is inherited in C++?

struct Base
{
  virtual ~Base(){}
  virtual void func();
};

struct Derived : public Base
{
  void func(){}
};

void callVirtually(Base &base)
{
  base.func();//this will use virtual dispatch
}

void callStatically(Derived &derived)
{
  derived.func();//I don't want/need this to use virtual dispatch
}

int main()
{
  Derived derived;
  callVirtually(derived);
  callStatically(derived);
}

Body:
The answer lies in your question.

derived.func();  // no virtual dispatch

When you call a virtual function using object, there is no virtual dispatch. It calls the function using the static-type of the object.

virtual function comes into the picture only when you try to call a function using a pointer or a reference.

Edit: In your updated question, you are using Derived& to call func(). Calling by reference will make sure that virtual dispatch happens. So there is no language facility (like final in Java), which will stop virtual dispatch.


问:
Incompatible types: 'string' and 'Double'
I would like to use a Label or a Memo to view information:

```<code>function GetCPUSpeed: Double;
const
  DelayTime = 500;
var
  TimerHi, TimerLo: DWORD;
  PriorityClass, Priority: Integer;
begin
  PriorityClass := GetPriorityClass(GetCurrentProcess);
  Priority      := GetThreadPriority(GetCurrentThread);
  SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
  SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
  Sleep(10);
  asm
    dw 310Fh
    mov TimerLo, eax
    mov TimerHi, edx
  end;
  Sleep(DelayTime);
  asm
    dw 310Fh
    sub eax, TimerLo
    sbb edx, TimerHi
    mov TimerLo, eax
    mov TimerHi, edx
  end;
  SetThreadPriority(GetCurrentThread, Priority);
  SetPriorityClass(GetCurrentProcess, PriorityClass);
  Result := TimerLo / (1000 * DelayTime);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(Format('Your CPU speed: %f MHz', [GetCPUSpeed]));
  Label1.caption := GetCPUSpeed;
  Memo1.Lines := GetCPUSpeed;
end;
</code>```

To use the Label or a Memo, I have to convert data into a string. How can I do that?

[DCC Error] speed_cpu.pas(62): E2010 Incompatible types: 'string' and 'Double'

答:
First off, you can't assign a string to the TMemo.Lines property, which is a TStrings object.  You would have to assign to either TMemo.Lines.Text or TMemo.Text instead.

As for the actual conversion, you already know one way to do it, via SysUtils.Format():

uses
  ..., SysUtils;

var
  Speed: Double;
...
Speed := GetCPUSpeed;
ShowMessage(Format('Your CPU speed: %f MHz', [Speed]));
Label1.Caption := Format('%f', [Speed]);
Memo1.Text := Format('%f', [Speed]);
```
<p>You can also use <code>SysUtils.FloatToStr()</code>:</p>
<pre class="lang-pascal prettyprint-override"><code>uses
  ..., SysUtils;

var
  Speed: Double;
...
Speed := GetCPUSpeed;
ShowMessage(Format('Your CPU speed: %f MHz', [Speed]));
Label1.Caption := FloatToStr(Speed);
Memo1.Text := FloatToStr(Speed);
</code>```

In XE4+, you can also use SysUtils.TDoubleHelper.ToString():

uses
  ..., SysUtils;

var
  Speed: Double;
...
Speed := GetCPUSpeed;
ShowMessage(Format('Your CPU speed: %f MHz', [Speed]));
Label1.Caption := Speed.ToString;
Memo1.Text := Speed.ToString;
```

Body:
I would like to use a Label or a Memo to view information:

function GetCPUSpeed: Double;
const
  DelayTime = 500;
var
  TimerHi, TimerLo: DWORD;
  PriorityClass, Priority: Integer;
begin
  PriorityClass := GetPriorityClass(GetCurrentProcess);
  Priority      := GetThreadPriority(GetCurrentThread);
  SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
  SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
  Sleep(10);
  asm
    dw 310Fh
    mov TimerLo, eax
    mov TimerHi, edx
  end;
  Sleep(DelayTime);
  asm
    dw 310Fh
    sub eax, TimerLo
    sbb edx, TimerHi
    mov TimerLo, eax
    mov TimerHi, edx
  end;
  SetThreadPriority(GetCurrentThread, Priority);
  SetPriorityClass(GetCurrentProcess, PriorityClass);
  Result := TimerLo / (1000 * DelayTime);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(Format('Your CPU speed: %f MHz', [GetCPUSpeed]));
  Label1.caption := GetCPUSpeed;
  Memo1.Lines := GetCPUSpeed;
end;

To use the Label or a Memo, I have to convert data into a string. How can I do that?

[DCC Error] speed_cpu.pas(62): E2010 Incompatible types: 'string' and 'Double'

Body:
First off, you can't assign a string to the TMemo.Lines property, which is a TStrings object.  You would have to assign to either TMemo.Lines.Text or TMemo.Text instead.

As for the actual conversion, you already know one way to do it, via SysUtils.Format():

uses
  ..., SysUtils;

var
  Speed: Double;
...
Speed := GetCPUSpeed;
ShowMessage(Format('Your CPU speed: %f MHz', [Speed]));
Label1.Caption := Format('%f', [Speed]);
Memo1.Text := Format('%f', [Speed]);

You can also use SysUtils.FloatToStr():

uses
  ..., SysUtils;

var
  Speed: Double;
...
Speed := GetCPUSpeed;
ShowMessage(Format('Your CPU speed: %f MHz', [Speed]));
Label1.Caption := FloatToStr(Speed);
Memo1.Text := FloatToStr(Speed);

In XE4+, you can also use SysUtils.TDoubleHelper.ToString():

uses
  ..., SysUtils;

var
  Speed: Double;
...
Speed := GetCPUSpeed;
ShowMessage(Format('Your CPU speed: %f MHz', [Speed]));
Label1.Caption := Speed.ToString;
Memo1.Text := Speed.ToString;


问:
In Django, how to rename user model?
I trying to rename my user model CustomUser => User

Here what I've done:

Rename Python class and all references

makemigrations

```<code>Did you rename the accounts.CustomUser model to User? [y/N] y
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped
    res = handle_func(*args, **kwargs)
  File "/venv/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 168, in handle
    migration_name=self.migration_name,
  File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes
    changes = self._detect_changes(convert_apps, graph)
  File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 186, in _detect_changes
    self.generate_altered_fields()
  File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 959, in generate_altered_fields
    dependencies.extend(self._get_dependencies_for_foreign_key(new_field))
  File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 1086, in _get_dependencies_for_foreign_key
    dep_app_label = field.remote_field.model._meta.app_label
AttributeError: 'SettingsReference' object has no attribute '_meta'
</code>```

So I'm stuck with this exception, any help appreciated :)

答:
Just ran into this problem, here is how I handled it:

Assuming that your user models are in an app called "users":

Leave the AUTH_USER_MODEL setting at the old value (users.CustomUser).

In users/model.py, rename the class from CustomUser to User add a new class with the old name that inherits from the new name

```<code>class CustomUser(User):
    pass
</code>```

Use manage.py to create an empty migration file

```<code>python manage.py makemigrations --empty users
</code>```

Open the newly create migration file, and add this operation:

```<code>operations = [
    migrations.RenameModel('CustomUser', 'User')
]
</code>```

Migrate the changes

```<code>python manage.py migrate users
</code>```

Then you can go and change AUTH_USER_MODEL to users.User and remove the CustomUser class from users/model.py

I reference the user model using settings.AUTH_USER_MODEL when defining a ForeignKey and get_user_model() from django.contrib.auth anywhere else so I had no other references that needed to be changed.

Title: In Django, how to rename user model?

Body:
I trying to rename my user model CustomUser => User

Here what I've done:

Rename Python class and all references

makemigrations

Did you rename the accounts.CustomUser model to User? [y/N] y
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "/venv/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped
    res = handle_func(*args, **kwargs)
  File "/venv/lib/python3.7/site-packages/django/core/management/commands/makemigrations.py", line 168, in handle
    migration_name=self.migration_name,
  File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 43, in changes
    changes = self._detect_changes(convert_apps, graph)
  File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 186, in _detect_changes
    self.generate_altered_fields()
  File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 959, in generate_altered_fields
    dependencies.extend(self._get_dependencies_for_foreign_key(new_field))
  File "/venv/lib/python3.7/site-packages/django/db/migrations/autodetector.py", line 1086, in _get_dependencies_for_foreign_key
    dep_app_label = field.remote_field.model._meta.app_label
AttributeError: 'SettingsReference' object has no attribute '_meta'

So I'm stuck with this exception, any help appreciated :)

Body:
Just ran into this problem, here is how I handled it:

Assuming that your user models are in an app called "users":

Leave the AUTH_USER_MODEL setting at the old value (users.CustomUser).

In users/model.py, rename the class from CustomUser to User add a new class with the old name that inherits from the new name

class CustomUser(User):
    pass

Use manage.py to create an empty migration file

python manage.py makemigrations --empty users

Open the newly create migration file, and add this operation:

operations = [
    migrations.RenameModel('CustomUser', 'User')
]

Migrate the changes

python manage.py migrate users

Then you can go and change AUTH_USER_MODEL to users.User and remove the CustomUser class from users/model.py

I reference the user model using settings.AUTH_USER_MODEL when defining a ForeignKey and get_user_model() from django.contrib.auth anywhere else so I had no other references that needed to be changed.


问:
ReactJS: how using queryselector variable out a function
I'm using this code:

export default function Naviguation() {

```<code>const overBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (
    <nav>
        <img src={img} className='nav-logo' alt="logo" />
        <div className='nav-btn-menu' onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
            <span className='nav-barTop nav-bars'></span>
            <span className='nav-barMiddle nav-bars'></span>
            <span className='nav-barBottom nav-bars'></span>
        </div>
    </nav>
)
</code>```

}

the code runs correctly but I want to use the variable "navBars" once time like this

export default function Naviguation() {

```<code>const navBars = document.querySelectorAll('.nav-bars')

const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (
    <nav>
        <img src={img} className='nav-logo' alt="logo" />
        <div className='nav-btn-menu' onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
            <span className='nav-barTop nav-bars'></span>
            <span className='nav-barMiddle nav-bars'></span>
            <span className='nav-barBottom nav-bars'></span>
        </div>
    </nav>
)
</code>```

}

But the code doesn't run because it wrote on the console "navBars undefined..."

How using a variable out the function to using it into my function?

答:
I found the solution !! I just remove "null" from const navBarsRef = useRef()
Thanks very much for helping</p>
```<code>import "./Naviguation.css";

export default function Navigation() {
  const navBarsRef = useRef();
  const navBars = navBarsRef.current;

  useEffect(() => {
    navBarsRef.current = document.querySelectorAll('.nav-bars');
  }, []);

  const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
      navBars[i].style.width = '40px';
    }
  };

  const outBtnMenu = () => {
    navBars[0].style.width = '20px';
    navBars[1].style.width = '30px';
    navBars[2].style.width = '20px';
  };

  return (
    <nav>
      <img src={img} className="nav-logo" alt="logo" />
      <div className="nav-btn-menu" onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
        <span className="nav-barTop nav-bars"></span>
        <span className="nav-barMiddle nav-bars"></span>
        <span className="nav-barBottom nav-bars"></span>
      </div>
    </nav>
  );
}
</code>```

Body:
I'm using this code:

export default function Naviguation() {

const overBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (

)

}

the code runs correctly but I want to use the variable "navBars" once time like this

export default function Naviguation() {

const navBars = document.querySelectorAll('.nav-bars')

const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (

)

}

But the code doesn't run because it wrote on the console "navBars undefined..."

How using a variable out the function to using it into my function?

Body:
I found the solution !! I just remove "null" from const navBarsRef = useRef()
Thanks very much for helping

import "./Naviguation.css";

export default function Navigation() {
  const navBarsRef = useRef();
  const navBars = navBarsRef.current;

  useEffect(() => {
    navBarsRef.current = document.querySelectorAll('.nav-bars');
  }, []);

  const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
      navBars[i].style.width = '40px';
    }
  };

  const outBtnMenu = () => {
    navBars[0].style.width = '20px';
    navBars[1].style.width = '30px';
    navBars[2].style.width = '20px';
  };

  return (
    <nav>
      <img src={img} className="nav-logo" alt="logo" />
      <div className="nav-btn-menu" onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
        <span className="nav-barTop nav-bars"></span>
        <span className="nav-barMiddle nav-bars"></span>
        <span className="nav-barBottom nav-bars"></span>
      </div>
    </nav>
  );
}


问:
Why isn't webpack retaining console.log statements?
I'm doing my first tests with webpack and experimenting with code splitting, and I simply wanted to log from my index.js file. It gets compiled, but it doesn't log nothing, both in development or in production mode. Files are compiled and loaded. Very strange. I'm sure I'm doing something wrong... Could you please point me in the right direction?

```<code>// index.js
import _ from 'lodash';
import Swiper from 'swiper';
import { Fancybox, Carousel, Panzoom } from "@fancyapps/ui";

function log(){
  console.log('from index');
  console.log(Swiper);
  console.log(Fancybox, Carousel, Panzoom);
  console.log(_);
}

log();
</code>```

webpack config:

```<code>const path = require('path');

module.exports = {
  //mode: 'development',
  mode: 'production',
  watch: true,
  entry: {
    index: './src/index.js',
    //page_2: './src/page-2.js'
  },

  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },

  optimization: {
    splitChunks: {
      cacheGroups: {
        visuals: {
          name: 'visuals',
          chunks: 'all',
          test: /[\\/]node_modules[\\/](swiper|@fancyapps\/ui|dom7|ssr-window)[\\/]/
        },
        lowdash: {
          name: 'lowdash',
          chunks: 'all',
          test: /[\\/]node_modules[\\/]lodash[\\/]/
        }
      },
    }
  },

  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: { presets: ['@babel/preset-env'] }
        }
      } // babel
    ] // rules
  } // module
};
</code>```

答:
My guess would the as part of the optimization that webpack does, it cleans out your console.logs.

You could try adding

optimization: {
    minimize: false,
  },
};

```

and see if that helps. Although I'm surprised it's doing it in dev mode as well.

Body:
I'm doing my first tests with webpack and experimenting with code splitting, and I simply wanted to log from my index.js file. It gets compiled, but it doesn't log nothing, both in development or in production mode. Files are compiled and loaded. Very strange. I'm sure I'm doing something wrong... Could you please point me in the right direction?

// index.js
import _ from 'lodash';
import Swiper from 'swiper';
import { Fancybox, Carousel, Panzoom } from "@fancyapps/ui";

function log(){
  console.log('from index');
  console.log(Swiper);
  console.log(Fancybox, Carousel, Panzoom);
  console.log(_);
}

log();

webpack config:

const path = require('path');

module.exports = {
  //mode: 'development',
  mode: 'production',
  watch: true,
  entry: {
    index: './src/index.js',
    //page_2: './src/page-2.js'
  },

  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },

  optimization: {
    splitChunks: {
      cacheGroups: {
        visuals: {
          name: 'visuals',
          chunks: 'all',
          test: /[\\/]node_modules[\\/](swiper|@fancyapps\/ui|dom7|ssr-window)[\\/]/
        },
        lowdash: {
          name: 'lowdash',
          chunks: 'all',
          test: /[\\/]node_modules[\\/]lodash[\\/]/
        }
      },
    }
  },

  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: { presets: ['@babel/preset-env'] }
        }
      } // babel
    ] // rules
  } // module
};

Body:
My guess would the as part of the optimization that webpack does, it cleans out your console.logs.

You could try adding

optimization: {
    minimize: false,
  },
};

and see if that helps. Although I'm surprised it's doing it in dev mode as well.