问:
Referencing MSBuildTasks from Nuget package
I'm trying to reference MSBuildTasks from an MSBuild file, and I'm unsure of how to do this when using NuGet for MSBuildTasks.

The reference says to use

```<code><Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
</code>```

when you have installed MSBuildTasks using the msi file. However, when installing from NuGet it puts it in a subfolder that contains version, so if I upgrade MSBuildTasks it will break the path in the build file. What is the best way to reference MSBuildTasks when its installed via NuGet?

答:
At the moment, 1.4.0.128 creates the .build folder in the solution directory (for a framework project). The nuget package does not install properly to a .Net Core 3.1 project. I created a MsBuild.Community.Tasks 4.7.2 framework project within my solution and deployed the nuget package there. Now I should be able to invoke it from my .NetCore project as described in the readme:</p>

```<code><PropertyGroup>
    <MSBuildCommunityTasksPath>$(SolutionDir)\.build</MSBuildCommunityTasksPath>
</PropertyGroup>

<Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets" />
</code>```

Body:
I'm trying to reference MSBuildTasks from an MSBuild file, and I'm unsure of how to do this when using NuGet for MSBuildTasks.

The reference says to use

<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>

when you have installed MSBuildTasks using the msi file. However, when installing from NuGet it puts it in a subfolder that contains version, so if I upgrade MSBuildTasks it will break the path in the build file. What is the best way to reference MSBuildTasks when its installed via NuGet?

Body:
At the moment, 1.4.0.128 creates the .build folder in the solution directory (for a framework project). The nuget package does not install properly to a .Net Core 3.1 project. I created a MsBuild.Community.Tasks 4.7.2 framework project within my solution and deployed the nuget package there. Now I should be able to invoke it from my .NetCore project as described in the readme:

<PropertyGroup>
    <MSBuildCommunityTasksPath>$(SolutionDir)\.build</MSBuildCommunityTasksPath>
</PropertyGroup>

<Import Project="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.Targets" />


来源: stackexchange

问:
How to resolve Python package dependencies with pipenv?
I am using pipenv to handle Python package dependencies.

The Python package is using two packages (named pckg1 and pckg2) that rely on the same package named pckg3, but from two different versions. Showing the dependency tree :

```<code>$ pipenv graph
  pckg1==3.0.0
    - pckg3 [required: >=4.1.0]
  pckg2==1.0.2
    - pckg3 [required: ==4.0.11]
</code>```

An attempt to install dependencies :

```<code>$ pipenv install

Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.
You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation.
Hint: try $ pipenv lock --pre if it is a pre-release dependency.
Could not find a version that matches pckg3==4.0.11,==4.1.0,>=4.1.0 (from -r C:\Users\user\AppData\Local\Temp\pipenv-o7uxm080-requirements\pipenv-hwekv7dc-constraints.txt (line 2))
Tried: 3.3.1, 3.3.2, 3.3.3, 3.4.0, 3.4.2, 4.0.0, 4.0.0, 4.0.1, 4.0.1, 4.0.2, 4.0.2, 4.0.3, 4.0.3, 4.0.4, 4.0.4, 4.0.6, 4.0.6, 4.0.8, 4.0.8, 4.0.9, 4.0.9, 4.0.10, 4.0.10, 4.0.11, 4.0.11, 4.1.0, 4.1.0, 4.1.1, 4.1.1, 4.1.2, 4.1.2, 4.2.1, 4.2.1, 4.3.0, 4.3.0
There are incompatible versions in the resolved dependencies.
</code>```

As suggested, pip install --skip-lock does the trick, but the dependency tree is still unresolved.

I would love to tell Pipenv to override pckg2's requirement, and specify pckg3>=4.1.0.

How can this be resolved?

答:
This works when there are unfinished routines on pipfile.

Once I made a mistake and run

```<code>pipenv install codecove # With an 'e' at the end
</code>```

and the pipenv kept always trying to complete the installation with no success because the lib does not exist. I resolved it with:

```<code>pipenv uninstall codecove
</code>```

and installed codecov after.

I tried to run

```<code>pipenv lock --clear
pipenv lock --pre --clear
</code>```

but only after uninstalled the lib with wrong name I succeeded.

ContentLicense: CC BY-SA 4.0

Body:
I am using pipenv to handle Python package dependencies.

The Python package is using two packages (named pckg1 and pckg2) that rely on the same package named pckg3, but from two different versions. Showing the dependency tree :

$ pipenv graph
  pckg1==3.0.0
    - pckg3 [required: >=4.1.0]
  pckg2==1.0.2
    - pckg3 [required: ==4.0.11]

An attempt to install dependencies :

$ pipenv install

Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies.
You can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation.
Hint: try $ pipenv lock --pre if it is a pre-release dependency.
Could not find a version that matches pckg3==4.0.11,==4.1.0,>=4.1.0 (from -r C:\Users\user\AppData\Local\Temp\pipenv-o7uxm080-requirements\pipenv-hwekv7dc-constraints.txt (line 2))
Tried: 3.3.1, 3.3.2, 3.3.3, 3.4.0, 3.4.2, 4.0.0, 4.0.0, 4.0.1, 4.0.1, 4.0.2, 4.0.2, 4.0.3, 4.0.3, 4.0.4, 4.0.4, 4.0.6, 4.0.6, 4.0.8, 4.0.8, 4.0.9, 4.0.9, 4.0.10, 4.0.10, 4.0.11, 4.0.11, 4.1.0, 4.1.0, 4.1.1, 4.1.1, 4.1.2, 4.1.2, 4.2.1, 4.2.1, 4.3.0, 4.3.0
There are incompatible versions in the resolved dependencies.

As suggested, pip install --skip-lock does the trick, but the dependency tree is still unresolved.

I would love to tell Pipenv to override pckg2's requirement, and specify pckg3>=4.1.0.

How can this be resolved?

Body:
This works when there are unfinished routines on pipfile.

Once I made a mistake and run

pipenv install codecove # With an 'e' at the end

and the pipenv kept always trying to complete the installation with no success because the lib does not exist. I resolved it with:

pipenv uninstall codecove

and installed codecov after.

I tried to run

pipenv lock --clear
pipenv lock --pre --clear

but only after uninstalled the lib with wrong name I succeeded.


问:
Replacing columns with different Dataframe
I have two dataframes,namely 'df' and 'df1'

```<code>df
Out[14]:
      first country  Rating
0    Robert      US     100
1     Chris     Aus      99
2  Scarlett      US     100

df1
Out[17]:
        last        Role
0     Downey     IronMan
1  Hemsworth        Thor
2  Johansson  BlackWidow
</code>```

Expected output:

```<code>      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100
</code>```

I need to drop off the 'country' column and replace with another dataframe(ie. 'df1')

I understand,I can join dataframes and drop 'country' column,but I need columns exactly in this order.

答:
@Moahmed you can try the below approach:

df2 = pd.concat([df,df1], axis = 1)

df2 = df2[['first','last','Role','Rating']]

df2.head()

Body:
I have two dataframes,namely 'df' and 'df1'

df
Out[14]:
      first country  Rating
0    Robert      US     100
1     Chris     Aus      99
2  Scarlett      US     100

df1
Out[17]:
        last        Role
0     Downey     IronMan
1  Hemsworth        Thor
2  Johansson  BlackWidow

Expected output:

      first       last        Role  Rating
0    Robert     Downey     IronMan     100
1     Chris  Hemsworth        Thor      99
2  Scarlett  Johansson  BlackWidow     100

I need to drop off the 'country' column and replace with another dataframe(ie. 'df1')

I understand,I can join dataframes and drop 'country' column,but I need columns exactly in this order.


问:
Change style property of a DIV when a task is complete with Javascript
I am using the below Javascript to go out and collect images from Instagram, this works successfully but sometimes the loading can take a while.

When feed.runhas been completed I want to change the style of a div.

```<code>
var feed = new Instafeed({
 accessToken: InstagramToken,
 limit: 10,
 target: 'instafeed',
 transform: function(item) { //Transform receives each item as its argument
// Over-write the original timestamp

item.timestamp = new Date(item.timestamp).toLocaleString('en-AU', {

   year: 'numeric',
   month: 'long',
   day: 'numeric'
 });

// return the modified item
return item;

},

 template: '<div class="vertical-line"></div><div class="post-title">{{timestamp}}</div><div class="vertical-line"></div><div class="post-container"><div class="post-image"><img src="{{image}}"/></div> </div>',
});
feed.run();

function abc() {
    var color = document.getElementById("myDIV").style.color;
    if (color === "aqua")
         document.getElementById("myDIV").style.color="black";
    else
         document.getElementById("myDIV").style.color="red";

};

</script>```
```

答:
http://instafeedjs.com/#advanced

callbacks listed here

You can use the after callback advanced option:

```<code>var feed = new Instafeed({
 after: function(img){ abc() },
 accessToken: InstagramToken,
 limit: 10,
 target: 'instafeed',
 transform: function(item) { //Transform receives each item as its argument
// Over-write the original timestamp

item.timestamp = new Date(item.timestamp).toLocaleString('en-AU', {

   year: 'numeric',
   month: 'long',
   day: 'numeric'
 });

// return the modified item
return item;

},

 template: '<div class="vertical-line"></div><div class="post-title">{{timestamp}}</div><div class="vertical-line"></div><div class="post-container"><div class="post-image"><img src="{{image}}"/></div> </div>',
});
feed.run();

