问:
Invoke Secured (https) REST API endpoint from WSO2 Integration Studio/Micro Integrator
I am trying to invoke a secured endpoint (https) from wso2 integration studio8.0/MI 4.0. Created integration project, created an endpoint with the url with secured endpoint address, provided on header with the transport scope as required for the secured endpoint. I got the public key certificate (.p7b/.cer) and imported to the trust store using key tool utility.
keytool -import -alias aliasName -file public-key-from-browser.cer -keystore client-truststore.jks -storepass password. Provided the truststore file path in deployment.toml in integration studio/MI4.0 but getting the following exception. Please let me know how to resolve the exception.

```<code>[2022-01-17 10:28:09,696] ERROR {TargetHandler} - I/O error: General SSLEngine problem javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1566)
    at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:545)
    at sun.security.ssl.SSLEngineImpl.writeAppRecord(SSLEngineImpl.java:1217)
    at sun.security.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:1185)
    at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:471)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.doWrap(SSLIOSession.java:270)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:316)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.isAppInputReady(SSLIOSession.java:541)
    at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:120)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:162)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:337)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:276)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
    at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:591)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:198)
    at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1729)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:333)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:325)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1688)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:226)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1082)
    at sun.security.ssl.Handshaker$1.run(Handshaker.java:1015)
    at sun.security.ssl.Handshaker$1.run(Handshaker.java:1012)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.security.ssl.Handshaker$DelegatedTask.run(Handshaker.java:1504)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.doRunTask(SSLIOSession.java:288)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:356)
    ... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:450)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:317)
    at sun.security.validator.Validator.validate(Validator.java:262)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:330)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:289)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:144)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1675)
</code>```

答:
Make sure that you have imported the chain of certificates. If you have already done that better to enable ssl debug logs [1] and analyse the ssl logs to identify what is the exact cause of the issue.

[1]-https://dilsichandrasena.medium.com/how-to-enable-ssl-debug-logs-for-wso2-products-6de7276ffe10

Body:
I am trying to invoke a secured endpoint (https) from wso2 integration studio8.0/MI 4.0. Created integration project, created an endpoint with the url with secured endpoint address, provided on header with the transport scope as required for the secured endpoint. I got the public key certificate (.p7b/.cer) and imported to the trust store using key tool utility.
keytool -import -alias aliasName -file public-key-from-browser.cer -keystore client-truststore.jks -storepass password. Provided the truststore file path in deployment.toml in integration studio/MI4.0 but getting the following exception. Please let me know how to resolve the exception.

[2022-01-17 10:28:09,696] ERROR {TargetHandler} - I/O error: General SSLEngine problem javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1566)
    at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:545)
    at sun.security.ssl.SSLEngineImpl.writeAppRecord(SSLEngineImpl.java:1217)
    at sun.security.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:1185)
    at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:471)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.doWrap(SSLIOSession.java:270)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:316)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.isAppInputReady(SSLIOSession.java:541)
    at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:120)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:162)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:337)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
    at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:276)
    at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
    at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:591)
    at java.lang.Thread.run(Thread.java:748)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:198)
    at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1729)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:333)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:325)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1688)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:226)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1082)
    at sun.security.ssl.Handshaker$1.run(Handshaker.java:1015)
    at sun.security.ssl.Handshaker$1.run(Handshaker.java:1012)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.security.ssl.Handshaker$DelegatedTask.run(Handshaker.java:1504)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.doRunTask(SSLIOSession.java:288)
    at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:356)
    ... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:450)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:317)
    at sun.security.validator.Validator.validate(Validator.java:262)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:330)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:289)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:144)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1675)


来源: stackexchange

问:
How to transform table data to dataframe in R
I have csv file containing 3 columns: name, position and plays (plays has value 1 if player plays at that position, otherwise has value 0). One player can play more than one position. There are no two players with the same name. Sample data:

```<code>Brian,goalkeeper,0
Brian,fullback,1
Brian,playmaker,1
Brian,centerback,0
Brian,striker,0
Teddy,goalkeeper,0
Teddy,fullback,0
Teddy,playmaker,1
Teddy,centerback,1
Teddy,striker,1
Alan,goalkeeper,1
Alan,fullback,0
Alan,playmaker,0
Alan,centerback,1
Alan,striker,0
</code>```

I want to transform this data to data frame, to have names in rows, positions as column names, and values 0/1 as data in cells.

```<code>players <-read.csv("players.csv", sep=",", stringsAsFactors = FALSE)
</code>```

command

```<code>table1 <-    table(players$name,players$position,players$plays)
</code>```

gives me two tables

```<code>        centerback fullback goalkeeper playmaker striker
  Alan           0        1          0         1       1
  Brian          1        0          1         0       1
  Teddy          0        1          1         0       0

and
        centerback fullback goalkeeper playmaker striker
  Alan           1        0          1         0       0
  Brian          0        1          0         1       0
  Teddy          1        0          0         1       1
</code>```

(Why is table function doing this?, second one is correct for me). How is it possible to transform table1 to data frame, to have player names in rows, positions as column names, and values 0/1 as data in cells?

答:
table is giving you an 3-D array because you have 3-variables to take into consideration, You need to drop one of them, ie only subset to get where plays == 1 then do a table on that.

```<code>as.data.frame.matrix(table(subset(players, plays == 1, -plays)))
      centerback fullback goalkeeper playmaker striker
Alan           1        0          1         0       0
Brian          0        1          0         1       0
Teddy          1        0          0         1       1
</code>```

Or you could also use xtabs as below:

```<code>as.data.frame.matrix(xtabs(plays~name + position, players))
      centerback fullback goalkeeper playmaker striker
Alan           1        0          1         0       0
Brian          0        1          0         1       0
Teddy          1        0          0         1       1
</code>```

If you need the names as a column, use reshape:

```<code>reshape(df, timevar = 'position', idvar = 'name', direction = 'wide', sep='_')
    name plays_goalkeeper plays_fullback plays_playmaker plays_centerback plays_striker
1  Brian                0              1               1                0             0
6  Teddy                0              0               1                1             1
11  Alan                1              0               0                1             0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have csv file containing 3 columns: name, position and plays (plays has value 1 if player plays at that position, otherwise has value 0). One player can play more than one position. There are no two players with the same name. Sample data:

Brian,goalkeeper,0
Brian,fullback,1
Brian,playmaker,1
Brian,centerback,0
Brian,striker,0
Teddy,goalkeeper,0
Teddy,fullback,0
Teddy,playmaker,1
Teddy,centerback,1
Teddy,striker,1
Alan,goalkeeper,1
Alan,fullback,0
Alan,playmaker,0
Alan,centerback,1
Alan,striker,0

I want to transform this data to data frame, to have names in rows, positions as column names, and values 0/1 as data in cells.

players <-read.csv("players.csv", sep=",", stringsAsFactors = FALSE)

command

table1 <-    table(players$name,players$position,players$plays)

gives me two tables

        centerback fullback goalkeeper playmaker striker
  Alan           0        1          0         1       1
  Brian          1        0          1         0       1
  Teddy          0        1          1         0       0

and
        centerback fullback goalkeeper playmaker striker
  Alan           1        0          1         0       0
  Brian          0        1          0         1       0
  Teddy          1        0          0         1       1

(Why is table function doing this?, second one is correct for me). How is it possible to transform table1 to data frame, to have player names in rows, positions as column names, and values 0/1 as data in cells?

Body:
table is giving you an 3-D array because you have 3-variables to take into consideration, You need to drop one of them, ie only subset to get where plays == 1 then do a table on that.

as.data.frame.matrix(table(subset(players, plays == 1, -plays)))
      centerback fullback goalkeeper playmaker striker
Alan           1        0          1         0       0
Brian          0        1          0         1       0
Teddy          1        0          0         1       1

Or you could also use xtabs as below:

as.data.frame.matrix(xtabs(plays~name + position, players))
      centerback fullback goalkeeper playmaker striker
Alan           1        0          1         0       0
Brian          0        1          0         1       0
Teddy          1        0          0         1       1

If you need the names as a column, use reshape:

reshape(df, timevar = 'position', idvar = 'name', direction = 'wide', sep='_')
    name plays_goalkeeper plays_fullback plays_playmaker plays_centerback plays_striker
1  Brian                0              1               1                0             0
6  Teddy                0              0               1                1             1
11  Alan                1              0               0                1             0


问:
getting error when trying start server in pywebio 1.5.2
I get this error:

```<code>Traceback (most recent call last):
  File "C:\Users\website\Desktop\collector.py", line 10, in <module>
    start_server(636)
  File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\tornado.py", line 360, in start_server
    handler = webio_handler(applications, cdn, allowed_origins=allowed_origins, check_origin=check_origin,
  File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\tornado.py", line 236, in webio_handler
    applications = make_applications(applications)
  File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\page.py", line 171, in make_applications
    assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
AssertionError: Don't support application type:<class 'int'>
</code>```

my code:

```<code>from time import sleep
from pywebio.input import *
from pywebio.output import *
from pywebio import start_server

import pandas

pandas.options.display.max_rows = 6000
pandas.set_option('display.float_format', lambda x: '%.0f' % x)

a = pandas.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv",
    delimiter=",",
    )

out = (a[["location",  "new_cases", "total_cases","new_deaths","total_deaths"]].to_string().replace('\n','\n'+' '*12))
out1 = '{:<11} {}'.format('',out)

Titles1 = out1.replace("location", "Location")
Titles2 = Titles1.replace("new_cases", "New Cases")
Titles3 = Titles2.replace("total_deaths", "Total Deaths")
Titles4 = Titles3.replace("total_cases", "Total Cases")
Titles5 = Titles4.replace("new_deaths", "New deaths")
No0 = Titles5.replace(".0", "")
print(No0)
put_code(No0)
start_server(636)
</code>```

what I do wrong? Please sorry if somebody asking this question but I can't find answer in Google.
Thanks for suggestions because I'm newbie on this forum :)
Thank you in advance!

答:
Your error comes from this line:

```<code>start_server(636)
</code>```

Note that from the documentation, start_server()'s first argument applications must be a  list or a dict or a callable

```<code>pywebio.platform.tornado.start_server(applications, port=0, host='', debug=False, cdn=True, static_dir=None, remote_access=False, reconnect_timeout=0, allowed_origins=None, check_origin=None, auto_open_webbrowser=False, max_payload_size='200M', **tornado_app_settings)
</code>```

applications (list/dict/callable)

PyWebIO application. Can be a task function, a list of functions, or a dictionary. Refer to Advanced topic: Multiple applications in start_server() for more information.

When the task function is a coroutine function, use Coroutine-based session implementation, otherwise, use thread-based session implementation.

The error is telling you that you gave an argument of an unsupported type (int) to the application argument.

AssertionError: Don't support application type:<class 'int'>

If you meant for 636 to be the port on which your server runs, it needs to be the second argument, or passed as a keyword argument.

Body:
I get this error:

Traceback (most recent call last):
  File "C:\Users\website\Desktop\collector.py", line 10, in <module>
    start_server(636)
  File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\tornado.py", line 360, in start_server
    handler = webio_handler(applications, cdn, allowed_origins=allowed_origins, check_origin=check_origin,
  File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\tornado.py", line 236, in webio_handler
    applications = make_applications(applications)
  File "C:\Users\website\AppData\Local\Programs\Python\Python310\lib\site-packages\pywebio\platform\page.py", line 171, in make_applications
    assert iscoroutinefunction(app) or isgeneratorfunction(app) or callable(app), \
AssertionError: Don't support application type:<class 'int'>

my code:

from time import sleep
from pywebio.input import *
from pywebio.output import *
from pywebio import start_server

import pandas

pandas.options.display.max_rows = 6000
pandas.set_option('display.float_format', lambda x: '%.0f' % x)

a = pandas.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/latest/owid-covid-latest.csv",
    delimiter=",",
    )

out = (a[["location",  "new_cases", "total_cases","new_deaths","total_deaths"]].to_string().replace('\n','\n'+' '*12))
out1 = '{:<11} {}'.format('',out)

Titles1 = out1.replace("location", "Location")
Titles2 = Titles1.replace("new_cases", "New Cases")
Titles3 = Titles2.replace("total_deaths", "Total Deaths")
Titles4 = Titles3.replace("total_cases", "Total Cases")
Titles5 = Titles4.replace("new_deaths", "New deaths")
No0 = Titles5.replace(".0", "")
print(No0)
put_code(No0)
start_server(636)

what I do wrong? Please sorry if somebody asking this question but I can't find answer in Google.
Thanks for suggestions because I'm newbie on this forum :)
Thank you in advance!

Body:
Your error comes from this line:

start_server(636)

Note that from the documentation, start_server()'s first argument applications must be a  list or a dict or a callable

pywebio.platform.tornado.start_server(applications, port=0, host='', debug=False, cdn=True, static_dir=None, remote_access=False, reconnect_timeout=0, allowed_origins=None, check_origin=None, auto_open_webbrowser=False, max_payload_size='200M', **tornado_app_settings)

applications (list/dict/callable)

PyWebIO application. Can be a task function, a list of functions, or a dictionary. Refer to Advanced topic: Multiple applications in start_server() for more information.

When the task function is a coroutine function, use Coroutine-based session implementation, otherwise, use thread-based session implementation.

The error is telling you that you gave an argument of an unsupported type (int) to the application argument.

AssertionError: Don't support application type:<class 'int'>

If you meant for 636 to be the port on which your server runs, it needs to be the second argument, or passed as a keyword argument.


问:
VB.NET Class Shared Function or Instance function
Just wondering what is the best practice when using functions or properties.
I have a class

```<code>Class Person
    Property FirstName as String
    Property LastName as String

    'code to use
    Return $"{LastName.ToUpper}, {FirstName}"
End Class
</code>```

What's the best way?

ReadOnly Property FullName as String

Function FullName as String

Shared Function FullName(p as Person) as String

My understanding is 3 would be better as 1 or 2 would be part of the object, but there is nothing unique in what they do to an object, so the same code would be duplicated for every Person object.

答:
At the time of writing this answer, there is a vote to close your question on the basis that it is "likely to be answered with opinions rather than facts and citations". About your 3. this is surely not the case because a shared member alone can only access shared members directly so it is out of the question. As for 1. and 2., this is what they would look like:

```<code>Class Person

    Public Property FirstName as String
    Public Property LastName as String

    Public Function GetFullName() As String
        Return $"{LastName.ToUpper}, {FirstName}"
    End Function

    Public ReadOnly Property FullName As String
        Public Get
            Return $"{LastName.ToUpper}, {FirstName}"
        End
    End Property

End Class
</code>```

Calling them:

Dim p As New Person() With {.FirstName = "John", .LastName = "Doe"}
Console.WriteLine(p.GetFullName())
Console.WriteLine(p.FullName)
```
<blockquote>
<p>DOE, John
<br>DOE, John</p>
</blockquote>
<p>Both do the same thing. Here comes the opinion part:</p>
<p>I prefer the property in this case because it doesn't do much work. I expect a method to do a little more work behind the scenes - I wouldn't expect a property to take much time to run, but am ok with a method delaying a bit - but that's a bit subjective. From this answer, <em>"Methods imply doing so action, while properties imply getting some data."</em> with which I agree (also with some other good info in the Q&A).</p>
<p>A way to pigeonhole a shared function into this answer would be to write a function which can be used by the instance members, but it can't access the name properties directly. As for the public API, the question is still between <code>1.</code> and <code>2.</code>. It may look something like this</p>
<pre class="lang-vb prettyprint-override"><code>Class Person

    Public Property FirstName As String
    Public Property LastName As String

    Public Function GetFullName() As String
        Return getFullName(FirstName, LastName)
    End Function

    Public ReadOnly Property FullName As String
        Get
            Return getFullName(FirstName, LastName)
        End Get
    End Property

    Private Shared Function getFullName(firstName As String, lastName As String)
        Return $"{lastName.ToUpper}, {firstName}"
    End Function

    Private Shared Function getFullName(p As Person)
        Return $"{p.LastName.ToUpper}, {p.FirstName}"
    End Function

End Class
</code>```

Body:
Just wondering what is the best practice when using functions or properties.
I have a class

Class Person
    Property FirstName as String
    Property LastName as String

    'code to use
    Return $"{LastName.ToUpper}, {FirstName}"
End Class

What's the best way?

ReadOnly Property FullName as String

Function FullName as String

Shared Function FullName(p as Person) as String

My understanding is 3 would be better as 1 or 2 would be part of the object, but there is nothing unique in what they do to an object, so the same code would be duplicated for every Person object.

Body:
At the time of writing this answer, there is a vote to close your question on the basis that it is "likely to be answered with opinions rather than facts and citations". About your 3. this is surely not the case because a shared member alone can only access shared members directly so it is out of the question. As for 1. and 2., this is what they would look like:

Class Person

    Public Property FirstName as String
    Public Property LastName as String

    Public Function GetFullName() As String
        Return $"{LastName.ToUpper}, {FirstName}"
    End Function

    Public ReadOnly Property FullName As String
        Public Get
            Return $"{LastName.ToUpper}, {FirstName}"
        End
    End Property

End Class

Calling them:

Dim p As New Person() With {.FirstName = "John", .LastName = "Doe"}
Console.WriteLine(p.GetFullName())
Console.WriteLine(p.FullName)

DOE, John

DOE, John

Both do the same thing. Here comes the opinion part:

I prefer the property in this case because it doesn't do much work. I expect a method to do a little more work behind the scenes - I wouldn't expect a property to take much time to run, but am ok with a method delaying a bit - but that's a bit subjective. From this answer, "Methods imply doing so action, while properties imply getting some data." with which I agree (also with some other good info in the Q&A).

A way to pigeonhole a shared function into this answer would be to write a function which can be used by the instance members, but it can't access the name properties directly. As for the public API, the question is still between 1. and 2.. It may look something like this

Class Person

    Public Property FirstName As String
    Public Property LastName As String

    Public Function GetFullName() As String
        Return getFullName(FirstName, LastName)
    End Function

    Public ReadOnly Property FullName As String
        Get
            Return getFullName(FirstName, LastName)
        End Get
    End Property

    Private Shared Function getFullName(firstName As String, lastName As String)
        Return $"{lastName.ToUpper}, {firstName}"
    End Function

    Private Shared Function getFullName(p As Person)
        Return $"{p.LastName.ToUpper}, {p.FirstName}"
    End Function

End Class


问:
Get all Arguments | Minecraft Spigot plugin
Heyy! How can I get all args from a sender? I want to code a little execute a command from a player plugin. Here is the code:

```<code>import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class runitcmd implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (sender.hasPermission("penguplayercommands.use")){
            if (args.length > 0) {
                String pName = args[0];
                Player p = Bukkit.getPlayer(pName);
                p.performCommand(args[1]+++allother);
            }
        }else {
            sender.sendMessage("§b[PenguCraft] §aYour rank is not allowed to do this.");
        }

        return false;
    }
}
</code>```

at   p.performCommand(args[1]+++allother); it should do all args after the first one.
Can anyone help me?

答:
You can do something like that :

StringJoiner sj = new StringJoiner(" "); // object that you manage all args
for(int i = 1; i < args.length; i++) // for all arg between 0 and max arg length
   sj.add(args[i]); // add arg
p.performCommand(sj.toString()); // here is your final command
```
<p><strong>Update:</strong></p>
<p>There is a quicky way, <code>String.join</code> that should be use like that:</p>
<pre class="lang-java prettyprint-override"><code>p.performCommand(String.join(" ", args));
</code>```

Body:
Heyy! How can I get all args from a sender? I want to code a little execute a command from a player plugin. Here is the code:

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class runitcmd implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (sender.hasPermission("penguplayercommands.use")){
            if (args.length > 0) {
                String pName = args[0];
                Player p = Bukkit.getPlayer(pName);
                p.performCommand(args[1]+++allother);
            }
        }else {
            sender.sendMessage("§b[PenguCraft] §aYour rank is not allowed to do this.");
        }

        return false;
    }
}

at   p.performCommand(args[1]+++allother); it should do all args after the first one.
Can anyone help me?

Body:
You can do something like that :

StringJoiner sj = new StringJoiner(" "); // object that you manage all args
for(int i = 1; i < args.length; i++) // for all arg between 0 and max arg length
   sj.add(args[i]); // add arg
p.performCommand(sj.toString()); // here is your final command

Update:

There is a quicky way, String.join that should be use like that:

p.performCommand(String.join(" ", args));


问:
generating lists from google sheet

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

答:
This will generate lists based on row values. NaN should be excluded while doing the task.

```<code>import pandas as pd
import numpy as np
df = pd.read_excel('sample.xlsx')