function abc() {
    var color = document.getElementById("myDIV").style.color;
    if (color === "aqua")
         document.getElementById("myDIV").style.color="black";
    else
         document.getElementById("myDIV").style.color="red";

};
</code>```

Body:
I am using the below Javascript to go out and collect images from Instagram, this works successfully but sometimes the loading can take a while.

When feed.runhas been completed I want to change the style of a div.

var feed = new Instafeed({
 accessToken: InstagramToken,
 limit: 10,
 target: 'instafeed',
 transform: function(item) { //Transform receives each item as its argument
// Over-write the original timestamp

item.timestamp = new Date(item.timestamp).toLocaleString('en-AU', {

   year: 'numeric',
   month: 'long',
   day: 'numeric'
 });

// return the modified item
return item;

},

 template: '

{{timestamp}}

',
});
feed.run();

function abc() {
    var color = document.getElementById("myDIV").style.color;
    if (color === "aqua")
         document.getElementById("myDIV").style.color="black";
    else
         document.getElementById("myDIV").style.color="red";

};

</script>```

Body:
http://instafeedjs.com/#advanced

callbacks listed here

You can use the after callback advanced option:

var feed = new Instafeed({
 after: function(img){ abc() },
 accessToken: InstagramToken,
 limit: 10,
 target: 'instafeed',
 transform: function(item) { //Transform receives each item as its argument
// Over-write the original timestamp

item.timestamp = new Date(item.timestamp).toLocaleString('en-AU', {

   year: 'numeric',
   month: 'long',
   day: 'numeric'
 });

// return the modified item
return item;

},

 template: '<div class="vertical-line"></div><div class="post-title">{{timestamp}}</div><div class="vertical-line"></div><div class="post-container"><div class="post-image"><img src="{{image}}"/></div> </div>',
});
feed.run();

function abc() {
    var color = document.getElementById("myDIV").style.color;
    if (color === "aqua")
         document.getElementById("myDIV").style.color="black";
    else
         document.getElementById("myDIV").style.color="red";

};


问:
Odoo onchange method is not saving values in readonly fields
In my view I have a Boolean field (chk_valido) and  two other fields. I want those fields to get the value of the current user and the current date, when the boolean fields is set to True. With this code the fields are getting the value but when I click the "Save" button  those values desapear. What is causing these issue? How can i save those values? "user_valido" and "fecha_validaciongabinete" are set to readoly in the view</p>

```<code>chk_valido = fields.Boolean(string='Está validado')
user_valido = fields.Many2one('res.users', string='Usuario valido')
fecha_validaciongabinete = fields.Datetime(string='Fecha Validacion gabinete')

@api.onchange('chk_valido')
def _onchange_chk_valido(self):
    if self.chk_valido:
        self.fecha_validaciongabinete=fields.Datetime.today()
        self.user_valido= self.env.user
    else:
        self.fecha_validaciongabinete=""
        self.user_valido=False
</code>```

答:
I found a solution: adding force_save="1" to the readonly fields in the view. I would be like this:</p>

```<code><field name="user_valido" readonly="1" force_save="1"/>

<field name="fecha_validaciongabinete" readonly="1" force_save="1"/>
</code>```

Body:
In my view I have a Boolean field (chk_valido) and  two other fields. I want those fields to get the value of the current user and the current date, when the boolean fields is set to True. With this code the fields are getting the value but when I click the "Save" button  those values desapear. What is causing these issue? How can i save those values? "user_valido" and "fecha_validaciongabinete" are set to readoly in the view

chk_valido = fields.Boolean(string='Está validado')
user_valido = fields.Many2one('res.users', string='Usuario valido')
fecha_validaciongabinete = fields.Datetime(string='Fecha Validacion gabinete')

@api.onchange('chk_valido')
def _onchange_chk_valido(self):
    if self.chk_valido:
        self.fecha_validaciongabinete=fields.Datetime.today()
        self.user_valido= self.env.user
    else:
        self.fecha_validaciongabinete=""
        self.user_valido=False

Body:
I found a solution: adding force_save="1" to the readonly fields in the view. I would be like this:

<field name="user_valido" readonly="1" force_save="1"/>

<field name="fecha_validaciongabinete" readonly="1" force_save="1"/>


问:
Single column dataframe containing 1D lists using a numpy 2D array
I want to create a new single column pandas dataframe using a 2D numpy array. Apparently, each row should contain 1D lists. Following is a simplified reproducible example.

```<code>import pandas as pd
import numpy as np

arr = np.ones((4,3)) # could be any 2D array
</code>```

What I want is,

```<code>       lists
0  [1, 1, 1]
1  [1, 1, 1]
2  [1, 1, 1]
3  [1, 1, 1]
</code>```

Now, df  = pd.DataFrame(arr, columns=['lists']) gives the error,

```<code>ValueError: Shape of passed values is (4, 3), indices imply (4, 1)
</code>```

And df = pd.DataFrame(list(arr), columns=['lists']) gives the error,

```<code>ValueError: 1 columns passed, passed data had 3 columns
</code>```

Finally, df = pd.DataFrame(arr.flatten(), columns=['lists']) gives a wrong dataframe with all cells having a scalar 1.

How do I get what I want?

Body:
I want to create a new single column pandas dataframe using a 2D numpy array. Apparently, each row should contain 1D lists. Following is a simplified reproducible example.

import pandas as pd
import numpy as np

arr = np.ones((4,3)) # could be any 2D array

What I want is,

       lists
0  [1, 1, 1]
1  [1, 1, 1]
2  [1, 1, 1]
3  [1, 1, 1]

Now, df  = pd.DataFrame(arr, columns=['lists']) gives the error,

ValueError: Shape of passed values is (4, 3), indices imply (4, 1)

And df = pd.DataFrame(list(arr), columns=['lists']) gives the error,

ValueError: 1 columns passed, passed data had 3 columns

Finally, df = pd.DataFrame(arr.flatten(), columns=['lists']) gives a wrong dataframe with all cells having a scalar 1.

How do I get what I want?

Body:
data = {"lists": list(arr)}

df = pd.DataFrame(data, columns=['lists'])

print(df)

Output:

             lists
0  [1.0, 1.0, 1.0]
1  [1.0, 1.0, 1.0]
2  [1.0, 1.0, 1.0]
3  [1.0, 1.0, 1.0]


问:
How can I strip Python logging calls without commenting them out?
Today I was thinking about a Python project I wrote about a year back where I used logging pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (hotshot indicated it was one of my biggest bottlenecks).

I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and target only the code objects that are causing bottlenecks. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:

```<code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls

[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls

[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code>```

Of course, you'd want to use it sparingly and probably with per-function granularity -- only for code objects that have shown logging to be a bottleneck. Anybody know of anything like this?

Note: There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named debug may have to be wrapped with an if not isinstance(log, Logger). In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)

答:
This is an issue in my project as well--logging ends up on profiler reports pretty consistently.

I've used the _ast module before in a fork of PyFlakes (http://github.com/kevinw/pyflakes) ... and it is definitely possible to do what you suggest in your question--to inspect and inject guards before calls to logging methods (with your acknowledged caveat that you'd have to do some runtime type checking). See http://pyside.blogspot.com/2008/03/ast-compilation-from-python.html for a simple example.

Edit: I just noticed MetaPython on my planetpython.org feed--the example use case is removing log statements at import time.

Maybe the best solution would be for someone to reimplement logging as a C module, but I wouldn't be the first to jump at such an...opportunity :p

OwnerDisplayName: cdleary

ContentLicense: CC BY-SA 2.5

Body:
Today I was thinking about a Python project I wrote about a year back where I used logging pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (hotshot indicated it was one of my biggest bottlenecks).

I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and target only the code objects that are causing bottlenecks. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:

[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls

[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls

[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls

Of course, you'd want to use it sparingly and probably with per-function granularity -- only for code objects that have shown logging to be a bottleneck. Anybody know of anything like this?

Note: There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named debug may have to be wrapped with an if not isinstance(log, Logger). In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)

LastEditorDisplayName: cdleary

OwnerDisplayName: Kevin Watters

LastEditorDisplayName: Kevin Watters


问:
UseMethod("type") error; no applicable method for 'type" applied to an object of class "c('double', 'numeric')"
In a dataframe, I have a column that has numeric values and some mixed in character data for some rows. I want to remove all rows with the character data and keep those rows with a number value. The df I have is 6 million rows, so I simply made a small object to try to solve my issue and then implement at a larger scale.

Here is what I did:

```<code>a <- c("fruit", "love", 53)

b <- str_replace_all("^[:alpha:]", 0)
</code>```

Reading answers to other UseMethod errors on here (about factors), I tried to change "a" to as.character(a) and attempt "b" again. But, I get the same error. I'm trying to simply make any alphabetic value into the number zero and I'm fairly new at all this.

答:
There are several issues here, even in these two lines of code.  First, a is a character vector, because its first element is a character.  This means that your numeric 53 is coerced into a character.

```<code>> print(a)
[1] "fruit" "love"  "53"
</code>```

You've got the wrong syntax for str_replace_all.  See the documentation for how to use it correctly.  But that's not what you want here, because you want numerics.

The first thing you need to do is convert a to a numeric.  A crude way of doing this is simply

```<code>>b <- as.numeric(a)
Warning message:
NAs introduced by coercion b
> b
[1] NA NA 53

</code>```

And then subset to include only the numeric values in b:

```<code>> b <- b[!is.na(b)]
> b
[1] 53
</code>```

But whether that's what you want to do with a 6 million row dataframe is another matter.  Please think about exactly what you would like to do, supply us with better test data, and ask your question again.

Body:
In a dataframe, I have a column that has numeric values and some mixed in character data for some rows. I want to remove all rows with the character data and keep those rows with a number value. The df I have is 6 million rows, so I simply made a small object to try to solve my issue and then implement at a larger scale.

Here is what I did:

a <- c("fruit", "love", 53)

b <- str_replace_all("^[:alpha:]", 0)

Reading answers to other UseMethod errors on here (about factors), I tried to change "a" to as.character(a) and attempt "b" again. But, I get the same error. I'm trying to simply make any alphabetic value into the number zero and I'm fairly new at all this.

Body:
There are several issues here, even in these two lines of code.  First, a is a character vector, because its first element is a character.  This means that your numeric 53 is coerced into a character.

> print(a)
[1] "fruit" "love"  "53"

You've got the wrong syntax for str_replace_all.  See the documentation for how to use it correctly.  But that's not what you want here, because you want numerics.

The first thing you need to do is convert a to a numeric.  A crude way of doing this is simply

>b <- as.numeric(a)
Warning message:
NAs introduced by coercion b
> b
[1] NA NA 53

And then subset to include only the numeric values in b:

> b <- b[!is.na(b)]
> b
[1] 53

But whether that's what you want to do with a 6 million row dataframe is another matter.  Please think about exactly what you would like to do, supply us with better test data, and ask your question again.


答:
In instafeed.js docs, it's mentioned that you can add some callbacks to the Instafeed function object, like before, after, success, error. In your case you want to add success callback function:

```<code>var feed = new Instafeed({
 accessToken: InstagramToken,
 limit: 10,
 target: 'instafeed',
 success: (images) => {
     // Change style here
 }
 ...
}
feed.run();
</code>```

Title: Change style property of a DIV when a task is complete with Javascript

Body:
In instafeed.js docs, it's mentioned that you can add some callbacks to the Instafeed function object, like before, after, success, error. In your case you want to add success callback function:

var feed = new Instafeed({
 accessToken: InstagramToken,
 limit: 10,
 target: 'instafeed',
 success: (images) => {
     // Change style here
 }
 ...
}
feed.run();


问:
CSS url image not visible Pythonanywhere
I created a header where the text changes according to an output in the backend. However, the image that constitutes this header is not visible.

I put the image in the static file that constitutes my app and added the path to the image in the CSS code as well as in the static files section of the Web tab as follows :

CSS code :

```<code>.hero-image {
    background-image: linear-gradient(rgb(47, 50, 51), rgba(0, 0, 0, 0.5)), url("/images/Ax8yBTP.jpg");
    height: 25%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
}
</code>```

Static files : /home/jejrhom1/mysite/static/images

Would you know where the error comes from?

Thank you!

答:
According to your path the correct is url("/static/images/Ax8yBTP.jpg")

Try to use relative path based on your css file location.
If you css path is like /home/jejrhom1/mysite/static/css/style.css - so the correct path to the image will be

```<code>url("../images/Ax8yBTP.jpg");
</code>```

../ this part means we go one level back, to the folder static, where we see both css and images.

Body:
I created a header where the text changes according to an output in the backend. However, the image that constitutes this header is not visible.

I put the image in the static file that constitutes my app and added the path to the image in the CSS code as well as in the static files section of the Web tab as follows :

CSS code :

.hero-image {
    background-image: linear-gradient(rgb(47, 50, 51), rgba(0, 0, 0, 0.5)), url("/images/Ax8yBTP.jpg");
    height: 25%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    position: relative;
}

Static files : /home/jejrhom1/mysite/static/images

Would you know where the error comes from?

Thank you!

Body:
According to your path the correct is url("/static/images/Ax8yBTP.jpg")

Try to use relative path based on your css file location.
If you css path is like /home/jejrhom1/mysite/static/css/style.css - so the correct path to the image will be

url("../images/Ax8yBTP.jpg");

../ this part means we go one level back, to the folder static, where we see both css and images.


问:
Negative Lookahead not match suffix
I have an expression that is matching something, but am trying to get this not to match if it's followed by the suffix: one or more spaces, three dashes, one or more spaces, one or more digits, a slash, and finally one or more digits.  Here is the expression:

```<code>(?<=(^|\s+))[A-Z]+[ ]+([0-9]+(\.[0-9]{1,3})?)/([0-9]+(\.[0-9]{1,3})?)(?!(\s+\-\-\-\s+[0-9]+/[0-9]+))
</code>```

And here is the text:

```<code>January        10.5/13.5   ---     22/26     ---
</code>```

It's matching January 10.5/13, but I don't want it to match anything.

答:
As lookarounds are supported, you can change the positive lookbehind at the start to a negative lookbehind asserting a whitespace boundary to the left (?<!\S)

You can use .* to it to scan the whole line, instead of starting with 1+ more whitespace chars \s+

The negative lookahead (?!.*\s-{3}\s+[0-9]+/[0-9] asserts that what is on the right is not the suffix.

You can omit the quantifier + after the last character class, as it does not matter if there are 1 or more digits following...as long as it is not a digit.

Note that in the current pattern, the decimal part is an optional capturing group 2. If you want that whole value in group 1, you can make it an optional group.

```<code>(?<!\S)[A-Z]+[ ]+([0-9]+(\.[0-9]{1,3})?)/([0-9]+(\.[0-9]{1,3})?)(?!.*\s-{3}\s+[0-9]+/[0-9])
</code>```

Regex demo

Title: Negative Lookahead not match suffix

Body:
I have an expression that is matching something, but am trying to get this not to match if it's followed by the suffix: one or more spaces, three dashes, one or more spaces, one or more digits, a slash, and finally one or more digits.  Here is the expression:

(?<=(^|\s+))[A-Z]+[ ]+([0-9]+(\.[0-9]{1,3})?)/([0-9]+(\.[0-9]{1,3})?)(?!(\s+\-\-\-\s+[0-9]+/[0-9]+))

And here is the text:

January        10.5/13.5   ---     22/26     ---

It's matching January 10.5/13, but I don't want it to match anything.

Body:
As lookarounds are supported, you can change the positive lookbehind at the start to a negative lookbehind asserting a whitespace boundary to the left (?<!\S)

You can use .* to it to scan the whole line, instead of starting with 1+ more whitespace chars \s+

The negative lookahead (?!.*\s-{3}\s+[0-9]+/[0-9] asserts that what is on the right is not the suffix.

You can omit the quantifier + after the last character class, as it does not matter if there are 1 or more digits following...as long as it is not a digit.

Note that in the current pattern, the decimal part is an optional capturing group 2. If you want that whole value in group 1, you can make it an optional group.

(?<!\S)[A-Z]+[ ]+([0-9]+(\.[0-9]{1,3})?)/([0-9]+(\.[0-9]{1,3})?)(?!.*\s-{3}\s+[0-9]+/[0-9])

Regex demo


问:
Prolog permutation extracting solutions
```<code>permutation([], []).
permutation(L, [X|Xs]) :- select(X, L, Rest), permutation(Rest, Xs).
</code>```

If I type permutation([1,2,3],R), the first solution is "[1,2,3]" but how to get to the second one without using ";" or "fail". I need to use the 2nd solution like "[1,3,2]" or so in order compare it to another list.

What I mean is:

```<code>permutation([], []).
permutation(L, [X|Xs]) :- select(X, L, Rest), permutation(Rest, Xs).

go_perm(L,P) :-
        L = P,
        write(P),nl.

go_perm(L,P) :-
        permutation(P,P2), % in this case i wanna get the next solution -.-
        go_perm(L,P2).
</code>```

If L = P then it finishes. Permutation of the first solution for "[1,2,3]" is "[1,2,3]". But that pulls me into stackoverflow because it runs into never-endless thing.
Perhaps you understand me. Thanks!

答:
Assuming you want to loop over the solutions to print them

One standard way to accomplish this is to fail and backtrack, as in:

```<code>print_all_permutations(X)
  :- permutation(X, Y), print(Y), nl, fail ; true.
</code>```

Assuming you just want to check if a given solution is correct

You are already done. Just call the function with the reference list and the list you want to test:

```<code>permutation([1, 2, 3], [2, 1, 3]).
</code>```

will return true, because [2, 1, 3] is a permutation of [1, 2, 3]. If the second argument is not a permutation, the goal will evaluate to false.

This is the magic of prolog: finding a solution, or checking if a given solution is correct, are the same thing.

In between: partial solution

The same reasoning still applies:

```<code>permutation([1, 2, 3], [2, X, 3]).
</code>```

will display the only possible value for X.

Or, if you want the whole list to be the result:

```<code>X = [2, X, 3], permutation([1, 2, 3], X).
</code>```

ContentLicense: CC BY-SA 3.0

Title: Prolog permutation extracting solutions

Body:
permutation([], []).
permutation(L, [X|Xs]) :- select(X, L, Rest), permutation(Rest, Xs).

If I type permutation([1,2,3],R), the first solution is "[1,2,3]" but how to get to the second one without using ";" or "fail". I need to use the 2nd solution like "[1,3,2]" or so in order compare it to another list.

What I mean is:

permutation([], []).
permutation(L, [X|Xs]) :- select(X, L, Rest), permutation(Rest, Xs).

go_perm(L,P) :-
        L = P,
        write(P),nl.

go_perm(L,P) :-
        permutation(P,P2), % in this case i wanna get the next solution -.-
        go_perm(L,P2).

If L = P then it finishes. Permutation of the first solution for "[1,2,3]" is "[1,2,3]". But that pulls me into stackoverflow because it runs into never-endless thing.
Perhaps you understand me. Thanks!

Body:
Assuming you want to loop over the solutions to print them

One standard way to accomplish this is to fail and backtrack, as in:

print_all_permutations(X)
  :- permutation(X, Y), print(Y), nl, fail ; true.

Assuming you just want to check if a given solution is correct

You are already done. Just call the function with the reference list and the list you want to test:

permutation([1, 2, 3], [2, 1, 3]).

will return true, because [2, 1, 3] is a permutation of [1, 2, 3]. If the second argument is not a permutation, the goal will evaluate to false.

This is the magic of prolog: finding a solution, or checking if a given solution is correct, are the same thing.

In between: partial solution

The same reasoning still applies:

permutation([1, 2, 3], [2, X, 3]).

will display the only possible value for X.

Or, if you want the whole list to be the result:

X = [2, X, 3], permutation([1, 2, 3], X).


问:
Create Page Persistence with Tabulator
I'm trying to enable a user to be able to leave the page with Tabulator on it and come back and it loads the same view they had before (including the page they were on, filters, and sorters they had enabled).

I have tried making it work using Tabulator's persist feature (as suggested below) but I get an error of: Pagination Error - Requested page is out of range of 1 - 1: 3

```<code>        //define new tabulator instance
        var table = new Tabulator("#production-data-table", {
            ajaxURL:"scripts/order_status.php?action=fetch_production_data", //ajax URL
            pagination:"remote",
            persistenceMode: "local",
            persistenceID: "production-data",
            persistence: {
                 sort: true, //persist column sorting
                 filter: true, //persist filter sorting
                 group: true, //persist row grouping
                 page: true, //persist page
                 columns: true, //persist columns
            },
            ajaxFiltering:true,
            ajaxSorting:true,
            layout:"fitColumns",
            columns:[
                {title:"Enterprise", field:"Enterprise", sorter:"string", width:100, headerSort:false},
                {title:"Job Number", field:"Job Number", sorter:"number", width:100, headerSort:false},
                {title:"LN #", field:"LN #", sorter:"string", formatter:"html", align:'center', width:80, headerSort:false},
                {title:"Description", field:"Description", sorter:"string", headerSort:false},
                {title:"QTY", field:"QTY", sorter:"string", headerSort:false, align: 'center', width: 40,},
                {title:"AS400 Ship Date", field:"AS400 Ship Date", sorter:"date", align:"center", width:100},
                {title:"Exp. Ship", field:"Est Ship", sorter:"date", align:"center", width:100, headerSort:false},
                //{title:"QC", field:"QC", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Pole Barn", field:"Pole Barn", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Thermoforming", field:"Thermoforming", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Vinyl/Paint", field:"Vinyl/Paint", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"FA1", field:"Fnl Asmb 1", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"FA2", field:"Fnl Asmb 2", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Crating", field:"Crating", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Shipping", field:"Shipping", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"New", field:"New", visible:false},
                {title:"Revised", field:"Revised", visible:false},
            ],
            ajaxResponse:function(url, params, response) {
                var obj = JSON.parse(JSON.stringify(response)); //parse response
                var array_to_output = obj['tabulator_get_session'];

                console.debug(obj['tabulator_get_session']);
                console.debug(obj['current_page']);

                return response;
            },

            rowFormatter:function(row) {

                var data = row.getData();
                var data = JSON.parse(JSON.stringify(row.getData()));
                var orderNew = data['New'];
                var orderRevised = data['Revised'];

                if ( orderNew == 1 ) {
                    row.getElement().style.backgroundColor = "#69db88";
                    row.getElement().style.fontWeight = "bold";
                }

                if ( orderRevised == 1 ) {
                    row.getElement().style.backgroundColor = "#dbd069";
                    row.getElement().style.fontWeight = "bold";
                    row.getElement().style.fontStyle = "italic";
                }

            },
            placeholder:"No Data Available", //display message to user on empty table

        });
</code>```

I would have left a comment instead of editing the post. But the website won't allow me to.

答:
Try the following  codeblock for Version 4.6:

```<code>        //define new tabulator instance
        var table = new Tabulator("#production-data-table", {
            ajaxURL:"scripts/order_status.php?action=fetch_production_data", //ajax URL
            pagination:"remote",
            persistenceMode: "local",
            persistenceID: "production-data",
            persistence: {
                 sort: true, //persist column sorting
                 filter: true, //persist filter sorting
                 group: true, //persist row grouping
                 page: true, //persist page
                 columns: true, //persist columns
            },
            ajaxFiltering:true,
            ajaxSorting:true,
            layout:"fitColumns",
            columns:[
                {title:"Enterprise", field:"Enterprise", sorter:"string", width:100, headerSort:false},
                {title:"Job Number", field:"Job Number", sorter:"number", width:100, headerSort:false},
                {title:"LN #", field:"LN #", sorter:"string", formatter:"html", align:'center', width:80, headerSort:false},
                {title:"Description", field:"Description", sorter:"string", headerSort:false},
                {title:"QTY", field:"QTY", sorter:"string", headerSort:false, align: 'center', width: 40,},
                {title:"AS400 Ship Date", field:"AS400 Ship Date", sorter:"date", align:"center", width:100},
                {title:"Exp. Ship", field:"Est Ship", sorter:"date", align:"center", width:100, headerSort:false},
                //{title:"QC", field:"QC", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Pole Barn", field:"Pole Barn", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Thermoforming", field:"Thermoforming", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Vinyl/Paint", field:"Vinyl/Paint", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"FA1", field:"Fnl Asmb 1", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"FA2", field:"Fnl Asmb 2", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Crating", field:"Crating", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Shipping", field:"Shipping", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"New", field:"New", visible:false},
                {title:"Revised", field:"Revised", visible:false},
            ],
            ajaxResponse:function(url, params, response) {
                var obj = JSON.parse(JSON.stringify(response)); //parse response
                var array_to_output = obj['tabulator_get_session'];

                console.debug(obj['tabulator_get_session']);
                console.debug(obj['current_page']);

                return response;
            },

            rowFormatter:function(row) {

                var data = row.getData();
                var data = JSON.parse(JSON.stringify(row.getData()));
                var orderNew = data['New'];
                var orderRevised = data['Revised'];

                if ( orderNew == 1 ) {
                    row.getElement().style.backgroundColor = "#69db88";
                    row.getElement().style.fontWeight = "bold";
                }

                if ( orderRevised == 1 ) {
                    row.getElement().style.backgroundColor = "#dbd069";
                    row.getElement().style.fontWeight = "bold";
                    row.getElement().style.fontStyle = "italic";
                }

            },
            placeholder:"No Data Available", //display message to user on empty table
            //ajaxLoaderError:"<div>New Error new error new error</div>",
            dataLoaded: function(data) {
                table.setPage(<?=$_SESSION['tabulator_get']['pagination']['current_page']?>);
            },

        });
</code>```

This should allow you to store the table state in localStorage for easy use.

Documentation Link: http://tabulator.info/docs/4.6/persist

EDIT:

After doing some looking at the code block, it seems as if you are missing some required arguments for remote pagination. See docs here: http://tabulator.info/docs/4.6/page#remote

Title: Create Page Persistence with Tabulator

Body:
I'm trying to enable a user to be able to leave the page with Tabulator on it and come back and it loads the same view they had before (including the page they were on, filters, and sorters they had enabled).

I have tried making it work using Tabulator's persist feature (as suggested below) but I get an error of: Pagination Error - Requested page is out of range of 1 - 1: 3

        //define new tabulator instance
        var table = new Tabulator("#production-data-table", {
            ajaxURL:"scripts/order_status.php?action=fetch_production_data", //ajax URL
            pagination:"remote",
            persistenceMode: "local",
            persistenceID: "production-data",
            persistence: {
                 sort: true, //persist column sorting
                 filter: true, //persist filter sorting
                 group: true, //persist row grouping
                 page: true, //persist page
                 columns: true, //persist columns
            },
            ajaxFiltering:true,
            ajaxSorting:true,
            layout:"fitColumns",
            columns:[
                {title:"Enterprise", field:"Enterprise", sorter:"string", width:100, headerSort:false},
                {title:"Job Number", field:"Job Number", sorter:"number", width:100, headerSort:false},
                {title:"LN #", field:"LN #", sorter:"string", formatter:"html", align:'center', width:80, headerSort:false},
                {title:"Description", field:"Description", sorter:"string", headerSort:false},
                {title:"QTY", field:"QTY", sorter:"string", headerSort:false, align: 'center', width: 40,},
                {title:"AS400 Ship Date", field:"AS400 Ship Date", sorter:"date", align:"center", width:100},
                {title:"Exp. Ship", field:"Est Ship", sorter:"date", align:"center", width:100, headerSort:false},
                //{title:"QC", field:"QC", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Pole Barn", field:"Pole Barn", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Thermoforming", field:"Thermoforming", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Vinyl/Paint", field:"Vinyl/Paint", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"FA1", field:"Fnl Asmb 1", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"FA2", field:"Fnl Asmb 2", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Crating", field:"Crating", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Shipping", field:"Shipping", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"New", field:"New", visible:false},
                {title:"Revised", field:"Revised", visible:false},
            ],
            ajaxResponse:function(url, params, response) {
                var obj = JSON.parse(JSON.stringify(response)); //parse response
                var array_to_output = obj['tabulator_get_session'];

                console.debug(obj['tabulator_get_session']);
                console.debug(obj['current_page']);

                return response;
            },

            rowFormatter:function(row) {

                var data = row.getData();
                var data = JSON.parse(JSON.stringify(row.getData()));
                var orderNew = data['New'];
                var orderRevised = data['Revised'];

                if ( orderNew == 1 ) {
                    row.getElement().style.backgroundColor = "#69db88";
                    row.getElement().style.fontWeight = "bold";
                }

                if ( orderRevised == 1 ) {
                    row.getElement().style.backgroundColor = "#dbd069";
                    row.getElement().style.fontWeight = "bold";
                    row.getElement().style.fontStyle = "italic";
                }

            },
            placeholder:"No Data Available", //display message to user on empty table

        });

I would have left a comment instead of editing the post. But the website won't allow me to.

Body:
Try the following  codeblock for Version 4.6:

        //define new tabulator instance
        var table = new Tabulator("#production-data-table", {
            ajaxURL:"scripts/order_status.php?action=fetch_production_data", //ajax URL
            pagination:"remote",
            persistenceMode: "local",
            persistenceID: "production-data",
            persistence: {
                 sort: true, //persist column sorting
                 filter: true, //persist filter sorting
                 group: true, //persist row grouping
                 page: true, //persist page
                 columns: true, //persist columns
            },
            ajaxFiltering:true,
            ajaxSorting:true,
            layout:"fitColumns",
            columns:[
                {title:"Enterprise", field:"Enterprise", sorter:"string", width:100, headerSort:false},
                {title:"Job Number", field:"Job Number", sorter:"number", width:100, headerSort:false},
                {title:"LN #", field:"LN #", sorter:"string", formatter:"html", align:'center', width:80, headerSort:false},
                {title:"Description", field:"Description", sorter:"string", headerSort:false},
                {title:"QTY", field:"QTY", sorter:"string", headerSort:false, align: 'center', width: 40,},
                {title:"AS400 Ship Date", field:"AS400 Ship Date", sorter:"date", align:"center", width:100},
                {title:"Exp. Ship", field:"Est Ship", sorter:"date", align:"center", width:100, headerSort:false},
                //{title:"QC", field:"QC", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Pole Barn", field:"Pole Barn", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Thermoforming", field:"Thermoforming", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Vinyl/Paint", field:"Vinyl/Paint", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"FA1", field:"Fnl Asmb 1", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"FA2", field:"Fnl Asmb 2", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Crating", field:"Crating", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"Shipping", field:"Shipping", sorter:"string", formatter:"html", align:'center', width:101, resizable:false, headerSort:false},
                {title:"New", field:"New", visible:false},
                {title:"Revised", field:"Revised", visible:false},
            ],
            ajaxResponse:function(url, params, response) {
                var obj = JSON.parse(JSON.stringify(response)); //parse response
                var array_to_output = obj['tabulator_get_session'];

                console.debug(obj['tabulator_get_session']);
                console.debug(obj['current_page']);

                return response;
            },

            rowFormatter:function(row) {

                var data = row.getData();
                var data = JSON.parse(JSON.stringify(row.getData()));
                var orderNew = data['New'];
                var orderRevised = data['Revised'];

                if ( orderNew == 1 ) {
                    row.getElement().style.backgroundColor = "#69db88";
                    row.getElement().style.fontWeight = "bold";
                }

                if ( orderRevised == 1 ) {
                    row.getElement().style.backgroundColor = "#dbd069";
                    row.getElement().style.fontWeight = "bold";
                    row.getElement().style.fontStyle = "italic";
                }

            },
            placeholder:"No Data Available", //display message to user on empty table
            //ajaxLoaderError:"<div>New Error new error new error</div>",
            dataLoaded: function(data) {
                table.setPage(<?=$_SESSION['tabulator_get']['pagination']['current_page']?>);
            },

        });

This should allow you to store the table state in localStorage for easy use.

Documentation Link: http://tabulator.info/docs/4.6/persist

EDIT:

After doing some looking at the code block, it seems as if you are missing some required arguments for remote pagination. See docs here: http://tabulator.info/docs/4.6/page#remote


问:
Python module shows up in pip freeze, but cannot be imported
I'm in Win10 and use vanilla Python 3.7.3 (e.g. not conda or anything). I had a successful pip install for the package, the package shows up in pip freeze, and the package is supposed to be compatible with my version of Python. I've seen several threads with similar issues on OS X and Linux, and have tried to emulate their solutions on Windows, but no luck. I'm guessing it could be an issue with my PATH variable, but I'm not quite sure. The error I get when trying to import is the "No module named" error.</p>

答: Went into site-packages...for some reason the module was named Bio there (everywhere else it's named biopython, again, including pip freeze) and importing that worked. Not sure if this was just a bad dev choice or what. </p>


问:
How do I convert a Django QuerySet into list of dicts?
How can I convert a Django QuerySet into a list of dicts? I haven't found an answer to this so I'm wondering if I'm missing some sort of common helper function that everyone uses.

答:
You could define a function using model_to_dict as follows:

```<code>from django.forms.models import model_to_dict
def queryset_to_list(qs,fields=None, exclude=None):
    return [model_to_dict(x,fields,exclude) for x in qs]
</code>```

Suppose your Model has the following fields

```<code>id
name
email
</code>```

Run the following commands in Django shell

```<code>>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_list(qs)
>>>list
[{'id':1, 'name':'abc', 'email':'abc@ab.co'},{'id':2, 'name':'xyz', 'email':'xy@xy.co'}]
</code>```

Say you want only the id and the name in the list of queryset dictionary

```<code>>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_list(qs,fields=['id','name'])
>>>list
[{'id':1, 'name':'abc'},{'id':2, 'name':'xyz'}]
</code>```

Similarly, you can exclude fields in your output.

Body:
You could define a function using model_to_dict as follows:

from django.forms.models import model_to_dict
def queryset_to_list(qs,fields=None, exclude=None):
    return [model_to_dict(x,fields,exclude) for x in qs]

Suppose your Model has the following fields

id
name
email

Run the following commands in Django shell

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_list(qs)
>>>list
[{'id':1, 'name':'abc', 'email':'abc@ab.co'},{'id':2, 'name':'xyz', 'email':'xy@xy.co'}]

Say you want only the id and the name in the list of queryset dictionary

>>>qs=<yourmodel>.objects.all()
>>>list=queryset_to_list(qs,fields=['id','name'])
>>>list
[{'id':1, 'name':'abc'},{'id':2, 'name':'xyz'}]

Similarly, you can exclude fields in your output.


问:
Using Draft js mention plugin with react hooks
I have been trying to get draft js mention plugin to work with react hooks but can't seem to figure what's wrong with the code. Appreciate any help on this.</p>

```<code>import React, { useRef, useState, useEffect } from "react";
import { EditorState } from "draft-js";
import Editor from "draft-js-plugins-editor";
import createMentionPlugin, { defaultSuggestionsFilter } from "draft-js-mention-plugin";
import mentions from "./mentions";

export default function MentionEditor() {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const [suggestions, setSuggestions] = useState(mentions);
  const editor = useRef(null);

  useEffect(() => {
    editor.current.focus();
  }, [])

  const mentionPlugin = createMentionPlugin();
  const { MentionSuggestions } = mentionPlugin;
  const plugins = [mentionPlugin];

  const onSearchChange = ({ value }) => {
    setSuggestions(defaultSuggestionsFilter(value, mentions))
  };

  return (
    <div style={{ border: "1px solid gray" }}>
      <Editor
        editorState={editorState}
        onChange={editorState => setEditorState(editorState)}
        plugins={plugins}
        ref={editor}
      />
      <MentionSuggestions
        onSearchChange={onSearchChange}
        suggestions={suggestions}
      />
    </div>
  );
}
</code>```

答:
Just move these lines outside component and it will work:</p>

```<code>  const mentionPlugin = createMentionPlugin();
  const { MentionSuggestions } = mentionPlugin;
  const plugins = [mentionPlugin];

export default function MentionEditor() {
        const [editorState, setEditorState] = useState(EditorState.createEmpty());
.. ... ...
}
</code>```

Body:
I have been trying to get draft js mention plugin to work with react hooks but can't seem to figure what's wrong with the code. Appreciate any help on this.

import React, { useRef, useState, useEffect } from "react";
import { EditorState } from "draft-js";
import Editor from "draft-js-plugins-editor";
import createMentionPlugin, { defaultSuggestionsFilter } from "draft-js-mention-plugin";
import mentions from "./mentions";

export default function MentionEditor() {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());
  const [suggestions, setSuggestions] = useState(mentions);
  const editor = useRef(null);

  useEffect(() => {
    editor.current.focus();
  }, [])

  const mentionPlugin = createMentionPlugin();
  const { MentionSuggestions } = mentionPlugin;
  const plugins = [mentionPlugin];

  const onSearchChange = ({ value }) => {
    setSuggestions(defaultSuggestionsFilter(value, mentions))
  };

  return (

      <Editor
        editorState={editorState}
        onChange={editorState => setEditorState(editorState)}
        plugins={plugins}
        ref={editor}
      />
      <MentionSuggestions
        onSearchChange={onSearchChange}
        suggestions={suggestions}
      />

  );
}

Body:
Just move these lines outside component and it will work:

  const mentionPlugin = createMentionPlugin();
  const { MentionSuggestions } = mentionPlugin;
  const plugins = [mentionPlugin];

export default function MentionEditor() {
        const [editorState, setEditorState] = useState(EditorState.createEmpty());
.. ... ...
}


问:
Getting refs to rendered videos in FlatList
I have an application where I am rendering a video component using expo-video-player via FlatList as this list could grow in the future and I want to keep things optimized as possible.

What I want to accomplish is that when I click to play on one video in the list, all others will pause if they are playing.  I'm using all functional components and typically if it wasn't in a FlatList could reference a video with the following:

```<code>const videoRef = useRef(null);

...

<Video
   ref={videoRef}
   ...
/>
</code>```

and then call videoRef.current.pauseAsync() to pause it somewhere else in my code.

However, now that it is in a FlatList I am having trouble understanding how to link the ref for each video and be able to get the ref back to call pauseAsync() on the previous video that is playing.

Any direction/guidance would be appreciated.

答:
How need to create a Array of Refs.

I would use a code link this:

const videoRefs = [];

const videos = ['url.com/xyz.mp4', 'url.com/abc.mp4'];

videos.forEach((video, index) => {
  videoRefs.push(useRef(null));
});

...

renderItem = ({item, index}) => {
  <Video
     ref={videoRefs[index]}
     ...
  />
}
```

Body:
I have an application where I am rendering a video component using expo-video-player via FlatList as this list could grow in the future and I want to keep things optimized as possible.

What I want to accomplish is that when I click to play on one video in the list, all others will pause if they are playing.  I'm using all functional components and typically if it wasn't in a FlatList could reference a video with the following:

const videoRef = useRef(null);

...

<Video
   ref={videoRef}
   ...
/>

and then call videoRef.current.pauseAsync() to pause it somewhere else in my code.

However, now that it is in a FlatList I am having trouble understanding how to link the ref for each video and be able to get the ref back to call pauseAsync() on the previous video that is playing.

Any direction/guidance would be appreciated.


问:
Difference between two date strings in java
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

```<code>public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }
</code>```

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

```<code>try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.

答: java.util.Calendar has a method add, that takes a quantity and a unit of time, and a method called compareTo, that takes another calendar. You should be using those.

Body:
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.


问:
I am trying to add a UILabel exactly like I already have but keep getting this error
I am trying to add a label to my calculator where it shows the tip amount but I keep getting

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I just want it to display the tip amount as well. I copied it exact for the other UILabel.

```<code>
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var PriceTxt: UITextField!
    @IBOutlet weak var Tip: UITextField!
    @IBOutlet weak var totalFinal: UILabel!
    @IBOutlet weak var TipAmount: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        totalFinal.text = ""
        TipAmount.text = ""
    }

    @IBAction func Calcualte(_ sender: Any) {
        if  PriceTxt.text! == "" || Tip.text! == ""
        {
            totalFinal.text = "Input the Numbers"
            TipAmount.text = ""
        }

        else {
        let price = Double(PriceTxt.text!)!
        let tipPer = Double(Tip.text!)!
        let TipMult =  price * (tipPer/100)
        let TipFinal = Double((round(100*TipMult)/100) + price)
        totalFinal.text = "$\(TipFinal)"
        TipAmount.text = "$\(TipMult)"
    }

}
}
</code>```

答:
Try using ? instead of !

! force unwraps and gives you a fatal error if there is no value (nil). ? only unwraps if a value is present.

Also, why unwrap the text here at all?

Use
PriceTxt.text == "" || Tip.text == "" without the ! or ?.

Body:
I am trying to add a label to my calculator where it shows the tip amount but I keep getting

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

I just want it to display the tip amount as well. I copied it exact for the other UILabel.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var PriceTxt: UITextField!
    @IBOutlet weak var Tip: UITextField!
    @IBOutlet weak var totalFinal: UILabel!
    @IBOutlet weak var TipAmount: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        totalFinal.text = ""
        TipAmount.text = ""
    }

    @IBAction func Calcualte(_ sender: Any) {
        if  PriceTxt.text! == "" || Tip.text! == ""
        {
            totalFinal.text = "Input the Numbers"
            TipAmount.text = ""
        }

        else {
        let price = Double(PriceTxt.text!)!
        let tipPer = Double(Tip.text!)!
        let TipMult =  price * (tipPer/100)
        let TipFinal = Double((round(100*TipMult)/100) + price)
        totalFinal.text = "$\(TipFinal)"
        TipAmount.text = "$\(TipMult)"
    }

}
}


问:
How do I pass a MouseEvent parameter in a QML signal
I'm trying to propagate the MouseArea signals to a parent object, but using MouseEvent as the parameter type causes an import error.</p>

```<code>import QtQuick 2.0
import org.kde.plasma.core 2.0

Rectangle {
    id: linkRect

    signal clicked(MouseEvent mouse)

    ToolTipArea {
        id: tooltip
        anchors.fill: parent

        MouseArea {
            id: mouseArea
            anchors.fill: parent

            onClicked: linkRect.clicked(mouse)
        }
    }
}
</code>```

答:
Use QtObject instead of MouseEvent.

Also this works for KeyEvent parameter in KeyPressed event.

```<code>signal clicked(QtObject mouse)
</code>```

Note: The QtObject is base of these classes.

Body:
I'm trying to propagate the MouseArea signals to a parent object, but using MouseEvent as the parameter type causes an import error.

import QtQuick 2.0
import org.kde.plasma.core 2.0

Rectangle {
    id: linkRect

    signal clicked(MouseEvent mouse)

    ToolTipArea {
        id: tooltip
        anchors.fill: parent

        MouseArea {
            id: mouseArea
            anchors.fill: parent

            onClicked: linkRect.clicked(mouse)
        }
    }
}

Body:
Use QtObject instead of MouseEvent.

Also this works for KeyEvent parameter in KeyPressed event.

signal clicked(QtObject mouse)

Note: The QtObject is base of these classes.


问:
Group values and remove duplicates of groups based on a column in Pandas
I have a datafile which is the result of combining several sources that contain name information. Each name have a unique ID (Column ID).
Sorting the ID by column, I would like to remove the second/third source finding in the column Source.

My output today:

(all the red rows are "duplicates" since we already got them from the first source (blue rows))

What I would like to achieve:

How can I achieve this result?
Is there a way to iterate row by row, where I remove duplicate of ID already when I iterate in the function "for file in files:" part of the code?
Or is it easier to do it in the "df_merged" before I output the dataframe to an  an excel file?.

Code:

```<code>import pandas as pd
import os
from datetime import datetime
from shutil import copyfile
from functools import reduce
import numpy as np

#Path
base_path = "G:/Till/"

# Def
def get_files(folder, filetype):
    list_files = []
    directory = os.fsencode(folder)
    for file in os.listdir(directory):
        filename = os.fsdecode(file)
        if filename.endswith("." + filetype.strip().lower()):
            list_files.append(filename)
    return list_files

# export files
df_result_e = pd.DataFrame()

files = get_files(base_path + "datasource/" + "export","xlsx")
df_append_e = pd.DataFrame()

for file in files:
    df_temp = pd.read_excel(base_path + "datasource/" + "export/" + file, "Results", dtype=str, index=False)
    df_temp["Source"] = file
    df_append_e = pd.concat([df_append_e, df_temp])

df_result_e = pd.concat([df_result_e, df_append_e])

print(df_result_e)

# match files
df_result_m = pd.DataFrame()

files = get_files(base_path + "datasource/" + "match","xlsx")
df_append_m = pd.DataFrame()

for file in files:
    df_temp = pd.read_excel(base_path + "datasource/" + "match/" + file, "Page 1", dtype=str, index=False)
    df_append_m = pd.concat([df_append_m, df_temp])

df_result_m = pd.concat([df_result_m, df_append_m])
df_result_m = df_result_m[['ID_Our','Name_Our','Ext ID']]
df_result_m.rename(columns={'ID_Our' : 'ID', 'Name_Our' : 'Name' , 'Ext ID' : 'Match ID'}, inplace=True)
df_result_m.dropna(subset=["Match ID"], inplace=True) # Drop all NA

data_frames = [df_result_e, df_result_m]

# Join files
df_merged = reduce(lambda  left,right: pd.merge(left, right, on=["Match ID"], how='outer'), data_frames)

#Output of files
df_merged.to_excel(base_path + "Total datasource Export/" +  datetime.now().strftime("%Y-%m-%d_%H%M") + ".xlsx", index=False)
</code>```

答:
For remove them you can try transform with factorize

```<code>newdf=df[df.groupby('ID')['Source'].transform(lambda x : x.factorize()[0])==0]
</code>```

Body:
I have a datafile which is the result of combining several sources that contain name information. Each name have a unique ID (Column ID).
Sorting the ID by column, I would like to remove the second/third source finding in the column Source.

My output today:

(all the red rows are "duplicates" since we already got them from the first source (blue rows))

What I would like to achieve:

How can I achieve this result?
Is there a way to iterate row by row, where I remove duplicate of ID already when I iterate in the function "for file in files:" part of the code?
Or is it easier to do it in the "df_merged" before I output the dataframe to an  an excel file?.

Code:

import pandas as pd
import os
from datetime import datetime
from shutil import copyfile
from functools import reduce
import numpy as np

#Path
base_path = "G:/Till/"

# Def
def get_files(folder, filetype):
    list_files = []
    directory = os.fsencode(folder)
    for file in os.listdir(directory):
        filename = os.fsdecode(file)
        if filename.endswith("." + filetype.strip().lower()):
            list_files.append(filename)
    return list_files

# export files
df_result_e = pd.DataFrame()

files = get_files(base_path + "datasource/" + "export","xlsx")
df_append_e = pd.DataFrame()

for file in files:
    df_temp = pd.read_excel(base_path + "datasource/" + "export/" + file, "Results", dtype=str, index=False)
    df_temp["Source"] = file
    df_append_e = pd.concat([df_append_e, df_temp])

df_result_e = pd.concat([df_result_e, df_append_e])

print(df_result_e)

# match files
df_result_m = pd.DataFrame()

files = get_files(base_path + "datasource/" + "match","xlsx")
df_append_m = pd.DataFrame()

for file in files:
    df_temp = pd.read_excel(base_path + "datasource/" + "match/" + file, "Page 1", dtype=str, index=False)
    df_append_m = pd.concat([df_append_m, df_temp])

df_result_m = pd.concat([df_result_m, df_append_m])
df_result_m = df_result_m[['ID_Our','Name_Our','Ext ID']]
df_result_m.rename(columns={'ID_Our' : 'ID', 'Name_Our' : 'Name' , 'Ext ID' : 'Match ID'}, inplace=True)
df_result_m.dropna(subset=["Match ID"], inplace=True) # Drop all NA

data_frames = [df_result_e, df_result_m]

# Join files
df_merged = reduce(lambda  left,right: pd.merge(left, right, on=["Match ID"], how='outer'), data_frames)

#Output of files
df_merged.to_excel(base_path + "Total datasource Export/" +  datetime.now().strftime("%Y-%m-%d_%H%M") + ".xlsx", index=False)

Body:
For remove them you can try transform with factorize

newdf=df[df.groupby('ID')['Source'].transform(lambda x : x.factorize()[0])==0]


问:
Kotlin reified issue with parameterized type
Why does the following not work?
It seems that the type Foo is not passed properly, or is this just a well known "issue"?

Foo<T> fails

data class Foo<T>(val a: T)
data class Bar(val b: String)
val objectMapper = ObjectMapper().registerKotlinModule()
val jsonString = "{\"a\": { \"b\": \"str\" }}"
fun main() {
    val parseJson = parseJson<Bar>()
}
private inline fun <reified T> parseJson(): T {
    val readValue: Foo<T> = objectMapper.readValue(jsonString)
    return readValue.a
}
```

```class java.util.LinkedHashMap cannot be cast to class ..Bar
(java.util.LinkedHashMap is in module java.base of loader 'bootstrap';
..Bar is in unnamed module of loader 'app')
```

答:
The issue in this case is that you're not specifying the class that ObjectMapper should try and map your jsonString to. The matter is further complicated by the Foo type being parametric.

You need to build a JavaType reference to pass to objectMapper.readValue.

private inline fun <reified T> parseJson(): T {
    val javaType = objectMapper.typeFactory.constructParametricType(Foo::class.java, T::class.java)
    val readValue: Foo<T> = objectMapper.readValue(jsonString, javaType)
    return readValue.a
}
```

Body:
Why does the following not work?
It seems that the type Foo is not passed properly, or is this just a well known "issue"?

Foo<T> fails

data class Foo<T>(val a: T)
data class Bar(val b: String)
val objectMapper = ObjectMapper().registerKotlinModule()
val jsonString = "{\"a\": { \"b\": \"str\" }}"
fun main() {
    val parseJson = parseJson<Bar>()
}
private inline fun <reified T> parseJson(): T {
    val readValue: Foo<T> = objectMapper.readValue(jsonString)
    return readValue.a
}

class java.util.LinkedHashMap cannot be cast to class ..Bar
(java.util.LinkedHashMap is in module java.base of loader 'bootstrap';
..Bar is in unnamed module of loader 'app')


问:
Convert af::array to af_array and back
I would like to use the ArrayFire library to run multiple artificial neural networks on the GPU in parallel.

Since I am mainly a C# developer I tried to realize it via SiaNet. But I encountered the problem that SiaNet can only run one neural network at a time.

This is because SiaNet and the C# API of ArrayFire do not implement the batchFunc function.

I wanted to make up for this and built my own little library.
There I call the batchFunc function and want to build an API which can be called from C# with PInvokes.

The problem is that I can only use af_array from C#, but the batchFunc function can only process af::array. Therefore I need to convert one into the other.

My MatrixMultiply function, to have a function that I can pass batchFunc:

```<code>af::array MatrixMultiply(const af::array &lhs, const af::array &rhs) {
    return matmul(lhs, rhs);
}
</code>```

My PInvoke friendly function:

```<code>af_err BatchMatmul(af_array *out, const af::array lhs, const af::array rhs) {
    try
    {
    *out = &(af::batchFunc(lhs, rhs, MatrixMultiply));

    return AF_SUCCESS;
    }
    catch (af::exception& e) {
    fprintf(stderr, "%s\n", e.what());
    return AF_ERR_BATCH;
    }
}
</code>```

As I call it on C# side:

```<code>[DllImport("BatchOpsWrapperLib.dll", ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
public static extern af_err BatchMatmul(out IntPtr array_out, IntPtr array_lhs, IntPtr array_rhs);
</code>```

I have hardly or not at all worked with C/C++ so far and would like to ask you for help here.

Edit:
This is my reworked new function:

```<code>af_err BatchMatmul(af_array *out, const af_array lhs, const af_array rhs)
{
    try
    {
        af_array retainedLhs = 0;
        af_array retainedRhs = 0;

        af_retain_array(&retainedLhs, lhs);
        af_retain_array(&retainedRhs, rhs);

        af_array resultHandle = 0;

        af_retain_array(&resultHandle, af::batchFunc(af::array(retainedLhs),
                                                     af::array(retainedRhs),
                                                     MatrixMultiply).get());

        *out = resultHandle;

        return AF_SUCCESS;
    }
    catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
        return AF_ERR_BATCH;
    }
}
</code>```

答:
An af::array instance has a method .get(), from which you can retrieve an af_array instance.

```<code>af::array some_array = ...;
af_array c_array = some_array.get();
</code>```

You can also construct an af::array from an af_array using af::array(some_af_array).

```<code>af::array another_array = af::array(c_array);`
</code>```

Title: Convert af::array to af_array and back

Body:
I would like to use the ArrayFire library to run multiple artificial neural networks on the GPU in parallel.

Since I am mainly a C# developer I tried to realize it via SiaNet. But I encountered the problem that SiaNet can only run one neural network at a time.

This is because SiaNet and the C# API of ArrayFire do not implement the batchFunc function.

I wanted to make up for this and built my own little library.
There I call the batchFunc function and want to build an API which can be called from C# with PInvokes.

The problem is that I can only use af_array from C#, but the batchFunc function can only process af::array. Therefore I need to convert one into the other.

My MatrixMultiply function, to have a function that I can pass batchFunc:

af::array MatrixMultiply(const af::array &lhs, const af::array &rhs) {
    return matmul(lhs, rhs);
}

My PInvoke friendly function:

af_err BatchMatmul(af_array *out, const af::array lhs, const af::array rhs) {
    try
    {
    *out = &(af::batchFunc(lhs, rhs, MatrixMultiply));

    return AF_SUCCESS;
    }
    catch (af::exception& e) {
    fprintf(stderr, "%s\n", e.what());
    return AF_ERR_BATCH;
    }
}

As I call it on C# side:

[DllImport("BatchOpsWrapperLib.dll", ExactSpelling = true, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
public static extern af_err BatchMatmul(out IntPtr array_out, IntPtr array_lhs, IntPtr array_rhs);

I have hardly or not at all worked with C/C++ so far and would like to ask you for help here.

Edit:
This is my reworked new function:

af_err BatchMatmul(af_array *out, const af_array lhs, const af_array rhs)
{
    try
    {
        af_array retainedLhs = 0;
        af_array retainedRhs = 0;

        af_retain_array(&retainedLhs, lhs);
        af_retain_array(&retainedRhs, rhs);

        af_array resultHandle = 0;

        af_retain_array(&resultHandle, af::batchFunc(af::array(retainedLhs),
                                                     af::array(retainedRhs),
                                                     MatrixMultiply).get());

        *out = resultHandle;

        return AF_SUCCESS;
    }
    catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
        return AF_ERR_BATCH;
    }
}

Body:
An af::array instance has a method .get(), from which you can retrieve an af_array instance.

af::array some_array = ...;
af_array c_array = some_array.get();

You can also construct an af::array from an af_array using af::array(some_af_array).

af::array another_array = af::array(c_array);`


问:
my table does not show table border and hyperlink
my table does not show table border and hyperlink, I am using thymeleaf and spring boot. I see the data from database when i type localhost:8080 without border, I should also see a Addbutton link in that page, but it  is not shown.</p>

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Employee Management System</title>

 <link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
 integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
 crossorigin="anonymous">

</head>
<body>

<div class ="container my-2">

    <h1>Employees List</h1>
    <a th:href="@{/showNewEmployeeForm}" class="btn btn-primary btn-sm mb-3"> Add Employee </a>

    <table border="1" class="table table-striped table-responsive-md">
</code>```

答:
Can you try this</p>

```<code><div class='table-responsive'>
<table class="table table-striped border-1">
     //your table data
</table>
</div>
</code>```

Body:
my table does not show table border and hyperlink, I am using thymeleaf and spring boot. I see the data from database when i type localhost:8080 without border, I should also see a Addbutton link in that page, but it  is not shown.

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Employee Management System</title>

 <link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
 integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
 crossorigin="anonymous">

Employees List

     Add Employee

Body:
Can you try this

<div class='table-responsive'>
<table class="table table-striped border-1">
     //your table data
</table>
</div>


问:
How to recursively list all the files in a directory in C#?
How to recursively list all the files in a directory and child directories in C#?</p>

答:
Shortest record</p>
```<code>string[] files = Directory.GetFiles(@"your_path", "*.jpg", SearchOption.AllDirectories);
</code>```

OwnerDisplayName: Arjab

Body:
Shortest record

string[] files = Directory.GetFiles(@"your_path", "*.jpg", SearchOption.AllDirectories);


问:
WinDbg can't load extension
I am having some trouble loading an extension in WinDbg preview. The extension code can be found here.

At present when I run .extpath I get the default path and the extension is saved in C:\Users\user\AppData\Local\Dbg\EngineExtensions32 however whenever I execute .chain the dll is extension is never loaded and attempting to load the extension manually results in the error The engine has been disconnected unexpectedly.

How do I get this extension to load correctly?

As a side note to this on many applications when I attach to them with WinDbg and attempt to load sos.dll I just get the following output and nothing I have found online such as this or this has been able to rectify this:

.cordll -u -ve -l
CLRDLL: No CLR image loaded (i.e. mscorwks.dll)
CLR DLL status: No load attempts

How do I get the CLR SOS dll to load automatically each time WinDbg starts?

答:
You are asking for help with 2 issues, so here are two answers. On this site we prefer one question at a time.

How do I get this extension to load correctly?

In the link you provided there is a note:

Though I believe I resolved the issue, it may be necessary that you copy the extension to the very same folder where WinDBG is located.

I could reproduce your issue and it was indeed fixed when I copied all the compilation artifacts into the WinDbg directory.

I've opened an issue on the Github repository for that.

How do I get the CLR SOS dll to load automatically each time WinDbg starts?

Loading SOS is not trivial for several reasons:

SOS cannot be loaded when WinDbg starts. It also needs a debugging session, so it either needs to be attached to a running program, a crash dump needs to be opened or a new process needs to be started. This means, you either need the -z to load a crash dump, -p to attach py PID, -pn to attach by process name or give the name of an executable.

SOS cannot be loaded at the initial breakpoint, because .NET is not available yet and it's unclear which version of SOS to load.

You need to run WinDbg in the correct bitness for SOS to load, otherwise it will fail with a bitness mismatch (something like BadImageFormatException in .NET).

depending on the .NET version, we need to load SOS where clr, coreclr or mscorwks is. Even worse, in some cases the .NET DLL is not even named correctly (e.g. mscorwks_64800000)

when using quotes, we might need to escape these quotes correctly

With that knowledge given, you can now construct a small script and pass that to WinDbg with the -c argument. But let's first identify what needs to be done.

First, we can simply try all .NET versions. two of them will fail and one of them will likely succeed if .NET was loaded. The three commands are

```<code>.loadby sos clr
.loadby sos coreclr
.loadby sos mscorwks
</code>```

Now, we need to do that when .NET is loaded. It's fine for crash dumps or processes  which have .NET already running. This will not work for processes started from scratch.

So, for the easy cases we have a command line like

```<code>windbg.exe -c ".loadby sos clr;.loadby sos coreclr;.loadby sos mscorwks" -z crash.dmp
windbg.exe -c ".loadby sos clr;.loadby sos coreclr;.loadby sos mscorwks" -p PID
windbg.exe -c ".loadby sos clr;.loadby sos coreclr;.loadby sos mscorwks" -pn name
</code>```

Things get more complicated for starting new processes. Typically you could do it like

```<code>sxe -c".loadby sos clr;g" ld clr
</code>```

to load SOS as early as the CLR DLL was loaded. Unfortunately, you can only have one ld breakpoint at a time and you can only specify one module. But, we can work around this by setting three unresolved breakpoints:

```<code>bu clr!EEStartup ".loadby sos clr;g"
bu mscorwks!EEStartup ".loadby sos mscorwks;g"
bu coreclr!EEStartup ".loadby sos coreclr;g"
</code>```

Note that we run into ugly escaping problems with the quotes here. These cannot be resolved using double quotes (""), caret quotes (^") or other things we know from the command line. That's why we need to write a script. The command line is then

```<code>windbg -c "$$<loadsos.dbg;g" notepad.exe
</code>```

where $$< is the command to run a script with the given name. That file then contains the needed commands

```<code>.loadby sos clr
.loadby sos coreclr
.loadby sos mscorwks
bu clr!EEStartup ".loadby sos clr;g"
bu mscorwks!EEStartup ".loadby sos mscorwks;g"
bu coreclr!EEStartup ".loadby sos coreclr;g"
</code>```

Title: WinDbg can't load extension

Body:
You are asking for help with 2 issues, so here are two answers. On this site we prefer one question at a time.

How do I get this extension to load correctly?

In the link you provided there is a note:

Though I believe I resolved the issue, it may be necessary that you copy the extension to the very same folder where WinDBG is located.

I could reproduce your issue and it was indeed fixed when I copied all the compilation artifacts into the WinDbg directory.

I've opened an issue on the Github repository for that.

How do I get the CLR SOS dll to load automatically each time WinDbg starts?

Loading SOS is not trivial for several reasons:

SOS cannot be loaded when WinDbg starts. It also needs a debugging session, so it either needs to be attached to a running program, a crash dump needs to be opened or a new process needs to be started. This means, you either need the -z to load a crash dump, -p to attach py PID, -pn to attach by process name or give the name of an executable.

SOS cannot be loaded at the initial breakpoint, because .NET is not available yet and it's unclear which version of SOS to load.

You need to run WinDbg in the correct bitness for SOS to load, otherwise it will fail with a bitness mismatch (something like BadImageFormatException in .NET).

depending on the .NET version, we need to load SOS where clr, coreclr or mscorwks is. Even worse, in some cases the .NET DLL is not even named correctly (e.g. mscorwks_64800000)

when using quotes, we might need to escape these quotes correctly

With that knowledge given, you can now construct a small script and pass that to WinDbg with the -c argument. But let's first identify what needs to be done.

First, we can simply try all .NET versions. two of them will fail and one of them will likely succeed if .NET was loaded. The three commands are

.loadby sos clr
.loadby sos coreclr
.loadby sos mscorwks

Now, we need to do that when .NET is loaded. It's fine for crash dumps or processes  which have .NET already running. This will not work for processes started from scratch.

So, for the easy cases we have a command line like

windbg.exe -c ".loadby sos clr;.loadby sos coreclr;.loadby sos mscorwks" -z crash.dmp
windbg.exe -c ".loadby sos clr;.loadby sos coreclr;.loadby sos mscorwks" -p PID
windbg.exe -c ".loadby sos clr;.loadby sos coreclr;.loadby sos mscorwks" -pn name

Things get more complicated for starting new processes. Typically you could do it like

sxe -c".loadby sos clr;g" ld clr

to load SOS as early as the CLR DLL was loaded. Unfortunately, you can only have one ld breakpoint at a time and you can only specify one module. But, we can work around this by setting three unresolved breakpoints:

bu clr!EEStartup ".loadby sos clr;g"
bu mscorwks!EEStartup ".loadby sos mscorwks;g"
bu coreclr!EEStartup ".loadby sos coreclr;g"

Note that we run into ugly escaping problems with the quotes here. These cannot be resolved using double quotes (""), caret quotes (^") or other things we know from the command line. That's why we need to write a script. The command line is then

windbg -c "$$<loadsos.dbg;g" notepad.exe

where $$< is the command to run a script with the given name. That file then contains the needed commands

.loadby sos clr
.loadby sos coreclr
.loadby sos mscorwks
bu clr!EEStartup ".loadby sos clr;g"
bu mscorwks!EEStartup ".loadby sos mscorwks;g"
bu coreclr!EEStartup ".loadby sos coreclr;g"


问:
Creating a stacked-grouped barplot with different categories per bar ggplot?
I have four variables: categories, x, y and z. X axis should be categories and there should be two bars per category, with the first one being x stacked on top of z, and the second one being y stacked on top of z. It should look like the image linked here (z is blue): </p>

```<code>sampledata <- data.frame(
  categories = c("2017", "2018", "2019", "2020"),
  x = c(2, 3, 0, 4),
  y = c(0, 2, 1, 4),
  z = c(1, 0 ,2 ,3)
)
</code>```

答:
Technically, there is no way to directly combine stacked and dodged style in geom_bar. But maybe you can do this trick:

```<code>#Your data frame
sampledata <- data.frame(
  categories = c("2017", "2018", "2019", "2020"),
  x = c(2, 3, 0, 4),
  y = c(0, 2, 1, 4),
  z = c(1, 0 ,2 ,3)
)
#Reshape into tidy data
library(tidyverse)
sampledata2<-sampledata %>%
  gather('x','y','z',key='variable',value='value')%>%
  mutate(group=ifelse(variable=='y','b','a')) #group into 2 groups (xz and yz)
sampledata2[13:16,]<-sampledata2[9:12,]
sampledata2[13:16,4]<-c('b','b','b','b')
sampledataA<-sampledata2 %>%
  filter(group=='a')
sampledataB<-sampledata2 %>%
  filter(group=='b')
#plot
barwidth=0.30
ggplot()+
#geom_bar for x and z
  geom_bar(data=sampledataA,
          mapping=aes(fill=variable,y=value,x=categories),
          position="stack",
          stat="identity",
          width=barwidth)+
#geom_bar for y and z
geom_bar(data=sampledataB,
          mapping=aes(x=as.numeric(categories)+barwidth+0.1,fill=variable,y=value),
          position="stack",
          stat="identity",
          width=barwidth)
</code>```

more information if it doesn't work: https://community.rstudio.com/t/ggplot-position-dodge-with-position-stack/16425

Body:
I have four variables: categories, x, y and z. X axis should be categories and there should be two bars per category, with the first one being x stacked on top of z, and the second one being y stacked on top of z. It should look like the image linked here (z is blue):

sampledata <- data.frame(
  categories = c("2017", "2018", "2019", "2020"),
  x = c(2, 3, 0, 4),
  y = c(0, 2, 1, 4),
  z = c(1, 0 ,2 ,3)
)

Body:
Technically, there is no way to directly combine stacked and dodged style in geom_bar. But maybe you can do this trick:

#Your data frame
sampledata <- data.frame(
  categories = c("2017", "2018", "2019", "2020"),
  x = c(2, 3, 0, 4),
  y = c(0, 2, 1, 4),
  z = c(1, 0 ,2 ,3)
)
#Reshape into tidy data
library(tidyverse)
sampledata2<-sampledata %>%
  gather('x','y','z',key='variable',value='value')%>%
  mutate(group=ifelse(variable=='y','b','a')) #group into 2 groups (xz and yz)
sampledata2[13:16,]<-sampledata2[9:12,]
sampledata2[13:16,4]<-c('b','b','b','b')
sampledataA<-sampledata2 %>%
  filter(group=='a')
sampledataB<-sampledata2 %>%
  filter(group=='b')
#plot
barwidth=0.30
ggplot()+
#geom_bar for x and z
  geom_bar(data=sampledataA,
          mapping=aes(fill=variable,y=value,x=categories),
          position="stack",
          stat="identity",
          width=barwidth)+
#geom_bar for y and z
geom_bar(data=sampledataB,
          mapping=aes(x=as.numeric(categories)+barwidth+0.1,fill=variable,y=value),
          position="stack",
          stat="identity",
          width=barwidth)

more information if it doesn't work: https://community.rstudio.com/t/ggplot-position-dodge-with-position-stack/16425