total_no = df.loc[~df['No'].isnull(),'No'].tolist()  #adding total No. values (excluding NaN)
total_topic = []
list_1= []
list_2 = []
for num,topic in zip(df['No'].tolist(), df['Topic'].tolist()):
    if num in total_no:
        total_topic.append(topic)
    elif type(topic) == float:  #excluding NaN for topics
        continue
    else:
        list_1.append(total_topic[-1])
        list_2.append(topic)

print(list_1)
print(list_2)
</code>```

Title: generating lists from google sheet

Body:
This will generate lists based on row values. NaN should be excluded while doing the task.

import pandas as pd
import numpy as np
df = pd.read_excel('sample.xlsx')

total_no = df.loc[~df['No'].isnull(),'No'].tolist()  #adding total No. values (excluding NaN)
total_topic = []
list_1= []
list_2 = []
for num,topic in zip(df['No'].tolist(), df['Topic'].tolist()):
    if num in total_no:
        total_topic.append(topic)
    elif type(topic) == float:  #excluding NaN for topics
        continue
    else:
        list_1.append(total_topic[-1])
        list_2.append(topic)

print(list_1)
print(list_2)


问:
Not able to pick ancestor Tag attribute value using XLST
Source XML for the XSLT issue statement.

```<code><College>
    <Student>
            <Name>ABC</Name>
            <Age>25<Age>
    </Student>
    <Result>
            <account>
               <accountNumber>1111</accountNumber>
            </account>
            <account>
               <accountNumber>2222</accountNumber>
            </account>
    </Result>
    </College>
</code>```

Current issue is that I am unable to pull Age from first Tag and add to the next tag in XSLT.

```<code>Below is the Desired O/P
    <College>
    <Student>
            <Name>ABC</Name>
            <Age>25<Age>
    </Student>
    <Result>
            <account>
               <accountNumber>1111</accountNumber>
               <Age>25<Age>
            </account>
            <account>
               <accountNumber>2222</accountNumber>
               <Age>25<Age>
            </account>
    </Result>
    </College>
</code>```

Current XSLT

```<code>    <xsl:template match = "Student">
            <Name><xsl:value-of select="Name" /></Name>
            <Age><xsl:value-of select="Age" /></Age>
    </xsl:template>

    <xsl:template match = "Result/account">
      <Student>
        <accountNumber><xsl:value-of select="accountNumber" /></accountNumber>
        <Age></Age> // Not sure how to add this here from earlier tag.
      </Student>
    </xsl:template>
</code>```

I am unable to use preceding-sibling as the tag isn't present under the same node. Need a way to refer the old node and pick the age value and insert in the new tag.

答:
I would suggest you do it this way:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="account">
    <xsl:copy>
        <xsl:copy-of select="accountNumber"/>
        <xsl:copy-of select="../preceding-sibling::Student[1]/Age"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

This is assuming there are multiple pairs of Student and Result, where each Result follows the relevant Student. Otherwise it could be simpler.

Body:
Source XML for the XSLT issue statement.

<College>
    <Student>
            <Name>ABC</Name>
            <Age>25<Age>
    </Student>
    <Result>
            <account>
               <accountNumber>1111</accountNumber>
            </account>
            <account>
               <accountNumber>2222</accountNumber>
            </account>
    </Result>
    </College>

Current issue is that I am unable to pull Age from first Tag and add to the next tag in XSLT.

Below is the Desired O/P
    <College>
    <Student>
            <Name>ABC</Name>
            <Age>25<Age>
    </Student>
    <Result>
            <account>
               <accountNumber>1111</accountNumber>
               <Age>25<Age>
            </account>
            <account>
               <accountNumber>2222</accountNumber>
               <Age>25<Age>
            </account>
    </Result>
    </College>

Current XSLT

    <xsl:template match = "Student">
            <Name><xsl:value-of select="Name" /></Name>
            <Age><xsl:value-of select="Age" /></Age>
    </xsl:template>

    <xsl:template match = "Result/account">
      <Student>
        <accountNumber><xsl:value-of select="accountNumber" /></accountNumber>
        <Age></Age> // Not sure how to add this here from earlier tag.
      </Student>
    </xsl:template>

I am unable to use preceding-sibling as the tag isn't present under the same node. Need a way to refer the old node and pick the age value and insert in the new tag.

Body:
I would suggest you do it this way:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="account">
    <xsl:copy>
        <xsl:copy-of select="accountNumber"/>
        <xsl:copy-of select="../preceding-sibling::Student[1]/Age"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

This is assuming there are multiple pairs of Student and Result, where each Result follows the relevant Student. Otherwise it could be simpler.


问:
mongorestore - AtlasError - getting non-bucket system collections is unsupported

Failed: (AtlasError) getting non-bucket system collections is unsupported

I'm trying to use mongorestore to migrate data from one database to another. Both on Atlas. The dump is working fine, but mongorestore is outputting the below messages. I have no clue what this means and a google search renders nothing remotely close. I've added hyphens to the beginning of each line of the output to make it more readable.

-- using write concern: &{majority false 0}
-- will listen for SIGTERM, SIGINT, and SIGKILL
-- connected to node type: replset
-- The --db and --collection flags are deprecated for this use-case; please use --nsInclude instead, i.e. with --nsInclude=${DATABASE}.${COLLECTION}
-- got error from options parsing: (AtlasError) getting non-bucket system collections is unsupported
-- Failed: (AtlasError) getting non-bucket system collections is unsupported
-- 0 document(s) restored successfully. 0 document(s) failed to restore.
```
<p>The command I'm running</p>
```mongorestore --uri="mongodb+srv://username:password@hostname.mongodb.net/$DEV_DATABASE" \
  --preserveUUID \
  --drop \
  --nsFrom="$PROD_DATABASE.*" \
  --nsTo="$DEV_DATABASE.*" \
  --verbose \
  "dump/$PROD_DATABASE"
```

I've also tried creating an archive file with mongodump and using that with --archive="filename", as well as piping stdout to mongorestore. I've also checked that the user I'm using has the correct privileges. They have the role of Atlas admin, which I'm assuming is correct. The dev cluster I'm trying to restore to is an M0 if that makes any difference.

I should also point out that I have minimal Mongo management experience, so I'm sure there's something I've overlooked. Thanks for your help.

答:
MongoDB records the collection UUIDs in a separate system collection.

The --preserveUUID option instructs mongorestore to create the collection, and force it to use the UUID from the source system.

The error message indicates that Atlas is refusing to allow you to access or modify that system collection.

Run without the --preserveUUID option when restoring to Atlas.

Body:
Failed: (AtlasError) getting non-bucket system collections is unsupported

I'm trying to use mongorestore to migrate data from one database to another. Both on Atlas. The dump is working fine, but mongorestore is outputting the below messages. I have no clue what this means and a google search renders nothing remotely close. I've added hyphens to the beginning of each line of the output to make it more readable.

-- using write concern: &{majority false 0}
-- will listen for SIGTERM, SIGINT, and SIGKILL
-- connected to node type: replset
-- The --db and --collection flags are deprecated for this use-case; please use --nsInclude instead, i.e. with --nsInclude=${DATABASE}.${COLLECTION}
-- got error from options parsing: (AtlasError) getting non-bucket system collections is unsupported
-- Failed: (AtlasError) getting non-bucket system collections is unsupported
-- 0 document(s) restored successfully. 0 document(s) failed to restore.

The command I'm running

mongorestore --uri="mongodb+srv://username:password@hostname.mongodb.net/$DEV_DATABASE" \
  --preserveUUID \
  --drop \
  --nsFrom="$PROD_DATABASE.*" \
  --nsTo="$DEV_DATABASE.*" \
  --verbose \
  "dump/$PROD_DATABASE"

I've also tried creating an archive file with mongodump and using that with --archive="filename", as well as piping stdout to mongorestore. I've also checked that the user I'm using has the correct privileges. They have the role of Atlas admin, which I'm assuming is correct. The dev cluster I'm trying to restore to is an M0 if that makes any difference.

I should also point out that I have minimal Mongo management experience, so I'm sure there's something I've overlooked. Thanks for your help.


问:
Spring CrudRepository Update doesn't work
I have a project in spring boot and I'm using CrudRepository, but when I try to update, it doesn't do anything.

```<code>@Entity
public class PfmSelection implements Serializable{

    @Id
    private Integer releaseId;
    private String preparedBy;
}
</code>```

Repositiry

```<code>@Repository
public interface IPfmSelectionDao extends CrudRepository<PfmSelection, Integer> {

}
</code>```

Service

```<code>public interface IPfmSelectionService {

    public PfmSelection save(PfmSelection pfmSelection);

    public PfmSelection findById(Integer id);

}
</code>```

Service Impl

```<code>@Service
public class PfmSelectionService implements IPfmSelectionService {

    @Autowired
    private IPfmSelectionDao pfmSelectionDao;

    @Override
    @Transactional
    public PfmSelection save(PfmSelection pfmSelection) {
        return this.pfmSelectionDao.save(pfmSelection);
    }

    @Override
    @Transactional(readOnly = true)
    public PfmSelection findById(Integer id) {
        return this.pfmSelectionDao.findById(id).orElse(null);
    }

}
</code>```

Service where I use the other Service

```<code>@Autowired
    private IPfmSelectionService pfmSelectionService;

private void updatePfm(PushModel pushModel) {
    PfmSelection pfm = this.pfmSelectionService.findById(167427);

     pfm.setPreparedBy("Rodrige");
     pfmSelectionService.save(pfm);

}
</code>```

I don't receive any error in the console.

答:
You need to take a few steps to know what the problem is

Take the return of pfmSelectionService.save(pfm) and print the saved instance returned like below:

```<code>private void updatePfm(PushModel pushModel) {
    PfmSelection pfm = this.pfmSelectionService.findById(167427);
    pfm.setPreparedBy("Rodrige");
    PfmSelection pfm2 = pfmSelectionService.save(pfm);
    System.out.println(pfm2.getPreparedBy());
}
</code>```

Put logger/debugger inside the save method, before and after the save method and check for the entry/exit sop/logger statements in log/console like

```<code>@Override
@Transactional
public PfmSelection save(PfmSelection pfmSelection) {
     System.out.println("Inside save method");
     PfmSelection pfmSelectionSaved =
                       this.pfmSelectionDao.save(pfmSelection);
     System.out.println("Exits save method");
     return pfmSelectionSaved;
}
</code>```

Check for any Aop around advice or any place where the exception is being caught but eaten/not thrown further.

Check if there is any update query fired in the logs at the time of save call.

Also check if the setter method pfm.setPreparedBy("Rodrige"); is Empty?

Body:
I have a project in spring boot and I'm using CrudRepository, but when I try to update, it doesn't do anything.

@Entity
public class PfmSelection implements Serializable{

    @Id
    private Integer releaseId;
    private String preparedBy;
}

Repositiry

@Repository
public interface IPfmSelectionDao extends CrudRepository<PfmSelection, Integer> {

}

Service

public interface IPfmSelectionService {

    public PfmSelection save(PfmSelection pfmSelection);

    public PfmSelection findById(Integer id);

}

Service Impl

@Service
public class PfmSelectionService implements IPfmSelectionService {

    @Autowired
    private IPfmSelectionDao pfmSelectionDao;

    @Override
    @Transactional
    public PfmSelection save(PfmSelection pfmSelection) {
        return this.pfmSelectionDao.save(pfmSelection);
    }

    @Override
    @Transactional(readOnly = true)
    public PfmSelection findById(Integer id) {
        return this.pfmSelectionDao.findById(id).orElse(null);
    }

}

Service where I use the other Service

@Autowired
    private IPfmSelectionService pfmSelectionService;

private void updatePfm(PushModel pushModel) {
    PfmSelection pfm = this.pfmSelectionService.findById(167427);

     pfm.setPreparedBy("Rodrige");
     pfmSelectionService.save(pfm);

}

I don't receive any error in the console.

Body:
You need to take a few steps to know what the problem is

Take the return of pfmSelectionService.save(pfm) and print the saved instance returned like below:

private void updatePfm(PushModel pushModel) {
    PfmSelection pfm = this.pfmSelectionService.findById(167427);
    pfm.setPreparedBy("Rodrige");
    PfmSelection pfm2 = pfmSelectionService.save(pfm);
    System.out.println(pfm2.getPreparedBy());
}

Put logger/debugger inside the save method, before and after the save method and check for the entry/exit sop/logger statements in log/console like

@Override
@Transactional
public PfmSelection save(PfmSelection pfmSelection) {
     System.out.println("Inside save method");
     PfmSelection pfmSelectionSaved =
                       this.pfmSelectionDao.save(pfmSelection);
     System.out.println("Exits save method");
     return pfmSelectionSaved;
}

Check for any Aop around advice or any place where the exception is being caught but eaten/not thrown further.

Check if there is any update query fired in the logs at the time of save call.

Also check if the setter method pfm.setPreparedBy("Rodrige"); is Empty?


问:
How to check if a point is in a quadrilateral made up of 4 points in Python?
What is the best way to do this only using python's built-in libraries?

Here is my code so far.

```<code>class Quadrilateral:

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y

    def __init__(self, Ax, Ay, Bx, By, Cx, Cy, Dx, Dy):
        self.A = self.Point(Ax, Ay)
        self.B = self.Point(Bx, By)
        self.C = self.Point(Cx, Cy)
        self.D = self.Point(Dx, Dy)

    # checks if a point is in the Quadrilateral
    def check(self, x, y):
        pass
</code>```

答:
This should do it (adapted to python and your case from there):

```<code>def check(self, testx, testy):
  vertx = [self.A.x, self.B.x, self.C.x, self.D.x]
  verty = [self.A.y, self.B.y, self.C.y, self.D.y]

  c = False
  j = len(vertx)-1

  for i in range(len(vertx)):
    if ( ((verty[i]>testy) != (verty[j]>testy)) and
     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ):
       c = not c

    j = i

  return c;
</code>```

What it does is "tracing" an horizontal ray starting from the test point and going to the right at infinity, and counting the number of times that ray crosses one of the segments. An even number means outside, an odd number means inside, hence the c = not c each time a new segment is crossed.

The second index j is there to close the quadrilateral.

It's both short and efficient and works both for convex and concave polygons.

This will work for n-polygon, so not only quadrilaterals.

Body:
What is the best way to do this only using python's built-in libraries?

Here is my code so far.

class Quadrilateral:

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y

    def __init__(self, Ax, Ay, Bx, By, Cx, Cy, Dx, Dy):
        self.A = self.Point(Ax, Ay)
        self.B = self.Point(Bx, By)
        self.C = self.Point(Cx, Cy)
        self.D = self.Point(Dx, Dy)

    # checks if a point is in the Quadrilateral
    def check(self, x, y):
        pass

Body:
This should do it (adapted to python and your case from there):

def check(self, testx, testy):
  vertx = [self.A.x, self.B.x, self.C.x, self.D.x]
  verty = [self.A.y, self.B.y, self.C.y, self.D.y]

  c = False
  j = len(vertx)-1

  for i in range(len(vertx)):
    if ( ((verty[i]>testy) != (verty[j]>testy)) and
     (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ):
       c = not c

    j = i

  return c;

What it does is "tracing" an horizontal ray starting from the test point and going to the right at infinity, and counting the number of times that ray crosses one of the segments. An even number means outside, an odd number means inside, hence the c = not c each time a new segment is crossed.

The second index j is there to close the quadrilateral.

It's both short and efficient and works both for convex and concave polygons.

This will work for n-polygon, so not only quadrilaterals.


问:
JavaScript If statement ERROR - null is not an object (evaluating
I am using TagUI(js based automation tool) and javascript, and while writing code to extract information from the a string I receive a  "null is not an object (evaluating 'd1.match(/(Internet provider)(.*)(
)/ig)[0];'

Where d1 can contain a couple of fields that I want to extract as parameters if a certain field is not available I would like to replace it with "not applicable"

examples:

```<code>d1 = "<p>please create a new entry.</p> <p>Person's name: Tom Jones<br/> Company: some company <br/> address: street one <br/> Employee ID: 07092120 <br/></p> "
OR
d1 = "<p>please create a new entry.</p> <p>Person's name: Jon Tomes<br/> Company: some company2 <br/> address: street two <br/><br/> Internet provider: O2 <br/> Employee ID: 07092121 <br/></p>"
</code>```

I have tried the following expressions with no luck

```<code>provider = d1.match(/(Internet provider)(.*)(<br\/>)/ig)[0];
</code>```
```<code>if (typeof ((d1.match(/(Internet provider)(.*)(<br\/>)/ig)[0]) === 'object' && (d1.match(/(Internet provider)(.*)(<br\/>)/ig)[0]) !== null)){provider=(d1.match(/(Internet provider)(.*)(<br\/>)/ig)[0]);}else{provider="not applicable"; }
</code>```
```<code>if (d1.match(/(Internet provider)(.*)(<br\/>)/ig)[0] !== null){provider="not applicable";}else{provider = d1.match(/(Internet provider)(.*)(<br\/>)/ig)[0];}
</code>```
```<code>if (typeof (provider = d1.match(/(Internet provider)(.*)(<br\/>)/ig)[0]) !== 'string'){provider="not applicable";}else{provider=d1.match(/(Internet provider)(.*)(<br\/>)/ig)[0]; }
</code>```

答:
@VLAZ's comment did the trick:

If .match() doesn't match anything, the result is null. .match()[0] would throw an error in that case.

Body:
I am using TagUI(js based automation tool) and javascript, and while writing code to extract information from the a string I receive a  "null is not an object (evaluating 'd1.match(/(Internet provider)(.*)(
)/ig)[0];'

Where d1 can contain a couple of fields that I want to extract as parameters if a certain field is not available I would like to replace it with "not applicable"

examples:

d1 = "
please create a new entry.

Person's name: Tom Jones
 Company: some company
 address: street one
 Employee ID: 07092120

 "
OR
d1 = "
please create a new entry.

Person's name: Jon Tomes
 Company: some company2
 address: street two

 Internet provider: O2
 Employee ID: 07092121

"

I have tried the following expressions with no luck

provider = d1.match(/(Internet provider)(.*)(
)/ig)[0];

if (typeof ((d1.match(/(Internet provider)(.*)(
)/ig)[0]) === 'object' && (d1.match(/(Internet provider)(.*)(
)/ig)[0]) !== null)){provider=(d1.match(/(Internet provider)(.*)(
)/ig)[0]);}else{provider="not applicable"; }

if (d1.match(/(Internet provider)(.*)(
)/ig)[0] !== null){provider="not applicable";}else{provider = d1.match(/(Internet provider)(.*)(
)/ig)[0];}

if (typeof (provider = d1.match(/(Internet provider)(.*)(
)/ig)[0]) !== 'string'){provider="not applicable";}else{provider=d1.match(/(Internet provider)(.*)(
)/ig)[0]; }


问:
text processing question: remove rows where one column does not contain a particular value
I have a tab delimited file that looks like this:

```<code>input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYSGGYEQY 1.00    33843   KTAYSHLSTSK polymerase  Hepatitis B virus (hepatitis B virus (HBV))
ASSYSGGYEQY ASSYSGGYEQY 1.00    131430  KLSYGIATV   orf1ab polyprotein [Severe acute respiratory syndrome coronavirus 2]    SARS-CoV2
ASSYSGGYEQY ASSFSGGYEQY 0.97    82603   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYAGGYEQY 0.98    133155  FVCNLLLLFVTVYSHLLLV ORF3a protein [Severe acute respiratory syndrome coronavirus 2] SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
</code>```

I want to keep 'input_sequence' that only match with 'organism' = SARS-CoV2 and nothing else. So in this example I would keep only line 2 and line 7 and discard lines 3,4,5,6 because here this 'input_sequence' has also a hit with Hepatitis B virus.

In total I have over 20.000 rows in my file.

results required:

```<code>input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
</code>```

Is there a way to quickly do this using awk or bash (without writing a long script)? Any tips are welcome.

I thought to use awk to count the occurences of each value in column 1 and occurences of SARS-COV2 in column 7, and then only keep those that match... but I don't know how to do this. I only got this far (counting the number of occurrences in column one):

```<code>awk '{for(i=1;i<=NF;i++)if($i ~ /^/)x++;print x;x=0}' file
</code>```

Thanks!

答:
awk '
    NR==1                              # Print first line (header)
    $NF != "SARS-CoV2" { bad[$1] }     # Collect primary keys of "bad"  records based on content in last field
    $NF == "SARS-CoV2" { good[$1]=$0 } # Collect primary keys of "good" records with opposite check
    END {
        for(v in bad) delete good[v]   # Remove primary keys from "good" records that also appear in "bad" records
        for(v in good) print good[v]   # Print the "good" rows
    }
' file
```

Passing the file once, this could potentially be a solution. This will delete any duplicate entries.

Body:
I have a tab delimited file that looks like this:

input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYSGGYEQY 1.00    33843   KTAYSHLSTSK polymerase  Hepatitis B virus (hepatitis B virus (HBV))
ASSYSGGYEQY ASSYSGGYEQY 1.00    131430  KLSYGIATV   orf1ab polyprotein [Severe acute respiratory syndrome coronavirus 2]    SARS-CoV2
ASSYSGGYEQY ASSFSGGYEQY 0.97    82603   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSYSGGYEQY ASSYAGGYEQY 0.98    133155  FVCNLLLLFVTVYSHLLLV ORF3a protein [Severe acute respiratory syndrome coronavirus 2] SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2

I want to keep 'input_sequence' that only match with 'organism' = SARS-CoV2 and nothing else. So in this example I would keep only line 2 and line 7 and discard lines 3,4,5,6 because here this 'input_sequence' has also a hit with Hepatitis B virus.

In total I have over 20.000 rows in my file.

results required:

input_sequence  match_sequence  score   receptor_group  epitope antigen organism
ASRPPGGVNEQF    ASRPPGGVNEQF    1.00    25735   EPLPQGQLTAY surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2
ASSLFGSTDTQY    ASSLFGSTDTQY    1.00    92508   FTISVTTEIL  surface glycoprotein [Severe acute respiratory syndrome coronavirus 2]  SARS-CoV2

Is there a way to quickly do this using awk or bash (without writing a long script)? Any tips are welcome.

I thought to use awk to count the occurences of each value in column 1 and occurences of SARS-COV2 in column 7, and then only keep those that match... but I don't know how to do this. I only got this far (counting the number of occurrences in column one):

awk '{for(i=1;i<=NF;i++)if($i ~ /^/)x++;print x;x=0}' file

Thanks!

Body:
awk '
    NR==1                              # Print first line (header)
    $NF != "SARS-CoV2" { bad[$1] }     # Collect primary keys of "bad"  records based on content in last field
    $NF == "SARS-CoV2" { good[$1]=$0 } # Collect primary keys of "good" records with opposite check
    END {
        for(v in bad) delete good[v]   # Remove primary keys from "good" records that also appear in "bad" records
        for(v in good) print good[v]   # Print the "good" rows
    }
' file

Passing the file once, this could potentially be a solution. This will delete any duplicate entries.


问:
jQuery toggle method issue
When using jquery-ui-1.8.15.custom.min toggle method, the element next to the target element is always hidden.

Here is the test page: http://jsfiddle.net/dassio/CLrMx/9

I want the div with class name suggestion to toggle between hidden and show when you click the button, but why the red line is always missing?

答:
This should do the job:
http://jsfiddle.net/CLrMx/15/

Your script was accidentally hiding your text. Cleaned it up a bit so it olny does the necessary.

ContentLicense: CC BY-SA 3.0

Title: jQuery toggle method issue


问:
CNN Transfer Learning Takes Too Much Time
I'm trying to train my model with transfer learning with Vgg16 via Google Colab(using GPU) but it takes too time and validation and test accuracy is low.
Additional informations; Train data is 16057 , test data is 4000, validation data is 2000 with different sized rgb images. Classes facial mood expressions (Happy,Sad,Energetic,Neutral) .Any suggestion ??

```<code>#source root directory and distination root directory
train_src = "/content/drive/MyDrive/Affectnet/train_class/"
val_src = "/content/drive/MyDrive/Affectnet/val_class/"
test_src="/content/drive/MyDrive/Affectnet/test_classs/"
train_datagen = tensorflow.keras.preprocessing.image.ImageDataGenerator(
      rescale=1./255,
      rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest'
      )
train_generator = train_datagen.flow_from_directory(
        train_src,
        target_size=(224,224),
        batch_size=32,
        shuffle=True
        )
validation_datagen = tensorflow.keras.preprocessing.image.ImageDataGenerator(
        rescale=1./255
        )

validation_generator = validation_datagen.flow_from_directory(
        val_src,
        target_size=(224, 224),
        batch_size=32,
        )
conv_base = tensorflow.keras.applications.VGG16(weights='imagenet',
                  include_top=False,
                  input_shape=(224, 224, 3)
                  )

for layer in conv_base.layers:
    layer.trainable=False
# An empyty model is created.
model = tensorflow.keras.models.Sequential()

# VGG16 is added as convolutional layer.
model.add(conv_base)

# Layers are converted from matrices to a vector.
model.add(tensorflow.keras.layers.Flatten())

# Our neural layer is added.
model.add(tensorflow.keras.layers.Dense(4, activation='softmax'))
model.compile(loss='categorical_crossentropy',
              optimizer=tensorflow.keras.optimizers.Adam(lr=1e-5),
              metrics=['acc'])
history = model.fit_generator(
      train_generator,
      epochs=50,
      steps_per_epoch=100,
      validation_data=validation_generator,
      validation_steps=5)
</code>```

Training Part

EDIT= I set the workers = 8 and model started training faster but i took .69 test accuracy after 30 epoch . Any Suggestion ?

答: Issue most likely related to "ImageDataGenerator", try using workers=8 in your fit_generator.</p>

Body:
I'm trying to train my model with transfer learning with Vgg16 via Google Colab(using GPU) but it takes too time and validation and test accuracy is low.
Additional informations; Train data is 16057 , test data is 4000, validation data is 2000 with different sized rgb images. Classes facial mood expressions (Happy,Sad,Energetic,Neutral) .Any suggestion ??

#source root directory and distination root directory
train_src = "/content/drive/MyDrive/Affectnet/train_class/"
val_src = "/content/drive/MyDrive/Affectnet/val_class/"
test_src="/content/drive/MyDrive/Affectnet/test_classs/"
train_datagen = tensorflow.keras.preprocessing.image.ImageDataGenerator(
      rescale=1./255,
      rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest'
      )
train_generator = train_datagen.flow_from_directory(
        train_src,
        target_size=(224,224),
        batch_size=32,
        shuffle=True
        )
validation_datagen = tensorflow.keras.preprocessing.image.ImageDataGenerator(
        rescale=1./255
        )

validation_generator = validation_datagen.flow_from_directory(
        val_src,
        target_size=(224, 224),
        batch_size=32,
        )
conv_base = tensorflow.keras.applications.VGG16(weights='imagenet',
                  include_top=False,
                  input_shape=(224, 224, 3)
                  )

for layer in conv_base.layers:
    layer.trainable=False
# An empyty model is created.
model = tensorflow.keras.models.Sequential()

# VGG16 is added as convolutional layer.
model.add(conv_base)

# Layers are converted from matrices to a vector.
model.add(tensorflow.keras.layers.Flatten())

# Our neural layer is added.
model.add(tensorflow.keras.layers.Dense(4, activation='softmax'))
model.compile(loss='categorical_crossentropy',
              optimizer=tensorflow.keras.optimizers.Adam(lr=1e-5),
              metrics=['acc'])
history = model.fit_generator(
      train_generator,
      epochs=50,
      steps_per_epoch=100,
      validation_data=validation_generator,
      validation_steps=5)

Training Part

EDIT= I set the workers = 8 and model started training faster but i took .69 test accuracy after 30 epoch . Any Suggestion ?


问:
Running an alias in a bash script gives me `<arguments>: command not found`
I have a script with an alias _test. It works fine, but before printing the output, it does <arguments>: command not found. For example, _test -h gives line 49: -h: command not found

This is a minimal example:

```<code>alias _test='
echo Hi
'
shopt -s expand_aliases

_test -h
</code>```

EDIT: For those asking about using functions, I did in fact, used to have a function instead -- but it started to cause recursion problems. I just wanted something similar to a macro -- something that acts as if the text was inserted into the script.

EDIT 2: I just realized why I kept having recursion with my function/alias. I fixed it, and I switched back to a function, but this question may help someone else.

答:
Thanks to Kugelman's answer, I was able to solve it with</p>
```<code>alias _test='
echo Hi
true'
shopt -s expand_aliases

_test -h
</code>```

Body:
I have a script with an alias _test. It works fine, but before printing the output, it does <arguments>: command not found. For example, _test -h gives line 49: -h: command not found

This is a minimal example:

alias _test='
echo Hi
'
shopt -s expand_aliases

_test -h

EDIT: For those asking about using functions, I did in fact, used to have a function instead -- but it started to cause recursion problems. I just wanted something similar to a macro -- something that acts as if the text was inserted into the script.

EDIT 2: I just realized why I kept having recursion with my function/alias. I fixed it, and I switched back to a function, but this question may help someone else.

Body:
Thanks to Kugelman's answer, I was able to solve it with

alias _test='
echo Hi
true'
shopt -s expand_aliases

_test -h


问:
How to enable dragging and resizing of divs across table cells and rows
UPDATE

I am thinking Jquery is the only solution to my problem. So making the demo work would be a big help. Thank you.

I am trying to create a scheduler type application.

I need to be able to resize the colored divs vertically and also drag them to any row/cell in the table.

Example. Drag resize orange div into row beneath it.

Or in this case if I resize the Green div the yellow div needs to be pushed into the row beneath it.

Dragging divs is self-explanatory.

I have a working sandbox DEMO

I did find a fiddle online that has exactly what I need but it uses Jquery and I would prefer not to use it if possible. FIDDLE OF WHAT I AM LOOKING FOR

```<code>   $(function() {
      $(".drop").sortable({
        connectWith: "td",
        placeholder: "ui-state-highlight"
      }).disableSelection();
    });

    $(function() {
      $(".resize").resizable({
        grid: [50, 0],
        handles: 'e'
      });
    });
</code>```

答:
Vanilla JS solution

You said:

I did find a fiddle online that has exactly what I need, but it
uses jQuery and I would prefer not to use it if possible.

I tried to replicate the output of the fiddle mentioned above using vanilla JS (HTML Drag and Drop API). This is the closest that I could get.

Note: Change resize: horizontal; to resize: vertical; if you want to resize boxes vertically.

See the snippet below.

document.addEventListener('DOMContentLoaded', (event) => {
  var dragSrcEl = null;

  function handleDragStart(e) {
    dragSrcEl = this;

    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
  }

  function handleDragOver(e) {
    if (e.preventDefault) {
      e.preventDefault();
    }

    e.dataTransfer.dropEffect = 'move';

    return false;
  }

  function handleDragEnter(e) {
    this.classList.add('over');
  }

  function handleDragLeave(e) {
    this.classList.remove('over');
  }

  function handleDrop(e) {
    if (e.stopPropagation) {
      e.stopPropagation();
    }

    if (dragSrcEl != this) {
      dragSrcEl.innerHTML = this.innerHTML;
      this.innerHTML = e.dataTransfer.getData('text/html');
    }

    return false;
  }

  function handleDragEnd(e) {
    items.forEach(function(item) {
      item.classList.remove('over');
    });
  }

  let items = document.querySelectorAll('.container .drop');
  items.forEach(function(item) {
    item.addEventListener('dragstart', handleDragStart, false);
    item.addEventListener('dragenter', handleDragEnter, false);
    item.addEventListener('dragover', handleDragOver, false);
    item.addEventListener('dragleave', handleDragLeave, false);
    item.addEventListener('drop', handleDrop, false);
    item.addEventListener('dragend', handleDragEnd, false);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  height: 100px;
}

td {
  height: 68px;
  width: 150px;
  border: gray thin solid;
}

.resize {
  top: 10px;
  width: 50px;
  height: 50px;
  float: left;
  border: #002DA4 thin solid;
  border-radius: 8px;
  text-align: center;
  border-right-color: red;
  position: absolute;
  overflow: hidden;
  resize: horizontal;
  z-index: 1;
}

td.drop {
  position: relative;
  width: 60px;
}</code>```

<!DOCTYPE html>

  <meta charset='UTF-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Document</title>

        8am
        9am
        10am
        11am
        12n
        1pm
        2pm
        3pm
        4pm
        5pm

Session A

Session B

```

Body:
UPDATE

I am thinking Jquery is the only solution to my problem. So making the demo work would be a big help. Thank you.

I am trying to create a scheduler type application.

I need to be able to resize the colored divs vertically and also drag them to any row/cell in the table.

Example. Drag resize orange div into row beneath it.

Or in this case if I resize the Green div the yellow div needs to be pushed into the row beneath it.

Dragging divs is self-explanatory.

I have a working sandbox DEMO

I did find a fiddle online that has exactly what I need but it uses Jquery and I would prefer not to use it if possible. FIDDLE OF WHAT I AM LOOKING FOR

   $(function() {
      $(".drop").sortable({
        connectWith: "td",
        placeholder: "ui-state-highlight"
      }).disableSelection();
    });

    $(function() {
      $(".resize").resizable({
        grid: [50, 0],
        handles: 'e'
      });
    });

Body:
Vanilla JS solution

You said:

I did find a fiddle online that has exactly what I need, but it
uses jQuery and I would prefer not to use it if possible.

I tried to replicate the output of the fiddle mentioned above using vanilla JS (HTML Drag and Drop API). This is the closest that I could get.

Note: Change resize: horizontal; to resize: vertical; if you want to resize boxes vertically.

See the snippet below.

document.addEventListener('DOMContentLoaded', (event) => {
  var dragSrcEl = null;

  function handleDragStart(e) {
    dragSrcEl = this;

    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
  }

  function handleDragOver(e) {
    if (e.preventDefault) {
      e.preventDefault();
    }

    e.dataTransfer.dropEffect = 'move';

    return false;
  }

  function handleDragEnter(e) {
    this.classList.add('over');
  }

  function handleDragLeave(e) {
    this.classList.remove('over');
  }

  function handleDrop(e) {
    if (e.stopPropagation) {
      e.stopPropagation();
    }

    if (dragSrcEl != this) {
      dragSrcEl.innerHTML = this.innerHTML;
      this.innerHTML = e.dataTransfer.getData('text/html');
    }

    return false;
  }

  function handleDragEnd(e) {
    items.forEach(function(item) {
      item.classList.remove('over');
    });
  }

  let items = document.querySelectorAll('.container .drop');
  items.forEach(function(item) {
    item.addEventListener('dragstart', handleDragStart, false);
    item.addEventListener('dragenter', handleDragEnter, false);
    item.addEventListener('dragover', handleDragOver, false);
    item.addEventListener('dragleave', handleDragLeave, false);
    item.addEventListener('drop', handleDrop, false);
    item.addEventListener('dragend', handleDragEnd, false);
  });
});

table {
  height: 100px;
}

td {
  height: 68px;
  width: 150px;
  border: gray thin solid;
}

.resize {
  top: 10px;
  width: 50px;
  height: 50px;
  float: left;
  border: #002DA4 thin solid;
  border-radius: 8px;
  text-align: center;
  border-right-color: red;
  position: absolute;
  overflow: hidden;
  resize: horizontal;
  z-index: 1;
}

td.drop {
  position: relative;
  width: 60px;
}

<!DOCTYPE html>
<html lang='en'>

<head>
  <meta charset='UTF-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Document</title>
</head>

<body>
  <div>
    <table cellspacing='3'>
      <tr>
        <th>8am</th>
        <th>9am</th>
        <th>10am</th>
        <th>11am</th>
        <th>12n</th>
        <th>1pm</th>
        <th>2pm</th>
        <th>3pm</th>
        <th>4pm</th>
        <th>5pm</th>
      </tr>

      <tbody class='container'>
        <tr>
          <td class='drop'>
            <div draggable='true' class='resize'>Session A</div>
          </td>
          <td draggable='true' class='drop'>
            <div draggable='true' class='resize'>Session B</div>
          </td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
        </tr>

        <tr>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
          <td draggable='true' class='drop'></td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

</html>


问:
Disable autocomplete in C#
I have the following problem with AutoComplete feature in ComboBox (DropDown). My settings for combo:

AutoCompleteMode: AutoCompleteMode.None

AutoCompleteSource: AutoCompleteSource.None

DropDownStyle: ComboBoxStyle.DropDown

Issue is -
It completes the text from database

Can anyone help to deal with this?What am I missing?

答:
Solution is this:
EnableAutoComplete = false;
Example:

    *c#*

    cmbOrderEvasion.EnableAutoComplete = false;
```
```*dotnet*
cmbOrderEvasion->EnableAutoComplete = false;
```

Warning:
Need write manually without Intellsense because Intelsense not suggest ever.

Title: Disable autocomplete in C#

Body:
Solution is this:
EnableAutoComplete = false;
Example:

    *c#*

    cmbOrderEvasion.EnableAutoComplete = false;

*dotnet*
cmbOrderEvasion->EnableAutoComplete = false;

Warning:
Need write manually without Intellsense because Intelsense not suggest ever.


问:
How to pull a range of data (plus/minus) around a specific date in SQL
I have Table 1 and Table 2, where Table 1 has unique customer id and their report date and Table 2 has the entire date range and corresponding values for each date for each customer id. Basically, I want to pull 2 dates before the report date and 2 dates after the report date for each customer id to get the Desired Output Table below. SQL - pull data for date range based on a start date seems to be the closest to what I want, but I don't know how to tweak the answer to suit my requirement.

Below is my code, but it does not work in Hive/Hue SQL. Appreciate your help :)

```<code>SELECT b.date, a.report_date, a.customer_id, b.value
FROM table1 a
  LEFT JOIN table2 b ON b.date = a.report_date AND b.customer_id = a.customer_id
WHERE b.date IN (DATE_ADD(a.report_date, 2)
   OR b.date IN (DATE_SUB(a.report_date, 2)
</code>```

TABLE 1

customer id
report date

123
15/01/2021

456
20/02/2021

TABLE 2

customer id
date
value

...
...
...

123
13/01/2021
10

123
14/01/2021
13

123
15/01/2021
9

123
16/01/2021
19

123
17/01/2021
20

...
...
...

...
...
...

456
18/02/2021
4

456
19/02/2021
5

456
20/02/2021
2

456
21/02/2021
9

456
22/02/2021
1

...
...
...

DESIRED OUTPUT TABLE

date
report date
customer id
value

13/01/2021
15/01/2021
123
10

14/01/2021
15/01/2021
123
13

15/01/2021
15/01/2021
123
9

16/01/2021
15/01/2021
123
19

17/01/2021
15/01/2021
123
20

18/02/2021
20/02/2021
456
4

19/02/2021
20/02/2021
456
5

20/02/2021
20/02/2021
456
2

21/02/2021
20/02/2021
456
9

22/02/2021
20/02/2021
456
1

答:
Shouldn't it be

```<code>SELECT b.date, a.report_date, a.customer_id, b.value
FROM table1 a
  LEFT JOIN table2 b ON b.customer_id = a.customer_id
WHERE
  b.date BETWEEN DATE_SUB(a.report_date, 2)
         AND DATE_ADD(a.report_date, 2)
</code>```

I don't really know HIVE SQL but IN is a set/list operator, so you would be looking for the two dates, but the closing brackets are missing, too.

Body:
I have Table 1 and Table 2, where Table 1 has unique customer id and their report date and Table 2 has the entire date range and corresponding values for each date for each customer id. Basically, I want to pull 2 dates before the report date and 2 dates after the report date for each customer id to get the Desired Output Table below. SQL - pull data for date range based on a start date seems to be the closest to what I want, but I don't know how to tweak the answer to suit my requirement.

Below is my code, but it does not work in Hive/Hue SQL. Appreciate your help :)

SELECT b.date, a.report_date, a.customer_id, b.value
FROM table1 a
  LEFT JOIN table2 b ON b.date = a.report_date AND b.customer_id = a.customer_id
WHERE b.date IN (DATE_ADD(a.report_date, 2)
   OR b.date IN (DATE_SUB(a.report_date, 2)

TABLE 1

customer id
report date

123
15/01/2021

456
20/02/2021

TABLE 2

customer id
date
value

...
...
...

123
13/01/2021
10

123
14/01/2021
13

123
15/01/2021
9

123
16/01/2021
19

123
17/01/2021
20

...
...
...

...
...
...

456
18/02/2021
4

456
19/02/2021
5

456
20/02/2021
2

456
21/02/2021
9

456
22/02/2021
1

...
...
...

DESIRED OUTPUT TABLE

date
report date
customer id
value

13/01/2021
15/01/2021
123
10

14/01/2021
15/01/2021
123
13

15/01/2021
15/01/2021
123
9

16/01/2021
15/01/2021
123
19

17/01/2021
15/01/2021
123
20

18/02/2021
20/02/2021
456
4

19/02/2021
20/02/2021
456
5

20/02/2021
20/02/2021
456
2

21/02/2021
20/02/2021
456
9

22/02/2021
20/02/2021
456
1

Body:
Shouldn't it be

SELECT b.date, a.report_date, a.customer_id, b.value
FROM table1 a
  LEFT JOIN table2 b ON b.customer_id = a.customer_id
WHERE
  b.date BETWEEN DATE_SUB(a.report_date, 2)
         AND DATE_ADD(a.report_date, 2)

I don't really know HIVE SQL but IN is a set/list operator, so you would be looking for the two dates, but the closing brackets are missing, too.


问:
How to resolve the Virtualized Lists warning with multiple Flatlists within a scroll
I have been working my way through legacy views within an app - resolving the issues of FlatLists within a ScrollView component casuing the resulting Virtualised Lists error that is displayed.

I have 5 affected pages - first 3 only had 1 flatlist in the view - so was easy enough to split the urrounding code into flatlist header and footer assets.  However I'm not sure what to do in terms of having 2 or more flatlists - how do i apprach the layout in thsi scenario - so there is only 1 scroll?

I may be missing something very simple but need a nudge please!

here is the view code:

```<code><View style={[PRStyles.IRContainer]} >
        <StatusBar barStyle="light-content" />
        <View style={PRStyles.header}>
          <FixedHeader backButton={true} navScreen='HomeViewContainer' />
        </View>

        <View style={PRStyles.IRBody}>
          <ScrollView
            refreshControl={
              <RefreshControl
                refreshing={this.state.refreshing}
                onRefresh={this._onRefresh} />}>
            <KeyboardAvoidingView>
            <TitleHeader sectionLocaleTxt='Duty Record' sectionTxt='' sectionDesc='End of shift duty Record.' sectionHyphen={false}  />
            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowTitle}>{this.props.auth.checkedInVenueName}</Text>
              <Text style={FormStyles.PrRowDate}>{this.getCurrentDate()}</Text>
            </View>
            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowSubTitle}>General Manager / Licence Holder:</Text>
              <View style={FormStyles.PrTable}>
                <View style={FormStyles.prRowStrip}><Text style={FormStyles.prRowStripText} >{this.state.licenceHolder}</Text></View>
              </View>
            </View>

            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowSubTitle}>Door Staff (<Text style={FormStyles.PrRowCount}>{this.state.doorStaffCount}</Text> total)</Text>
              <View style={FormStyles.PrTable}>
                <FlatList
                  scrollEnabled={true}
                  data={this.state.rotaRecords}
                  keyExtractor={(item, index) => index.toString()}
                  ListEmptyComponent={this._listStaffEmptyComponent}
                  renderItem={this._renderDoorStaffItem}
                />
              </View>

            </View>
            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowSubTitle}>Numbers:</Text>
              <View style={FormStyles.PrTable}>
                <View style={FormStyles.prRowStrip}><Text style={FormStyles.prRowStripText} >Total In <Text style={ FormStyles.prRowStripColon}>:</Text> <Text style={FormStyles.prRowStripOrText}>{this.state.totalIn}</Text></Text></View>
                <View style={FormStyles.prRowStrip}><Text style={FormStyles.prRowStripText} >Total Out<Text style={FormStyles.prRowStripColon}>:</Text> <Text style={FormStyles.prRowStripOrText}>{this.state.totalOut}</Text></Text></View>
                <View style={FormStyles.prRowStrip}><Text style={FormStyles.prRowStripText} >Overall Difference<Text style={FormStyles.prRowStripColon}>:</Text> <Text style={FormStyles.prRowStripOrText}>{this.state.totalDifference}</Text></Text></View>
              </View>

            </View>

            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowSubTitle}>Door Counts:</Text>
              <FlatList
                  scrollEnabled={true}
                  data={this.state.countRecords}
                  keyExtractor={(item, index) => index.toString()}
                  ListEmptyComponent={this._listDoorCountEmptyComponent}
                  ListHeaderComponent={this._listDoorCountHeaderComponent}
                  renderItem={this._renderDoorCountItem}
                />
          </View>

            <View style={[FormStyles.form, FormStyles.PrRow, {marginTop:15, paddingTop:0, borderBottomWidth:0} ]}>
              <Text style={ModalStyles.formTop}><Text style={[ModalStyles.required, ]}>*</Text>Required Field</Text>
              <Text style={[FormStyles.formLabel, FormStyles.formlabelFirst ]}>1. Customer Comments:</Text>

              <View style={FormStyles.textInputBlock}>
                <TextInput
                  placeholder="Enter Comments"
                  numberOfLines={4}
                  onChangeText={val => this.setState({ comments: val})}
                  value={this.state.comments}
                  multiline
                  style={{minHeight: 280, height: 'auto', textAlignVertical: 'top'}}
                />
              </View>

              <Text style={[FormStyles.formLabel, FormStyles.formlabelFirst ]}>2. Duty Manager Name<Text style={ModalStyles.required}>*</Text> :</Text>

              <View style={FormStyles.textInputBlock}>
                <TextInput
                  ref='signatureName'
                  placeholder="Please Print Name"
                  style={FormStyles.textInputText}
                  autoCorrect={false}
                  returnKeyType='done'
                  value={this.state.signatureName}
                  onChangeText={(text) => this.setState({signatureName:text})}
                />
              </View>
              <Text style={[FormStyles.formLabel, FormStyles.formlabelFirst ]}>3. Duty Manager Signature: <Text style={ModalStyles.required}>*</Text></Text>
                  <Text style={[FormStyles.formLabelSub, FormStyles.formLabelSubHigh, FormStyles.superHighLight ]}>Note: PRESS BLUE SAVE BUTTON after applying Signature</Text>
              <View style={[FormStyles.textInputBlock, this.isSignatureAdded() && FormStyles.signatureBlock ]}>
                {this.signatureBlock()}

              </View>
            </View>

            {submitButton}
           </KeyboardAvoidingView>
          </ScrollView>
        </View>
      </View>
</code>```

答:
This is the most common error when working with scroll view and flat list.

To prevent the error cause, we have to manage our views inside a single flat list and put other components in the list header component and list footer component in an efficient way as we desire.

```<code><FlatList
    data={this.state.countRecords}
    renderItem={(item) => {
        return (
            // Your flat list item goes here..
        )
    }}
    ListHeaderComponent={
        // Content above the list goes here..
    }
    ListFooterComponent={
        // Content below the list should goes here..
    }
/>
</code>```

You can still check the below link for more understanding.

FlatList Example with Custom Header and Custom Footer

Body:
I have been working my way through legacy views within an app - resolving the issues of FlatLists within a ScrollView component casuing the resulting Virtualised Lists error that is displayed.

I have 5 affected pages - first 3 only had 1 flatlist in the view - so was easy enough to split the urrounding code into flatlist header and footer assets.  However I'm not sure what to do in terms of having 2 or more flatlists - how do i apprach the layout in thsi scenario - so there is only 1 scroll?

I may be missing something very simple but need a nudge please!

here is the view code:

<View style={[PRStyles.IRContainer]} >
        <StatusBar barStyle="light-content" />
        <View style={PRStyles.header}>
          <FixedHeader backButton={true} navScreen='HomeViewContainer' />
        </View>

        <View style={PRStyles.IRBody}>
          <ScrollView
            refreshControl={
              <RefreshControl
                refreshing={this.state.refreshing}
                onRefresh={this._onRefresh} />}>
            <KeyboardAvoidingView>
            <TitleHeader sectionLocaleTxt='Duty Record' sectionTxt='' sectionDesc='End of shift duty Record.' sectionHyphen={false}  />
            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowTitle}>{this.props.auth.checkedInVenueName}</Text>
              <Text style={FormStyles.PrRowDate}>{this.getCurrentDate()}</Text>
            </View>
            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowSubTitle}>General Manager / Licence Holder:</Text>
              <View style={FormStyles.PrTable}>
                <View style={FormStyles.prRowStrip}><Text style={FormStyles.prRowStripText} >{this.state.licenceHolder}</Text></View>
              </View>
            </View>

            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowSubTitle}>Door Staff (<Text style={FormStyles.PrRowCount}>{this.state.doorStaffCount}</Text> total)</Text>
              <View style={FormStyles.PrTable}>
                <FlatList
                  scrollEnabled={true}
                  data={this.state.rotaRecords}
                  keyExtractor={(item, index) => index.toString()}
                  ListEmptyComponent={this._listStaffEmptyComponent}
                  renderItem={this._renderDoorStaffItem}
                />
              </View>

            </View>
            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowSubTitle}>Numbers:</Text>
              <View style={FormStyles.PrTable}>
                <View style={FormStyles.prRowStrip}><Text style={FormStyles.prRowStripText} >Total In <Text style={ FormStyles.prRowStripColon}>:</Text> <Text style={FormStyles.prRowStripOrText}>{this.state.totalIn}</Text></Text></View>
                <View style={FormStyles.prRowStrip}><Text style={FormStyles.prRowStripText} >Total Out<Text style={FormStyles.prRowStripColon}>:</Text> <Text style={FormStyles.prRowStripOrText}>{this.state.totalOut}</Text></Text></View>
                <View style={FormStyles.prRowStrip}><Text style={FormStyles.prRowStripText} >Overall Difference<Text style={FormStyles.prRowStripColon}>:</Text> <Text style={FormStyles.prRowStripOrText}>{this.state.totalDifference}</Text></Text></View>
              </View>

            </View>

            <View style={FormStyles.PrRow}>
              <Text style={FormStyles.PrRowSubTitle}>Door Counts:</Text>
              <FlatList
                  scrollEnabled={true}
                  data={this.state.countRecords}
                  keyExtractor={(item, index) => index.toString()}
                  ListEmptyComponent={this._listDoorCountEmptyComponent}
                  ListHeaderComponent={this._listDoorCountHeaderComponent}
                  renderItem={this._renderDoorCountItem}
                />
          </View>

            <View style={[FormStyles.form, FormStyles.PrRow, {marginTop:15, paddingTop:0, borderBottomWidth:0} ]}>
              <Text style={ModalStyles.formTop}><Text style={[ModalStyles.required, ]}>*</Text>Required Field</Text>
              <Text style={[FormStyles.formLabel, FormStyles.formlabelFirst ]}>1. Customer Comments:</Text>

              <View style={FormStyles.textInputBlock}>
                <TextInput
                  placeholder="Enter Comments"
                  numberOfLines={4}
                  onChangeText={val => this.setState({ comments: val})}
                  value={this.state.comments}
                  multiline
                  style={{minHeight: 280, height: 'auto', textAlignVertical: 'top'}}
                />
              </View>

              <Text style={[FormStyles.formLabel, FormStyles.formlabelFirst ]}>2. Duty Manager Name<Text style={ModalStyles.required}>*</Text> :</Text>

              <View style={FormStyles.textInputBlock}>
                <TextInput
                  ref='signatureName'
                  placeholder="Please Print Name"
                  style={FormStyles.textInputText}
                  autoCorrect={false}
                  returnKeyType='done'
                  value={this.state.signatureName}
                  onChangeText={(text) => this.setState({signatureName:text})}
                />
              </View>
              <Text style={[FormStyles.formLabel, FormStyles.formlabelFirst ]}>3. Duty Manager Signature: <Text style={ModalStyles.required}>*</Text></Text>
                  <Text style={[FormStyles.formLabelSub, FormStyles.formLabelSubHigh, FormStyles.superHighLight ]}>Note: PRESS BLUE SAVE BUTTON after applying Signature</Text>
              <View style={[FormStyles.textInputBlock, this.isSignatureAdded() && FormStyles.signatureBlock ]}>
                {this.signatureBlock()}

              </View>
            </View>

            {submitButton}
           </KeyboardAvoidingView>
          </ScrollView>
        </View>
      </View>

Body:
This is the most common error when working with scroll view and flat list.

To prevent the error cause, we have to manage our views inside a single flat list and put other components in the list header component and list footer component in an efficient way as we desire.

<FlatList
    data={this.state.countRecords}
    renderItem={(item) => {
        return (
            // Your flat list item goes here..
        )
    }}
    ListHeaderComponent={
        // Content above the list goes here..
    }
    ListFooterComponent={
        // Content below the list should goes here..
    }
/>

You can still check the below link for more understanding.

FlatList Example with Custom Header and Custom Footer


答:
Your question has several problems.

What is embs; we can guess, such as a list of dict, or maybe pandas dataframe?

What is the block labeled input?  The result of this loop:

```<code>for emb in embs:
   print(emb['name'])
</code>```

What is output?  That actual output of your code, or the desired output?  If the latter, what did your code do?  What was wrong with it?

Often we see naive attempts to replicate this list iteration:

```<code>alist = []
for x in another_list:
    alist.append(x)
</code>```

But I'm not sure that's what you have in mind.  You don't define any array to 'collect' the loop values in.  And your loop just has a print(), which doesn't return anything (or rather returns None).  And concatenate doesn't work in in-place.

You've read enough of the concatenate docs to use the axis parameter, but your single first argument looks nothing like the documented tuple of arrays, (a1, a2, ...)

Since embs is apparently a list of 2 somethings with a name value, and the values are matching 2d arrays, this concatenate should produce your desired output:

```<code>np.concatenate( (embs[0]['name'], embs[1]['name']), axis=0 )
</code>```

We could make that argument tuple with a list comprehension, or my earlier list append, but I think you need to see this concatenation spelled out in detail.  Your understanding of python loops is still weak.

Title: Concatenate numpy arrays to a single array

Body:
I am trying to merge the two <class 'numpy.ndarray'> into a single array.

Code that I tried:

for emb in embs:
   print(np.concatenate( emb['name'], axis=0 ))

Input:

[[-0.05646843 -0.00381141 -0.05721215 0.06029008]
 [-0.02690301  0.04218878  0.00404305 0.05841358]]
[[-0.02675129  0.03649405 -0.04379312 -0.04826404]
 [ 0.01131434  0.0581139   0.00785002  -0.02065904]]

Output:

[[-0.05646843 -0.00381141 -0.05721215 0.06029008]
 [-0.02690301  0.04218878  0.00404305 0.05841358]
 [-0.02675129  0.03649405 -0.04379312 -0.04826404]
 [ 0.01131434  0.0581139   0.00785002  -0.02065904]]

Any leads would be appreciated.

Body:
Your question has several problems.

What is embs; we can guess, such as a list of dict, or maybe pandas dataframe?

What is the block labeled input?  The result of this loop:

for emb in embs:
   print(emb['name'])

What is output?  That actual output of your code, or the desired output?  If the latter, what did your code do?  What was wrong with it?

Often we see naive attempts to replicate this list iteration:

alist = []
for x in another_list:
    alist.append(x)

But I'm not sure that's what you have in mind.  You don't define any array to 'collect' the loop values in.  And your loop just has a print(), which doesn't return anything (or rather returns None).  And concatenate doesn't work in in-place.

You've read enough of the concatenate docs to use the axis parameter, but your single first argument looks nothing like the documented tuple of arrays, (a1, a2, ...)

Since embs is apparently a list of 2 somethings with a name value, and the values are matching 2d arrays, this concatenate should produce your desired output:

np.concatenate( (embs[0]['name'], embs[1]['name']), axis=0 )

We could make that argument tuple with a list comprehension, or my earlier list append, but I think you need to see this concatenation spelled out in detail.  Your understanding of python loops is still weak.


问:
DATEPART in Sequelize ORM
Is there any option for T-SQL DATEPART equivalent in Sequelize ORM?

Sequelize's between operator has an option to place the table field on the left side, but I wanted to do something like below but with DATEPART option

```<code>const Schedules= await Schedules.findAll({
   where: {
    *DATEPART here*
    Date.now() : {
     [Op.between]: [ startdate, enddate ]
    }
   }
</code>```

I want to write a query like this:

```<code>SELECT *
FROM schedules
WHERE DATEPART(HOUR, GETDATE()) BETWEEN DATEPART(HOUR, startdate) AND DATEPART(HOUR, enddate)
</code>```

Here is my model

```<code>module.exports = (sequelize, Sequelize) => {
    const Schedules = sequelize.define(
        "Schedules",
        {
            title: {
                type: Sequelize.STRING(255),
                allowNull: false,
            },
            startdate: {
                type: Sequelize.DATE,
                allowNull: false,
            },
            enddate: {
                type: Sequelize.DATE,
                allowNull: false,
            },
        },
        {
            freezeTableName: true
        }
    );
    return Schedules;
};
</code>```

Sequelize version: 6.x

答:
Just use Sequelize.fn and Sequelize.where to combine and compare SQL function result values:

const Schedules= await Schedules.findAll({
   where: {
    [Op.and]: [
Sequelize.where(Sequelize.fn('DATE', Sequelize.literal('HOUR'), Sequelize.fn('getdate')), Op.gte, Sequelize.fn('DATE', Sequelize.literal('HOUR'), Sequelize.col('startdate'))),

Sequelize.where(Sequelize.fn('DATE', Sequelize.literal('HOUR'), Sequelize.fn('getdate')), Op.lte, Sequelize.fn('DATE', Sequelize.literal('HOUR'), Sequelize.col('enddate')))
]
}
```

Title: DATEPART in Sequelize ORM

Body:
Is there any option for T-SQL DATEPART equivalent in Sequelize ORM?

Sequelize's between operator has an option to place the table field on the left side, but I wanted to do something like below but with DATEPART option

const Schedules= await Schedules.findAll({
   where: {
    *DATEPART here*
    Date.now() : {
     [Op.between]: [ startdate, enddate ]
    }
   }

I want to write a query like this:

SELECT *
FROM schedules
WHERE DATEPART(HOUR, GETDATE()) BETWEEN DATEPART(HOUR, startdate) AND DATEPART(HOUR, enddate)

Here is my model

module.exports = (sequelize, Sequelize) => {
    const Schedules = sequelize.define(
        "Schedules",
        {
            title: {
                type: Sequelize.STRING(255),
                allowNull: false,
            },
            startdate: {
                type: Sequelize.DATE,
                allowNull: false,
            },
            enddate: {
                type: Sequelize.DATE,
                allowNull: false,
            },
        },
        {
            freezeTableName: true
        }
    );
    return Schedules;
};

Sequelize version: 6.x


问:
What is best practice for storing weekly data in MySql table and deleting data from past weeks?
Some data is collected in a single MySql table. After one week, this data becomes obsolete. The old data is deleted weekly from the table by scheduled command. But this leads to performance bottleneck during deletion as the table is locked. I have been looking in direction of partitioning - to have at least 2 tables: one table for the current week and another for the past week. So I can drop complete table from the past week. Is it a good choice? Are there other options?</p>

答:
There are at least two options I can recommend:

Use table partitioning. Dropping a partition is like dropping a table, it's very fast regardless of the number of rows in the partition. But there are limitations on partitioning, so read the documentation carefully. The one that usually blocks usage of partitioning is how it requires the partitioning key is part of every unique key of the table: https://dev.mysql.com/doc/refman/8.0/en/partitioning-limitations-partitioning-keys-unique-keys.html

Use pt-archiver. This deletes rows in small groups, so it takes a brief time for each group. It may take longer than doing a single DELETE, but it's okay because it only locks one group at a time, not the whole table.


问:
Azure DevOps API Authentication
I would like to use the Azure DevOps API to create a PAT for my user. But I'm unable to authenticate yet. In this document from Microsoft, they state that authentication is possible with a PAT, but it is not true. I'm getting a HTTP 203 with a Sign In page in response.

PS: I'm using Postman to test the API requests.

答:
Yes it does work, you're just not setting it up right.

Look at the Basic Authentication of this document. You need to base 64 encode the username password like this: username:PAT. Spearate the two with the colon.

Title: Azure DevOps API Authentication