问:
Unable to format break tags in reportlab 3.5.34
I'm using reportlab to generate a pdf document.
I am using the following markup:

```<code><para><strong>Referred to MCH TVM.</strong></para><br/><para><i>Patient presented with bilateral neck nodes.</i></para><br/><para><i>O/E:</i></para><br/><para> Findings: klkllklklk</para><br/><para>Kindly advise.</para><br/>
</code>```

My code includes:

```<code>regstyle = ParagraphStyle(
    name='Regular', fontName='Helvetica', fontSize=10, leading=12)
AdviseBlock = Paragraph(f"{Advisedata}", style=regstyle)
</code>```

This gives the following error:

```<code>2020-02-14 10:46:19,921 django.request ERROR    Internal Server Error: /clinic/presc/hm9x9HHIRg
Traceback (most recent call last):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/joel/myappointments/clinic/views.py", line 5886, in GoGetPrescription
    clinicobj=clinicobj,
File "/home/joel/myappointments/clinic/views.py", line 13466, in PDFPrescriptions
    elements = CreateAdvise(elements, cur_clinical_record)
File "/home/joel/myappointments/clinic/views.py", line 13421, in CreateAdvise
    AdviseBlock = Paragraph(f"{Advisedata}", style=regstyle)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paragraph.py", line 1541, in __init__
    self._setup(text, style, bulletText or getattr(style,'bulletText',None), frags, cleanBlockQuotedText)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paragraph.py", line 1563, in _setup
    style, frags, bulletTextFrags = _parser.parse(text,style)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3224, in parse
    annotateException('\nparagraph text %s caused exception' % ascii(text))
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 1394, in annotateException
    rl_reraise(t,v,b)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 147, in rl_reraise
    raise v
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3222, in parse
    self.feed(text)
File "/usr/lib/python3.6/html/parser.py", line 111, in feed
    self.goahead(0)
File "/usr/lib/python3.6/html/parser.py", line 171, in goahead
    k = self.parse_starttag(i)
File "/usr/lib/python3.6/html/parser.py", line 343, in parse_starttag
    self.handle_startendtag(tag, attrs)
File "/usr/lib/python3.6/html/parser.py", line 427, in handle_startendtag
    self.handle_starttag(tag, attrs)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3245, in handle_starttag
    start(attrs or {})
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 2861, in start_br
    self._push('br',_selfClosingTag='br',lineBreak=True,text='')
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3063, in _push
    frag = copy.copy(self._stack[-1])
IndexError: list index out of range
paragraph text '<para><strong>Referred to MCH TVM.</strong></para><br/><para><i>Patient presented with bilateral neck nodes.</i></para><br/><para><i>O/E:</i></para><br/><para> Findings: klkllklklk</para><br/><para>Kindly advise.</para><br/>' caused exception
</code>```

What's wrong with the markup I'm using?

答:
The whole may be surrounded by <para> tags but it is unnecessary to include multiple times.

```<code>advise_data = '<para><strong>Referred to MCH TVM.</strong><br/><i>Patient presented with bilateral neck nodes.</i><br/><i>O/E:</i><br/>Findings: klkllklklk<br/>Kindly advise.</para>'
</code>```

Body:
I'm using reportlab to generate a pdf document.
I am using the following markup:

<para>Referred to MCH TVM.</para>
<para>Patient presented with bilateral neck nodes.</para>
<para>O/E:</para>
<para> Findings: klkllklklk</para>
<para>Kindly advise.</para>

My code includes:

regstyle = ParagraphStyle(
    name='Regular', fontName='Helvetica', fontSize=10, leading=12)
AdviseBlock = Paragraph(f"{Advisedata}", style=regstyle)

This gives the following error:

2020-02-14 10:46:19,921 django.request ERROR    Internal Server Error: /clinic/presc/hm9x9HHIRg
Traceback (most recent call last):
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/joel/myappointments/clinic/views.py", line 5886, in GoGetPrescription
    clinicobj=clinicobj,
File "/home/joel/myappointments/clinic/views.py", line 13466, in PDFPrescriptions
    elements = CreateAdvise(elements, cur_clinical_record)
File "/home/joel/myappointments/clinic/views.py", line 13421, in CreateAdvise
    AdviseBlock = Paragraph(f"{Advisedata}", style=regstyle)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paragraph.py", line 1541, in __init__
    self._setup(text, style, bulletText or getattr(style,'bulletText',None), frags, cleanBlockQuotedText)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paragraph.py", line 1563, in _setup
    style, frags, bulletTextFrags = _parser.parse(text,style)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3224, in parse
    annotateException('\nparagraph text %s caused exception' % ascii(text))
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 1394, in annotateException
    rl_reraise(t,v,b)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/lib/utils.py", line 147, in rl_reraise
    raise v
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3222, in parse
    self.feed(text)
File "/usr/lib/python3.6/html/parser.py", line 111, in feed
    self.goahead(0)
File "/usr/lib/python3.6/html/parser.py", line 171, in goahead
    k = self.parse_starttag(i)
File "/usr/lib/python3.6/html/parser.py", line 343, in parse_starttag
    self.handle_startendtag(tag, attrs)
File "/usr/lib/python3.6/html/parser.py", line 427, in handle_startendtag
    self.handle_starttag(tag, attrs)
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3245, in handle_starttag
    start(attrs or {})
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 2861, in start_br
    self._push('br',_selfClosingTag='br',lineBreak=True,text='')
File "/home/joel/myappointments/venv/lib/python3.6/site-packages/reportlab/platypus/paraparser.py", line 3063, in _push
    frag = copy.copy(self._stack[-1])
IndexError: list index out of range
paragraph text '<para>Referred to MCH TVM.</para>
<para>Patient presented with bilateral neck nodes.</para>
<para>O/E:</para>
<para> Findings: klkllklklk</para>
<para>Kindly advise.</para>
' caused exception

What's wrong with the markup I'm using?

Body:
The whole may be surrounded by <para> tags but it is unnecessary to include multiple times.

advise_data = '<para><strong>Referred to MCH TVM.</strong><br/><i>Patient presented with bilateral neck nodes.</i><br/><i>O/E:</i><br/>Findings: klkllklklk<br/>Kindly advise.</para>'


来源: stackexchange

问:
Firebase "Run firebase use default to activate project APP_NAME"
It was successfully when deployed first time, now im trying to deploy again, shows an error:

```<code>Run firebase use default to activate project MY_APP_NAME
</code>```

Error:

No project active, but a project alias is available.

答:
In my case firebase logout and login again by firebase login works.

I have the same problem - want to switch project alias to staging after pull my code repo to new machine. I have another project on firebase and logged in the same account as in this project, but error appears:

Error: No project active, but project aliases are available.

and

Error: Invalid project selection, please verify project staging exists
  and you have access.

Verify that in .firebaserc file project alias exist and it tagets to correct project in your account.

ContentLicense: CC BY-SA 3.0

Body:
It was successfully when deployed first time, now im trying to deploy again, shows an error:

Run firebase use default to activate project MY_APP_NAME

Error:

No project active, but a project alias is available.

ContentLicense: CC BY-SA 4.0


问:
Zabbix - how to lower the unsupported item refresh interval
I have a container which is runnig zabbix_web and has everything it needs to work properly (zabbix_server and zabbix_web). In a different container I have tests which create zabbix items and perform different checks on them everything through zabbix API. I need to be able to lower the unsupported item resresh interval for tests to be more reliable and I have no idea how to do it. It can be easily done through zabbix web GUI though.</p>

答: Administration -> General -> Other -> Refresh unsupported items


问:
Error parsing dacpac docker microsoft sql server
I am trying to create an image with a file dockerfile and using dacpac, but when I try do publish, it throw this exception: Error parsing connection string: The type initializer for 'Microsoft.SqlServer.Dac.DacProfile' threw an exception..
This is my dockerfile

```<code>FROM microsoft/mssql-server-windows-express

COPY sqlpackage/1033 /opt/sqlpackage/1033
COPY sqlpackage/Extensions /opt/sqlpackage/Extensions
COPY sqlpackage/en /opt/sqlpackage/en
COPY sqlpackage/DacUnpack.exe /opt/sqlpackage/DacUnpack.exe
COPY sqlpackage/Microsoft.Data.Tools.Schema.Sql.dll/ /opt/sqlpackage/Microsoft.Data.Tools.Schema.Sql.dll
COPY sqlpackage/Microsoft.Data.Tools.Utilities.dll /opt/sqlpackage/Microsoft.Data.Tools.Utilities.dll
COPY sqlpackage/Microsoft.SqlServer.Dac.dll /opt/sqlpackage/Microsoft.SqlServer.Dac.dll
COPY sqlpackage/Microsoft.SqlServer.Dac.Extensions.dll /opt/sqlpackage/Microsoft.SqlServer.Dac.Extensions.dll
COPY sqlpackage/Microsoft.SqlServer.Dac.Extensions.xml /opt/sqlpackage/Microsoft.SqlServer.Dac.Extensions.xml
COPY sqlpackage/SqlPackage.exe /opt/sqlpackage/SqlPackage.exe
COPY sqlpackage/SqlPackage.exe.config /opt/sqlpackage/SqlPackage.exe.config

COPY ./HAS_Database /tmp/HAS_Database

ENV ACCEPT_EULA=Y
ENV SA_PASSWORD=PaSSw0rd

RUN /opt/sqlpackage/sqlpackage /a:Publish /pr:'/tmp/HAS_Database/has.aux.ddbb.dev.publish.xml' /sf:'/tmp/HAS_Database/has.aux.ddbb.dacpac'
</code>```

This is my publish file:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <IncludeCompositeObjects>True</IncludeCompositeObjects>
    <TargetDatabaseName>HAS_ME_AUX_DEV_DEPLOY</TargetDatabaseName>
    <ScriptDatabaseOptions>False</ScriptDatabaseOptions>
    <BlockOnPossibleDataLoss>False</BlockOnPossibleDataLoss>
    <DropIndexesNotInSource>True</DropIndexesNotInSource>
    <DropExtendedPropertiesNotInSource>True</DropExtendedPropertiesNotInSource>
    <ProfileVersionNumber>1</ProfileVersionNumber>
    <BlockWhenDriftDetected>False</BlockWhenDriftDetected>
    <RegisterDataTierApplication>True</RegisterDataTierApplication>
    <TargetConnectionString>Data Source=.;Integrated Security=False;Persist Security Info=True;User ID=sa;Pooling=False;Context Connection=False;Password=PaSSw0rd</TargetConnectionString>
    <VerifyDeployment>False</VerifyDeployment>
    <VerifyCollationCompatibility>False</VerifyCollationCompatibility>
    <ScriptRefreshModule>False</ScriptRefreshModule>
    <ScriptNewConstraintValidation>False</ScriptNewConstraintValidation>
    <PopulateFilesOnFileGroups>False</PopulateFilesOnFileGroups>
    <DisableAndReenableDdlTriggers>True</DisableAndReenableDdlTriggers>
    <DoNotAlterChangeDataCaptureObjects>True</DoNotAlterChangeDataCaptureObjects>
    <DropStatisticsNotInSource>False</DropStatisticsNotInSource>
    <DeployScriptFileName>publish_dev.sql</DeployScriptFileName>
  </PropertyGroup>
</Project>

</code>```

答:
The source sqlpackage binary paths in your dockerfile look suspect. Download the Windows .NET Core zip file, extract to a directory named sqlpackage in your build context directory, and copy that directory into your container for use in the build.

Below is an example dockerfile that works for me:

```<code>FROM microsoft/mssql-server-windows-express

COPY ./sqlpackage /opt/sqlpackage/
COPY ./HAS_Database /tmp/HAS_Database

ENV ACCEPT_EULA=Y
ENV SA_PASSWORD=PaSSw0rd

RUN /opt/sqlpackage/sqlpackage /a:Publish /pr:'/tmp/HAS_Database/has.aux.ddbb.dev.publish.xml' /sf:'/tmp/HAS_Database/has.aux.ddbb.dacpac'
</code>```

Body:
I am trying to create an image with a file dockerfile and using dacpac, but when I try do publish, it throw this exception: Error parsing connection string: The type initializer for 'Microsoft.SqlServer.Dac.DacProfile' threw an exception..
This is my dockerfile

FROM microsoft/mssql-server-windows-express

COPY sqlpackage/1033 /opt/sqlpackage/1033
COPY sqlpackage/Extensions /opt/sqlpackage/Extensions
COPY sqlpackage/en /opt/sqlpackage/en
COPY sqlpackage/DacUnpack.exe /opt/sqlpackage/DacUnpack.exe
COPY sqlpackage/Microsoft.Data.Tools.Schema.Sql.dll/ /opt/sqlpackage/Microsoft.Data.Tools.Schema.Sql.dll
COPY sqlpackage/Microsoft.Data.Tools.Utilities.dll /opt/sqlpackage/Microsoft.Data.Tools.Utilities.dll
COPY sqlpackage/Microsoft.SqlServer.Dac.dll /opt/sqlpackage/Microsoft.SqlServer.Dac.dll
COPY sqlpackage/Microsoft.SqlServer.Dac.Extensions.dll /opt/sqlpackage/Microsoft.SqlServer.Dac.Extensions.dll
COPY sqlpackage/Microsoft.SqlServer.Dac.Extensions.xml /opt/sqlpackage/Microsoft.SqlServer.Dac.Extensions.xml
COPY sqlpackage/SqlPackage.exe /opt/sqlpackage/SqlPackage.exe
COPY sqlpackage/SqlPackage.exe.config /opt/sqlpackage/SqlPackage.exe.config

COPY ./HAS_Database /tmp/HAS_Database

ENV ACCEPT_EULA=Y
ENV SA_PASSWORD=PaSSw0rd

RUN /opt/sqlpackage/sqlpackage /a:Publish /pr:'/tmp/HAS_Database/has.aux.ddbb.dev.publish.xml' /sf:'/tmp/HAS_Database/has.aux.ddbb.dacpac'

This is my publish file:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <IncludeCompositeObjects>True</IncludeCompositeObjects>
    <TargetDatabaseName>HAS_ME_AUX_DEV_DEPLOY</TargetDatabaseName>

    <BlockOnPossibleDataLoss>False</BlockOnPossibleDataLoss>
    <DropIndexesNotInSource>True</DropIndexesNotInSource>
    <DropExtendedPropertiesNotInSource>True</DropExtendedPropertiesNotInSource>
    <ProfileVersionNumber>1</ProfileVersionNumber>
    <BlockWhenDriftDetected>False</BlockWhenDriftDetected>
    <RegisterDataTierApplication>True</RegisterDataTierApplication>
    <TargetConnectionString>Data Source=.;Integrated Security=False;Persist Security Info=True;User ID=sa;Pooling=False;Context Connection=False;Password=PaSSw0rd</TargetConnectionString>
    <VerifyDeployment>False</VerifyDeployment>
    <VerifyCollationCompatibility>False</VerifyCollationCompatibility>

    <PopulateFilesOnFileGroups>False</PopulateFilesOnFileGroups>
    <DisableAndReenableDdlTriggers>True</DisableAndReenableDdlTriggers>
    <DoNotAlterChangeDataCaptureObjects>True</DoNotAlterChangeDataCaptureObjects>
    <DropStatisticsNotInSource>False</DropStatisticsNotInSource>
    <DeployScriptFileName>publish_dev.sql</DeployScriptFileName>
  </PropertyGroup>
</Project>

Body:
The source sqlpackage binary paths in your dockerfile look suspect. Download the Windows .NET Core zip file, extract to a directory named sqlpackage in your build context directory, and copy that directory into your container for use in the build.

Below is an example dockerfile that works for me:

FROM microsoft/mssql-server-windows-express

COPY ./sqlpackage /opt/sqlpackage/
COPY ./HAS_Database /tmp/HAS_Database

ENV ACCEPT_EULA=Y
ENV SA_PASSWORD=PaSSw0rd

RUN /opt/sqlpackage/sqlpackage /a:Publish /pr:'/tmp/HAS_Database/has.aux.ddbb.dev.publish.xml' /sf:'/tmp/HAS_Database/has.aux.ddbb.dacpac'


问:
c# find if whether the number is happy or not
Im trying to understund how do I find whether the number is Happy Number or not,
I know that i need to check if the unit digit and the digit in the highest number location are greater
then the numbers in the middele.
`example:
given number: 63240
the unit: 6
the number in the highest location:0
are both of them greater then 3 and 2 and4(middle) ? yes
result: true (for that case)

the quation is:
write a program that get a number from user, the program will print if the given number from the user is a happy number or not

I know how to find the units and the highest number location, but got stack figure it out how to
how to use the digits in the middle in order to find the answer for that..

notice that the only class we've learned so fat is Math,(not even string yes)
we also learned while and for but nothing so far..

I also know that in order to go through all digit in given number i need to use the while loop,
but I dont know how do I use it in order to use them to get to the answer..

my code so far:

```<code>int number;
int units;
int highestDigitLoc;

bool isHappyNumber = true;
int count = 0;

Console.WriteLine("enter a number:");
number = int.Parse(Console.ReadLine());

while(number > 0)
{
    count++;

    units = number % 10;
    highestDigitLoc = number / 10;
}
</code>```

thanks

答:
Well, your question very vague, however, we can turn the number into an array of digits int[] digits

```<code>using System.Linq;

...

int[] digits = null;

while (true) {
  Console.WriteLine("enter a number:");

  // string : let's solve for arbitrary long numbers (no necessary int)
  string number = Console.ReadLine().Trim();

  if (string.IsNullOrEmpty(number))
    Console.WriteLine("Empty string is not enough");
  else if (number.All(c => c >= '0' && c <= '9')) {
     // This code preserves leading zeroes
     digits = number.Select(c => c - '0').ToArray();
     // This code removes leading zeroes
     //digits = number
     //  .SkipWhile(c => c == '0')
     //  .Select(c => c - '0')
     //  .DefaultIfEmpty()
     //  .ToArray();

    break;
  }
  else
    Console.Write("Not a valid integer value. Please, try again.");
}
</code>```

Then we can use this int[] digits to implement any logic required.
Please, note, that we preserve leading zeroes:

```<code>"63240"  -> int[] {6, 3, 4, 2, 0}
"063240" -> int[] {0, 6, 3, 4, 2, 0}
</code>```

e.g.

let a number be happy if and only if

It contains at least 3 digits (in order to have middle ones)

Max of the first and last digits is greater than max of all the other digits

In our case with 63240

63240 has 5 digits, the condition holds

Max(0, 6) == 6 > Max(3, 2, 4) == 4, the condition holds

Code:

```<code>bool isHappyNumber =
  digits.Length >= 3 &&
  Math.Max(digits[0], digits[digits.Length - 1]) >
    digits.Skip(1).Take(digits.Length - 2).Max();
</code>```

Edit: let's implement isHappyNumber with good old for loops:

```<code>int maxFirstAndLast = digits[0] > digits[digits.Length - 1]
  ? digits[0]
  : digits[digits.Length - 1];

int maxMiddle = 0;

for (int i = 1; i < digits.Length - 1; ++i)
  if (digits[i] > maxMiddle) then
    maxMiddle = digits[i];

bool isHappyNumber =
  digits.Length >= 3 &&
  maxFirstAndLast > maxMiddle;
</code>```

Body:
Im trying to understund how do I find whether the number is Happy Number or not,
I know that i need to check if the unit digit and the digit in the highest number location are greater
then the numbers in the middele.
`example:
given number: 63240
the unit: 6
the number in the highest location:0
are both of them greater then 3 and 2 and4(middle) ? yes
result: true (for that case)

the quation is:
write a program that get a number from user, the program will print if the given number from the user is a happy number or not

I know how to find the units and the highest number location, but got stack figure it out how to
how to use the digits in the middle in order to find the answer for that..

notice that the only class we've learned so fat is Math,(not even string yes)
we also learned while and for but nothing so far..

I also know that in order to go through all digit in given number i need to use the while loop,
but I dont know how do I use it in order to use them to get to the answer..

my code so far:

int number;
int units;
int highestDigitLoc;

bool isHappyNumber = true;
int count = 0;

Console.WriteLine("enter a number:");
number = int.Parse(Console.ReadLine());

while(number > 0)
{
    count++;

    units = number % 10;
    highestDigitLoc = number / 10;
}

thanks

Body:
Well, your question very vague, however, we can turn the number into an array of digits int[] digits

using System.Linq;

...

int[] digits = null;

while (true) {
  Console.WriteLine("enter a number:");

  // string : let's solve for arbitrary long numbers (no necessary int)
  string number = Console.ReadLine().Trim();

  if (string.IsNullOrEmpty(number))
    Console.WriteLine("Empty string is not enough");
  else if (number.All(c => c >= '0' && c <= '9')) {
     // This code preserves leading zeroes
     digits = number.Select(c => c - '0').ToArray();
     // This code removes leading zeroes
     //digits = number
     //  .SkipWhile(c => c == '0')
     //  .Select(c => c - '0')
     //  .DefaultIfEmpty()
     //  .ToArray();

    break;
  }
  else
    Console.Write("Not a valid integer value. Please, try again.");
}

Then we can use this int[] digits to implement any logic required.
Please, note, that we preserve leading zeroes:

"63240"  -> int[] {6, 3, 4, 2, 0}
"063240" -> int[] {0, 6, 3, 4, 2, 0}

e.g.

let a number be happy if and only if

It contains at least 3 digits (in order to have middle ones)

Max of the first and last digits is greater than max of all the other digits

In our case with 63240

63240 has 5 digits, the condition holds

Max(0, 6) == 6 > Max(3, 2, 4) == 4, the condition holds

Code:

bool isHappyNumber =
  digits.Length >= 3 &&
  Math.Max(digits[0], digits[digits.Length - 1]) >
    digits.Skip(1).Take(digits.Length - 2).Max();

Edit: let's implement isHappyNumber with good old for loops:

int maxFirstAndLast = digits[0] > digits[digits.Length - 1]
  ? digits[0]
  : digits[digits.Length - 1];

int maxMiddle = 0;

for (int i = 1; i < digits.Length - 1; ++i)
  if (digits[i] > maxMiddle) then
    maxMiddle = digits[i];

bool isHappyNumber =
  digits.Length >= 3 &&
  maxFirstAndLast > maxMiddle;


问:
LegacySameSiteCookieBehaviorEnabled=0 in the registry impacts to application authentication process
I have a asp.net mvc4 application with .NETFramework 4.6, with AzureAD authentication and OpenID Connect protocol. Now with recent updates to Chrome80 SameSite=None update , application authentication is failing.

Here goes the Testing instructions:
https://learn.microsoft.com/en-us/office365/troubleshoot/miscellaneous/chrome-behavior-affects-applications#testing-guidelines

I used the below mentioned article which uses URLRewrite module to setup SameSite=None :

https://blog.elmah.io/the-ultimate-guide-to-secure-cookies-with-web-config-in-net/

```<code><system.webServer>
  <rewrite>
   <outboundRules>
        <rule name="Remove Server Header">
          <match serverVariable="RESPONSE_Server" pattern=".+" />
          <action type="Rewrite" value="" />
        </rule>
        <rule name="Add SameSite" preCondition="No SameSite">
          <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />
          <action type="Rewrite" value="{R:0}; SameSite=None" />
        </rule>
        <preConditions>
          <preCondition name="No SameSite">
            <add input="{RESPONSE_Set_Cookie}" pattern="." />
            <add input="{RESPONSE_Set_Cookie}" pattern="; SameSite=None" negate="true" />
          </preCondition>
        </preConditions>
</outboundRules>
  </rewrite>
  ...
</system.webServer>
</code>```

Update the flags in Chrome browser to Enabled:

Setting the value of LegacySameSiteCookieBehaviorEnabled in registry to 1 leads to successful application authentication but whereas if the LegacySameSiteCookieBehaviorEnabled is setup to 0 , then in case the application authentication is failing.

Can anyone help me to know how to fix this issue?

答:
It looks like you're mixing Chrome flags (chrome://flags/#same-site-by-default-cookies) with Chrome Enterprise Policy - LegacySameSiteCookieBehaviorEnabled.

The Chrome Enterprise Policies are intended for organisations that are maintaining legacy applications where the cookies are not easily updated. By setting that to 1 you are explicitly maintaining the old behaviour of cookies. If that's really what you want to do though, I would look at the more specific LegacySameSiteCookieBehaviorEnabledForDomainList policy.

However, since you are attempting to update your app, I would ensure that you do not have either of the policies set, so that you can ensure the new behaviour is being enforced. You can visit https://samesite-sandbox.glitch.me and if all the rows are green, then the new behaviour is enabled in your browser.

I'm not sure about your cookie rules, however I don't see you explicitly adding Secure to your SameSite=None cookies. Both of these must be set. I would also ensure that you are not simply adding SameSite=None; Secure to every singly cookie. Just do this for the ones you know need to be access from third-party contexts. For other cookies, consider SameSite=Lax.

If you need to see which cookies are being blocked on requests, you can check the network tab in Chrome DevTools. Specifically, select a request and check the cookies tab in there. You can find detailed instructions on https://www.chromium.org/updates/same-site/test-debug

Body:
I have a asp.net mvc4 application with .NETFramework 4.6, with AzureAD authentication and OpenID Connect protocol. Now with recent updates to Chrome80 SameSite=None update , application authentication is failing.

Here goes the Testing instructions:
https://learn.microsoft.com/en-us/office365/troubleshoot/miscellaneous/chrome-behavior-affects-applications#testing-guidelines

I used the below mentioned article which uses URLRewrite module to setup SameSite=None :

https://blog.elmah.io/the-ultimate-guide-to-secure-cookies-with-web-config-in-net/

<system.webServer>
  <rewrite>
   <outboundRules>
        <rule name="Remove Server Header">
          <match serverVariable="RESPONSE_Server" pattern=".+" />
          <action type="Rewrite" value="" />
        </rule>
        <rule name="Add SameSite" preCondition="No SameSite">
          <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />
          <action type="Rewrite" value="{R:0}; SameSite=None" />
        </rule>
        <preConditions>
          <preCondition name="No SameSite">
            <add input="{RESPONSE_Set_Cookie}" pattern="." />
            <add input="{RESPONSE_Set_Cookie}" pattern="; SameSite=None" negate="true" />
          </preCondition>
        </preConditions>
</outboundRules>
  </rewrite>
  ...
</system.webServer>

Update the flags in Chrome browser to Enabled:

Setting the value of LegacySameSiteCookieBehaviorEnabled in registry to 1 leads to successful application authentication but whereas if the LegacySameSiteCookieBehaviorEnabled is setup to 0 , then in case the application authentication is failing.

Can anyone help me to know how to fix this issue?


问:
What's the name of the part of the URL before the query string?
Take the following URL: http://3.chart.apis.google.com/chart?cht=p&chd=t:1,2,3&chl=a|b|c&chs=300x100

It can be broken down as follows:

Protocol: http

Hostname: 3.chart.apis.google.com

Path: chart

Query: cht=p&chd=t:1,2,3&chl=a|b|c&chs=300x100

I'm looking for the name of the protocol, hostname and path? i.e. everything up to the query string.

答:
there is no canonical name for those parts of the URL (or URI if you like) up to but not including the querystring. the entirety of that string is a URL which consists of:

Scheme/Protocol

   Domain

   Port (Assumed as default for protocol if not specified)

   Path

   Querystring

see: http://en.wikipedia.org/wiki/Uniform_Resource_Locator


问:
MacOS Clipboard Set-Path equivalent
I'm looking for a feature like Set-Path (Windows) but for MacOS. The way Set-Path works in Windows is, in Powershell you do

```<code>SET-PATH C:\my\file\path.jpg
</code>```

which will then copy said file to the clipboard.

Is there a similar command in MacOS? With my current use-case, I need to copy a file by using a reference path programmatically.

Note: I am not looking to copy the contents within the file, as it may be an arbitrary file type.

答:
If I'm understanding the question right, what you're after is pbcopy and pbpaste.

Open a terminal and do:

$ cat C:\my\file\path.jpg | pbcopy

Now that file is in the clipboard.

To put it somewhere else, that is, to paste it, do:

$ pbpaste > C:\my\file\path\somewhere\

Title: MacOS Clipboard Set-Path equivalent

Body:
I'm looking for a feature like Set-Path (Windows) but for MacOS. The way Set-Path works in Windows is, in Powershell you do

SET-PATH C:\my\file\path.jpg

which will then copy said file to the clipboard.

Is there a similar command in MacOS? With my current use-case, I need to copy a file by using a reference path programmatically.

Note: I am not looking to copy the contents within the file, as it may be an arbitrary file type.


问:
Save ID in variable and add style to it
I want to highlight randomly a word which is inside a
 tag with the id=JShighlight. It should blink one time and then another randomly chosen word should blink.** I can't add the css style needed to the ID.

The words are nested in a span with an unique id like id="one" oder id="two".
Like:

```<code><p id="JShighlight"> <span id="one">Lorem </span><span id="two">Ipsum </span><span id="three">Dolores</span></p>
</code>```

To chose a word randomly, I build an array with the child-nodes of JShighlight. And call it childNodeArray

```<code>let childNodeArray = document.getElementById('JShighlight').children;
</code>```

Then I randomly chose an index:

```<code>  let i = Math.floor(Math.random() * childNodeArray.length);
</code>```

The variable name saves the randomly chosen ID.

```<code>let name = childNodeArray[i].id;
</code>```

To this randomly chosen word /Id I want to add a certain style so that this word blinks one time.
I tried:

```<code>name.classList.add("blinking");
</code>```

(.blinking is the css-class:

```<code>.blinking {
    animation: blinkingText 0.6s 1;
    /* animation-iteration-count: 1; */
}
</code>```

)

But it does not work.
What "works" is:

```<code>document.getElementById(name).style.color = "red";
</code>```

Why can I pass a variable as an argument in the latter case and not in the former case?
How can I append a css class to an variable ID?

答:
use Array.from to convert children DOM list to array of DOM elements. Also remove the id attribute before storing the name refer variable.

Please update the below lines.

```<code>let childNodeArray = Array.from(document.getElementById('JShighlight').children);
let i = Math.floor(Math.random() * childNodeArray.length);
let name = childNodeArray[i];
name.classList.add("blinking");
</code>```

Title: Save ID in variable and add style to it

Body:
I want to highlight randomly a word which is inside a
 tag with the id=JShighlight. It should blink one time and then another randomly chosen word should blink.** I can't add the css style needed to the ID.

The words are nested in a span with an unique id like id="one" oder id="two".
Like:

 Lorem Ipsum Dolores

To chose a word randomly, I build an array with the child-nodes of JShighlight. And call it childNodeArray

let childNodeArray = document.getElementById('JShighlight').children;

Then I randomly chose an index:

  let i = Math.floor(Math.random() * childNodeArray.length);

The variable name saves the randomly chosen ID.

let name = childNodeArray[i].id;

To this randomly chosen word /Id I want to add a certain style so that this word blinks one time.
I tried:

name.classList.add("blinking");

(.blinking is the css-class:

.blinking {
    animation: blinkingText 0.6s 1;
    /* animation-iteration-count: 1; */
}

)

But it does not work.
What "works" is:

document.getElementById(name).style.color = "red";

Why can I pass a variable as an argument in the latter case and not in the former case?
How can I append a css class to an variable ID?

Body:
use Array.from to convert children DOM list to array of DOM elements. Also remove the id attribute before storing the name refer variable.

Please update the below lines.

let childNodeArray = Array.from(document.getElementById('JShighlight').children);
let i = Math.floor(Math.random() * childNodeArray.length);
let name = childNodeArray[i];
name.classList.add("blinking");


问:
Postgresql - Map array aggregates into a single array in a particular order
I have a PostgreSQL table containing a column of 1 dimensional array data. I wish to perform an aggregate query on this column, obtaining min/max/mean for each element of the array as well as the group count, returning the result as a 1 dimensional array. The array lengths in the table may vary, but I can be certain that in any grouping I perform, all arrays will be of the same length.

In a simple form, say my arrays are of length 2 and have readings for x and y, I want to return the result as
{Min(x), Max(x), Mean(x), Min(y), Max(y), Mean(y), Count()}

I am able to get a result in the form {Min(x), Min(y), Max(x), Max(y), Mean(x), Mean(y) Count()} but I can't get from there to my desired result.

Here's an example showing where I am so far (this time with arrays of length 3, but without the mean aggregation as there isnt one for arrays built in to pgSql):
(SQLFiddle here)

```<code>CREATE TABLE my_test(some_key numeric, event_data bigint[]);

INSERT INTO my_test(some_key, event_data) VALUES
(1, {11,12,13}),
(1, {5,6,7}),
(1, {-11,-12,-13});

SELECT MIN(event_data) || MAX(event_data) || COUNT(event_data)  FROM my_test GROUP BY some_key;
</code>```

The above gives me

{11,12,13,-11,-12,-13,3}

However, I don't know how to transform a result like the above into what I want, which is:

{11,-11,12,-12,13,-13,3}

What function should I use to transform the above?

Note that the aggregation functions above don't exactly match with those I am using to get min, max - I'm using the aggs_for_vecs extension to give me min, max and mean.

答:
I would recommend using array operations and aggregation:

```<code>select x.some_key,
       array_agg(u.val order by x.n, u.nn)
from (select t.some_key, ed.n, min(val) as minval, max(val) as maxval
      from my_test t cross join lateral
           unnest(t.event_data) with ordinality as ed(val, n)
      group by t.some_key, ed.n
     ) x cross join lateral
     unnest(array[x.minval, x.maxval]) with ordinality u(val, nn)
group by x.some_key;
</code>```

Personally, I would prefer an array with three elements and the min/max as a record:

```<code>select x.some_key, array_agg((x.minval, x.maxval) order by x.n)
from (select t.some_key, ed.n, min(val) as minval, max(val) as maxval
      from my_test t cross join lateral
           unnest(t.event_data) with ordinality as ed(val, n)
      group by t.some_key, ed.n
     ) x
group by x.some_key;
</code>```

Here is a db<>fiddle.

Body:
I have a PostgreSQL table containing a column of 1 dimensional array data. I wish to perform an aggregate query on this column, obtaining min/max/mean for each element of the array as well as the group count, returning the result as a 1 dimensional array. The array lengths in the table may vary, but I can be certain that in any grouping I perform, all arrays will be of the same length.

In a simple form, say my arrays are of length 2 and have readings for x and y, I want to return the result as
{Min(x), Max(x), Mean(x), Min(y), Max(y), Mean(y), Count()}

I am able to get a result in the form {Min(x), Min(y), Max(x), Max(y), Mean(x), Mean(y) Count()} but I can't get from there to my desired result.

Here's an example showing where I am so far (this time with arrays of length 3, but without the mean aggregation as there isnt one for arrays built in to pgSql):
(SQLFiddle here)

CREATE TABLE my_test(some_key numeric, event_data bigint[]);

INSERT INTO my_test(some_key, event_data) VALUES
(1, {11,12,13}),
(1, {5,6,7}),
(1, {-11,-12,-13});

SELECT MIN(event_data) || MAX(event_data) || COUNT(event_data)  FROM my_test GROUP BY some_key;

The above gives me

{11,12,13,-11,-12,-13,3}

However, I don't know how to transform a result like the above into what I want, which is:

{11,-11,12,-12,13,-13,3}

What function should I use to transform the above?

Note that the aggregation functions above don't exactly match with those I am using to get min, max - I'm using the aggs_for_vecs extension to give me min, max and mean.

Body:
I would recommend using array operations and aggregation:

select x.some_key,
       array_agg(u.val order by x.n, u.nn)
from (select t.some_key, ed.n, min(val) as minval, max(val) as maxval
      from my_test t cross join lateral
           unnest(t.event_data) with ordinality as ed(val, n)
      group by t.some_key, ed.n
     ) x cross join lateral
     unnest(array[x.minval, x.maxval]) with ordinality u(val, nn)
group by x.some_key;

Personally, I would prefer an array with three elements and the min/max as a record:

select x.some_key, array_agg((x.minval, x.maxval) order by x.n)
from (select t.some_key, ed.n, min(val) as minval, max(val) as maxval
      from my_test t cross join lateral
           unnest(t.event_data) with ordinality as ed(val, n)
      group by t.some_key, ed.n
     ) x
group by x.some_key;

Here is a db<>fiddle.


问:
In pyspark I want to pass a dataframe column of values to a function and manipulate say, t the 5th value, in that columns of data
I'm using pySpark V2 on an EMR cluster on AWS and I'm trying to pass a dataframe column to a function and manipulate the individual items within the column

Let's say I have the following set up:

```<code>mylist = [x for x in range(0, 10)]
df=spark.createDataFrame(mylist,IntegerType())
df.show()

+-----+
|value|
+-----+
|    0|
|    1|
|    2|
|    3|
|    4|
|    5|
|    6|
|    7|
|    8|
|    9|
+-----+
</code>```

I want to have a function that performs a test on say, the value contained on row 5 of the data column and depending on what it finds, assigns that value to a new variable and perhaps do some other manipulations of the new variable

e.g

```<code>myfunc(df.value)

def myfunc(df_col):
#
#   In psuedocode:
#   x = value in row 5 of the data
#   if x = whatever:
#       do something with x
#
</code>```

Can anyone help me out. Just seem to have hit a mental roadblock with this

答:
Thanks for the link given. it was helpful. Here is one possible answer</p>

```<code>from pyspark.sql.types import *
mylist = [x for x in range(0, 10)]
df=spark.createDataFrame(mylist,IntegerType())
df.show()
rn=df.collect()[4]
x=rn.value
if(x == 4):
  print("fifth row value = ", str(x))
</code>```

```<code>+-----+
|value|
+-----+
|    0|
|    1|
|    2|
|    3|
|    4|
|    5|
|    6|
|    7|
|    8|
|    9|
+-----+

fifth row value =  4
</code>```

Body:
I'm using pySpark V2 on an EMR cluster on AWS and I'm trying to pass a dataframe column to a function and manipulate the individual items within the column

Let's say I have the following set up:

mylist = [x for x in range(0, 10)]
df=spark.createDataFrame(mylist,IntegerType())
df.show()

+-----+
|value|
+-----+
|    0|
|    1|
|    2|
|    3|
|    4|
|    5|
|    6|
|    7|
|    8|
|    9|
+-----+

I want to have a function that performs a test on say, the value contained on row 5 of the data column and depending on what it finds, assigns that value to a new variable and perhaps do some other manipulations of the new variable

e.g

myfunc(df.value)

def myfunc(df_col):
#
#   In psuedocode:
#   x = value in row 5 of the data
#   if x = whatever:
#       do something with x
#

Can anyone help me out. Just seem to have hit a mental roadblock with this

Body:
Thanks for the link given. it was helpful. Here is one possible answer

from pyspark.sql.types import *
mylist = [x for x in range(0, 10)]
df=spark.createDataFrame(mylist,IntegerType())
df.show()
rn=df.collect()[4]
x=rn.value
if(x == 4):
  print("fifth row value = ", str(x))

+-----+
|value|
+-----+
|    0|
|    1|
|    2|
|    3|
|    4|
|    5|
|    6|
|    7|
|    8|
|    9|
+-----+

fifth row value =  4


问:
Library - Plugin with id "com.android.library" not found
I just pulled an old project that its a library. I had to edit this to generate a new aar and include it again in my main project.

When i pulled the project and tried to open it i got that error of the tittle.
"ERROR: Plugin with id 'com.android.library' not found."

I have only one gradle (build.gradle) and it is this one.

```<code>apply plugin: 'com.android.library'

android {
compileSdkVersion 28

lintOptions {
    abortOnError false
}
defaultConfig {
    minSdkVersion 18
    targetSdkVersion 28
    versionCode 1000000
    versionName "1.0.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField "String", 'BASE_URL', '"https://d.api.redlink.com.ar/redlink/desarrollo/"'

    }
    debug {
        buildConfigField "String", 'BASE_URL', '"https://d.api.redlink.com.ar/redlink/desarrollo/"'
    }
}

configurations {
    retrofit
}
</code>```

}

```<code>dependencies {
    api fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'
    implementation 'com.android.support:appcompat-v7:28.0.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

答:
You can try adding below code in your build.gradle file (at the same level as defaultConfig)

```<code>buildscript {
    repositories {
        mavenCentral()
    }
}
</code>```

It should resolve your problem.

Body:
I just pulled an old project that its a library. I had to edit this to generate a new aar and include it again in my main project.

When i pulled the project and tried to open it i got that error of the tittle.
"ERROR: Plugin with id 'com.android.library' not found."

I have only one gradle (build.gradle) and it is this one.

apply plugin: 'com.android.library'

android {
compileSdkVersion 28

lintOptions {
    abortOnError false
}
defaultConfig {
    minSdkVersion 18
    targetSdkVersion 28
    versionCode 1000000
    versionName "1.0.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        buildConfigField "String", 'BASE_URL', '"https://d.api.redlink.com.ar/redlink/desarrollo/"'

    }
    debug {
        buildConfigField "String", 'BASE_URL', '"https://d.api.redlink.com.ar/redlink/desarrollo/"'
    }
}

configurations {
    retrofit
}

}

dependencies {
    api fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'
    implementation 'com.android.support:appcompat-v7:28.0.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Body:
You can try adding below code in your build.gradle file (at the same level as defaultConfig)

buildscript {
    repositories {
        mavenCentral()
    }
}

It should resolve your problem.


问:
How to find the count of items in an ngFor after the pipes have been applied
I have an ngFor creating rows in a table that is both filtered and paged.

```<code><tr *ngFor="#d of data.results | filter:filterText | pagination:resultsPerPage:currentPage">
</code>```

There is another element on the page that displays the number of records displayed. These elements are initially bound to the data.Results' length.

How do I get the length of the data that is displayed after the filter pipe has been applied so that I can display it correctly.  None of the provided local variables in ngFor seem to account for this.

答:
Assume your ngFor looks something like:

```<code><div #cardHolder>
    <app-card *ngFor="let card of cards|pipeA:paramX|pipeB:paramY"></app-card>
</div>
</code>```

Then in your component you may use something like:

```<code> get displayedCards() : number {
    let ch = this.cardHolder.nativeElement;

    // In case cardHolder has not been rendered yet...
    if(!ch)
      return 0;

    return ch.children.length;

  }
</code>```

Which you may display in your view by simple interpolation

```<code>{{displayedCards}}
</code>```

Advantages include not needing to modify the pipes to return additional data.

Body:
I have an ngFor creating rows in a table that is both filtered and paged.

There is another element on the page that displays the number of records displayed. These elements are initially bound to the data.Results' length.

How do I get the length of the data that is displayed after the filter pipe has been applied so that I can display it correctly.  None of the provided local variables in ngFor seem to account for this.

Body:
Assume your ngFor looks something like:

<div #cardHolder>
    <app-card *ngFor="let card of cards|pipeA:paramX|pipeB:paramY"></app-card>
</div>

Then in your component you may use something like:

 get displayedCards() : number {
    let ch = this.cardHolder.nativeElement;

    // In case cardHolder has not been rendered yet...
    if(!ch)
      return 0;

    return ch.children.length;

  }

Which you may display in your view by simple interpolation

{{displayedCards}}

Advantages include not needing to modify the pipes to return additional data.


问:
How do I find out my MySQL URL, host, port and username?
I need to find my MySQL username. When I open the MySQL command line client, it only asks me for my password. I don't remember my username. And for connectivity with JDBC, I need the URL, host and port number. Where do I find all of these?</p>

答:
Easiest way is probably using command status; In the output you'll find database, user, host and port:

```<code>mysql> status;
--------------
mysql  Ver 8.0.13 for Win64 on x86_64 (MySQL Community Server - GPL)

Connection id:          43
Current database:       mysql
Current user:           user@localhost
SSL:                    Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter:        ;
Server version:         8.0.13 MySQL Community Server - GPL
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    cp852
Conn.  characterset:    cp852
TCP port:               3306
Uptime:                 3 hours 32 min 40 sec

Threads: 3  Questions: 197  Slow queries: 0  Opens: 214  Flush tables: 2  Open tables: 190  Queries per second avg: 0.015
--------------
</code>```

OwnerDisplayName: shilps

Body:
Easiest way is probably using command status; In the output you'll find database, user, host and port:

mysql> status;
--------------
mysql  Ver 8.0.13 for Win64 on x86_64 (MySQL Community Server - GPL)

Connection id:          43
Current database:       mysql
Current user:           user@localhost
SSL:                    Cipher in use is DHE-RSA-AES128-GCM-SHA256
Using delimiter:        ;
Server version:         8.0.13 MySQL Community Server - GPL
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    cp852
Conn.  characterset:    cp852
TCP port:               3306
Uptime:                 3 hours 32 min 40 sec

Threads: 3  Questions: 197  Slow queries: 0  Opens: 214  Flush tables: 2  Open tables: 190  Queries per second avg: 0.015
--------------


问:
How do I import/use wp.blockEditor correctly?
I'm trying to write a Gutenberg-Block using create-guten-block. When I run it, I get a number of warnings in the console that a few elements I'm using are deprecated:

```<code>deprecated.min.js?ver=2.6.1:1 wp.editor.RichText.Content is deprecated. Please use wp.blockEditor.RichText.Content instead.
</code>```

Accordingly, I made some changes to my code. In my "blocks.js" I changed the declaration from

```<code>const {RichText} = wp.editor;
</code>```

to:

```<code>const {RichText} = wp.blockEditor;
</code>```

And within "init.php" I imported "wp-block-editor" where previously I had imported "wp-editor". RichText serves as an example here; I get the same warning for other elements from wp.blockEditor, like ColorPalette and InspectorControls.

When I test it, the block works just like before after including these changes, but I still get the same warning message. It drives me nuts because I have a problem with my RichText elements and I don't know whether it has anything to do with this, so I'd like to exclude this possibility.

I'm a beginner in general and I haven't worked with react before (nor with wordpress/gutenberg), so I don't yet fully understand what I'm doing here. I assume I'm making a silly error somewhere, but I can't figure out why this isn't working. Any help is appreciated!

答:
I'm not quite sure, but I think the dependency is still wp-editor.
You are destructuring the wp.blockEditor object (see: https://wesbos.com/destructuring-objects/).
You could as well use wp.blockEditor.RichText to access the component.</p>

Body:
I'm trying to write a Gutenberg-Block using create-guten-block. When I run it, I get a number of warnings in the console that a few elements I'm using are deprecated:

deprecated.min.js?ver=2.6.1:1 wp.editor.RichText.Content is deprecated. Please use wp.blockEditor.RichText.Content instead.

Accordingly, I made some changes to my code. In my "blocks.js" I changed the declaration from

const {RichText} = wp.editor;

to:

const {RichText} = wp.blockEditor;

And within "init.php" I imported "wp-block-editor" where previously I had imported "wp-editor". RichText serves as an example here; I get the same warning for other elements from wp.blockEditor, like ColorPalette and InspectorControls.

When I test it, the block works just like before after including these changes, but I still get the same warning message. It drives me nuts because I have a problem with my RichText elements and I don't know whether it has anything to do with this, so I'd like to exclude this possibility.

I'm a beginner in general and I haven't worked with react before (nor with wordpress/gutenberg), so I don't yet fully understand what I'm doing here. I assume I'm making a silly error somewhere, but I can't figure out why this isn't working. Any help is appreciated!


问:
Update with Looping SQL Server
I want to update Result row 1 = 15, row 2 = 5, row 3 = 30 with Looping:

答:
You can do JOIN :

```<code>UPDATE t1
     SET t1.Result = t.Result
FROM ( VALUES (1, 15), (2, 5), (3, 30)
     ) t(C,Result) INNER JOIN
     table t1
     on t1.c = t.c;
</code>```

Title: Update with Looping SQL Server

Body:
You can do JOIN :

UPDATE t1
     SET t1.Result = t.Result
FROM ( VALUES (1, 15), (2, 5), (3, 30)
     ) t(C,Result) INNER JOIN
     table t1
     on t1.c = t.c;


问:
How to import website graph data into google sheets
Essentially I'm working on a presentation and I would like to import this graph into google sheets it does not have to look the same I just need the data. I don't program in HTML so I'm not really sure what to do does anyone have ideas on how I could extract this graph data.

```<code>https://digitalik.net/btc/sf_model/#
</code>```

I've tried using google sheets built-in HTML graph function but for some reason, it can't detect it so an alternative would be to download the data as an XML and paste it into sheets so that's also an option.

答: unfortunately not possible for a given site because it uses JavaScript and Google Sheets does not support web scraping of JS elements. you can test this simply by disabling JS for a given site and what's left can be scraped. in your case its nothing:

Body:
Essentially I'm working on a presentation and I would like to import this graph into google sheets it does not have to look the same I just need the data. I don't program in HTML so I'm not really sure what to do does anyone have ideas on how I could extract this graph data.

https://digitalik.net/btc/sf_model/#

I've tried using google sheets built-in HTML graph function but for some reason, it can't detect it so an alternative would be to download the data as an XML and paste it into sheets so that's also an option.


问:
wifiManager.AddNetwork return -1 in android 10
when we select target sdk to android 9 means pi then all works fine but when we select the target sdk to 10 then wifiManager.AddNetwork(config) return -1 .</p>

答:
sdk to 10 then wifiManager.AddNetwork(config) return -1 .

For applications targeting Build.VERSION_CODES.Q or above, this API will always return -1.

This method was deprecated in API level 29.
  a) See WifiNetworkSpecifier.Builder#build() for new mechanism to trigger connection to a Wi-Fi network. b) See addNetworkSuggestions(java.util.List), removeNetworkSuggestions(java.util.List) for new API to add Wi-Fi networks for consideration when auto-connecting to wifi.

re: https://developer.android.com/reference/android/net/wifi/WifiManager#addNetwork(android.net.wifi.WifiConfiguration)


问:
Moved from bash to zsh - some commands / binaries not recognised
I've recently started using zsh. I notice some commands which work in bash no longer work in zsh. In particular, I'm using virtualenv with virtualenvwrapper for Python virtual environments, which has the command workon to change the current virtual environment. When I run bash, it recognises this command, but when running zsh, this command is not recognised.

Where does the shell look for these binaries? How can I point zsh to this binary when I use this or similar commands?

To clarify, my default shell is now zsh, when I enter bash to start running bash, the command is recognised, and when I enter zsh it is no longer recognised. The path is therefore the same when running both commands

Running Linux Mint 19.3

答:
The command workon is defined in a script to be sourced by the shell.
With bash, you typically edit .bashrc or .profile to make it happen whenever the shell is opened.

You can do the same for zsh, but you need to carry over the lines from the file you edited to a different file, e.g. .zprofile.

See https://superuser.com/questions/187639/zsh-not-hitting-profile and https://virtualenvwrapper.readthedocs.io/en/latest/install.html for more information.


问:
How to convert from one date time format to another in pandas?
I have a pandas dataframe where the date times can be either in the format Wed Oct 02 10:55:08 BST 2019 or
Wed Oct 02 10:55:08 GMT 2019.

I want all the these date times to be in datetimes in the format of 2019-01-10 10:55:08 where the times are GMT.

Thanks

答:
You need to use from datetime of the standard library and convert to date time     </p>

```<code>from datetime import datetime

df['datecolumn'].apply(lambda x:
   datetime.strptime(x, "%a %b %d %I:%M:%S GMT %Y") if 'GMT' in x else x)
</code>```

Body:
You need to use from datetime of the standard library and convert to date time

from datetime import datetime

df['datecolumn'].apply(lambda x:
   datetime.strptime(x, "%a %b %d %I:%M:%S GMT %Y") if 'GMT' in x else x)


问:
Load images on demand into FlowLayoutPanel?
i want to populate a flowlayoutpanel with many images (~400pc., 500x500px).
I loop through a string list with the filenames and add this pics to the flp.
But above ~200 images the panel doesn't show more images.

I think it's a perfomance problem and i want to ask, wether it is possible to load the images  "on demand"?

Like scrolling through the panel and only load the "visible" image?

For panel filling i use this:

```<code>public void PanelFill(List<string> filenames)
{
    try
    {
        int temp = 0;
        foreach (string filename in filenames)
        {
            GC.Collect();
            PictureBox pic = new PictureBox
            {
                ClientSize = new Size(int_thumbWidth, int_thumbHeight),
                //Image = new Bitmap(filename),
                Tag = filename,
                BorderStyle = BorderStyle.FixedSingle
            };
            if ((pic.Image.Width > int_thumbWidth) ||
                (pic.Image.Height > int_thumbHeight))
            {
                pic.SizeMode = PictureBoxSizeMode.Zoom;
            }
            else
            {
                pic.SizeMode = PictureBoxSizeMode.CenterImage;
            }
            flowLayoutPanel_esww_bildvergleich.Invoke(new Action(() => { pic.Parent = flowLayoutPanel_esww_bildvergleich; }));
            pic.Click += PictureBox_Click;
            pic.DoubleClick += PictureBox_DoubleClick;
            pic.MouseUp += PictureBox_MouseUp;
            temp++;
        }
    }
    catch (OutOfMemoryException)
    {
        MessageBox.Show("Es wurden zu viele Fotos gefunden. Der Arbeitsspeicher ist nicht ausreichend. Bitte passen Sie Ihre Filter an.", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
        str_aufnahmeTyp.Clear();
    }
    catch (Exception ex)
    {
        Fehlerbehandlung.Fehler(-1, ex.Message);
    }
}
</code>```

答:
A workaround for me is to add a Scroll/MouseEnter- Eventhandler for catching the scrolling through the panel.
In the handler i use .PerformLayout()

```<code> this.flowLayoutPanel_esww_bildvergleich.MouseEnter += new System.EventHandler(this.flowLayoutPanel_esww_bildvergleich_MouseEnter);
</code>```

and...

```<code>        private void flowLayoutPanel_esww_bildvergleich_MouseEnter(object sender, EventArgs e)
    {
        flowLayoutPanel_esww_bildvergleich.Focus();
        flowLayoutPanel_esww_bildvergleich.PerformLayout();
    }
</code>```

Body:
i want to populate a flowlayoutpanel with many images (~400pc., 500x500px).
I loop through a string list with the filenames and add this pics to the flp.
But above ~200 images the panel doesn't show more images.

I think it's a perfomance problem and i want to ask, wether it is possible to load the images  "on demand"?

Like scrolling through the panel and only load the "visible" image?

For panel filling i use this:

public void PanelFill(List<string> filenames)
{
    try
    {
        int temp = 0;
        foreach (string filename in filenames)
        {
            GC.Collect();
            PictureBox pic = new PictureBox
            {
                ClientSize = new Size(int_thumbWidth, int_thumbHeight),
                //Image = new Bitmap(filename),
                Tag = filename,
                BorderStyle = BorderStyle.FixedSingle
            };
            if ((pic.Image.Width > int_thumbWidth) ||
                (pic.Image.Height > int_thumbHeight))
            {
                pic.SizeMode = PictureBoxSizeMode.Zoom;
            }
            else
            {
                pic.SizeMode = PictureBoxSizeMode.CenterImage;
            }
            flowLayoutPanel_esww_bildvergleich.Invoke(new Action(() => { pic.Parent = flowLayoutPanel_esww_bildvergleich; }));
            pic.Click += PictureBox_Click;
            pic.DoubleClick += PictureBox_DoubleClick;
            pic.MouseUp += PictureBox_MouseUp;
            temp++;
        }
    }
    catch (OutOfMemoryException)
    {
        MessageBox.Show("Es wurden zu viele Fotos gefunden. Der Arbeitsspeicher ist nicht ausreichend. Bitte passen Sie Ihre Filter an.", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
        str_aufnahmeTyp.Clear();
    }
    catch (Exception ex)
    {
        Fehlerbehandlung.Fehler(-1, ex.Message);
    }
}

Body:
A workaround for me is to add a Scroll/MouseEnter- Eventhandler for catching the scrolling through the panel.
In the handler i use .PerformLayout()

 this.flowLayoutPanel_esww_bildvergleich.MouseEnter += new System.EventHandler(this.flowLayoutPanel_esww_bildvergleich_MouseEnter);

and...

        private void flowLayoutPanel_esww_bildvergleich_MouseEnter(object sender, EventArgs e)
    {
        flowLayoutPanel_esww_bildvergleich.Focus();
        flowLayoutPanel_esww_bildvergleich.PerformLayout();
    }


问:
Invoke JavaScript function with argument via pointer?
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

```<code>function foo (a, callback) {
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    });
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);
</code>```

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

答:
In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

It most certainly is possible to do this. Everything about your code looks just fine to me. Are you sure that the $.post() callback (the anonymous function) is being called? Is bar undefined when foo is invoked?

To clarify, we need to invoke a function using a string -- not a function pointer. Is this possible?

Yes. If the function is defined globally, you can invoke it as a property on the window object, like so:

```<code>function foo () { /* snip */ }

var fn_name = 'foo';

window.foo();       // works
window['foo']();    // works
window[fn_name]();  // also works
</code>```

Body:
How can you invoke a function in JavaScript, while passing in arguments, using a function pointer?

Example:

function foo (a, callback) {
        jQuery.post('/soon/check.json', { var:a }, function(resp) {
             callback(resp);
    });
}

function process_json(resp) {
  // Do something with resp
}

foo(bar, process_json);

process_json never gets invoked. Looking in Firebug, the string process_json is getting passed into foo, but I assumed this represents a pointer to the function process_json.

In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

Body:
In Javascript, is it not possible to invoke functions via pointers and pass in arguments?

It most certainly is possible to do this. Everything about your code looks just fine to me. Are you sure that the $.post() callback (the anonymous function) is being called? Is bar undefined when foo is invoked?

To clarify, we need to invoke a function using a string -- not a function pointer. Is this possible?

Yes. If the function is defined globally, you can invoke it as a property on the window object, like so:

function foo () { /* snip */ }

var fn_name = 'foo';

window.foo();       // works
window['foo']();    // works
window[fn_name]();  // also works


问:
How to send mail weekly once WordPress backup taken or not?
Multiple sites having in WordPress. backup buddy plugin using configured amazon S3 bucket we need every week send mail recent backup received or not in all sites backup information.</p>

答:
Finally I got the answer

First install the AWS S3 package refer this 'https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-examples-creating-buckets.html'
Then below mentioned code create index.php file then call in browser working good

When you want to automatically run index.php file use cron

```<code>require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;

$bucketData = '{
   "bucket":{
      "1":{
         "name":"bucketname-1",
         "backup":"backups/"
      },
      "2":{
         "name":"bucketname-2",
         "backup":"backups/"
      }
   },
   "uncheck":[
      "menardsimages"
   ]
}';
//multile-bucket-having-mentioned-except'uncheck'

$bucketData = json_decode($bucketData);
/**
 * List your Amazon S3 buckets.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

$key = 'xxxxxxxxx';
$secret = 'yyyyyyyy';
//Create a S3Client
$s3Client = new S3Client([
    'region' => 'us-west-2',
    'version' => 'latest',
    'credentials' => [
        'key' => $key,
        'secret' => $secret,
    ]
]);

function recent_backup_verify($objects){
    $tendays_bf_today = date('Y-m-d',(strtotime ( '-7 day' , strtotime ( date("Y-m-d")) ) ));
    foreach ($objects as $object) {
       $created_date = $object['LastModified']->format('Y-m-d');
       if($created_date > $tendays_bf_today){
           return $created_date;
       }
    }
    return false;
}

function searchForName($name, $array) {
   foreach ($array as $key => $val) {
       if ($val->name === $name) {
           return $val->backup;
       }
   }
   return null;
}

$buckets = $s3Client->listBuckets();
//print_r($created_bucketlist);
$backup_array = array();

foreach ($buckets['Buckets'] as $bucket) {
    //files-listing-insideofthe-bucket
    if(!in_array($bucket['Name'], $bucketData->uncheck)){
        $objects = $s3Client->getIterator('ListObjects', array(
            "Bucket" => $bucket['Name'],
            "Prefix" => searchForName($bucket['Name'], $bucketData->bucket) //must have the trailing forward slash "/"
        ));
        $getbackup_result = recent_backup_verify($objects);
        if($getbackup_result != false){
            $backup_array[$bucket['Name']]['status'] = 'Taken';
            $backup_array[$bucket['Name']]['date'] = $getbackup_result;
        }else{
            $backup_array[$bucket['Name']]['status'] = 'Not Taken';
            $backup_array[$bucket['Name']]['date'] = '-';
        }

    }
}

sendgrid_form($backup_array);
function sendgrid_form($backup_array){

    $msg = '<table border="1" cellpadding="5" cellspacing="0" width="500px" style="border-color:#ddd;">';
    $msg .= '<tr bgcolor="#555" style="color:#fff;">';
    $msg .= '<th>S.No</th><th>Site Name</th><th width="100px">Backup Date</th><th width="100px">Backup Status</th>';
    $msg .= '</tr>';
    $s_no = 1;
    foreach($backup_array as $site=>$val){
        if($val['status'] == 'Taken'){$color = 'green';}else{$color='red';}
        $msg .= '<tr>';
        $msg .= '<td align="center">'.$s_no.'</td><td>'.$site.'</td><td align="center" >'.$val['date'].'</td><td align="center" style="color:'.$color.'">'.$val['status'].'</td>';
        $msg .= '</tr>';
        $s_no++;

    }
    $msg .= '</table>';

    $message_html = "<hr width='20%' align='left'>
                    <img src='logo.png' width='100px'>
                    <hr width='20%' align='left'>
                    <h3>Hi Team,</h3>
                    <p>This is the list that has the every week backup status of our websites/applications that received in our AWS S3. If the 'Backup Status' is 'Not Taken' please check with the script/plugin immediately.</p>
                    ".$msg."
                    <p>Thank You</p>";

    $to = 'reciever@example.com';
    $json_string = array(
        'to' => array($to),
        'category' => 's3_backup'
    );

    $params = array(
    'api_user' => 'xxxxx',
    'api_key' => 'yyyy',
    'x-smtpapi' => json_encode($json_string),
    'to' => $to,
    'subject' => 'Backup S3 Report!',
    'html' => $message_html,
    'from' => 'info@example.com',
    );

    $request = 'https://api.sendgrid.com/api/mail.send.json';
    $session = curl_init($request);
    curl_setopt ($session, CURLOPT_POST, true);
    curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($session);
    curl_close($session);
    $temp = json_decode($response);

    if($temp->message == 'success'){
        $data['success'] = "Email Send Successfully!";
    }else{
        $data['success'] = "Email Send Failed!";
    }
    echo json_encode($data);
}
</code>```

Body:
Finally I got the answer

First install the AWS S3 package refer this 'https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-examples-creating-buckets.html'
Then below mentioned code create index.php file then call in browser working good

When you want to automatically run index.php file use cron

require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;

$bucketData = '{
   "bucket":{
      "1":{
         "name":"bucketname-1",
         "backup":"backups/"
      },
      "2":{
         "name":"bucketname-2",
         "backup":"backups/"
      }
   },
   "uncheck":[
      "menardsimages"
   ]
}';
//multile-bucket-having-mentioned-except'uncheck'

$bucketData = json_decode($bucketData);
/**
 * List your Amazon S3 buckets.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

$key = 'xxxxxxxxx';
$secret = 'yyyyyyyy';
//Create a S3Client
$s3Client = new S3Client([
    'region' => 'us-west-2',
    'version' => 'latest',
    'credentials' => [
        'key' => $key,
        'secret' => $secret,
    ]
]);

function recent_backup_verify($objects){
    $tendays_bf_today = date('Y-m-d',(strtotime ( '-7 day' , strtotime ( date("Y-m-d")) ) ));
    foreach ($objects as $object) {
       $created_date = $object['LastModified']->format('Y-m-d');
       if($created_date > $tendays_bf_today){
           return $created_date;
       }
    }
    return false;
}

function searchForName($name, $array) {
   foreach ($array as $key => $val) {
       if ($val->name === $name) {
           return $val->backup;
       }
   }
   return null;
}

$buckets = $s3Client->listBuckets();
//print_r($created_bucketlist);
$backup_array = array();

foreach ($buckets['Buckets'] as $bucket) {
    //files-listing-insideofthe-bucket
    if(!in_array($bucket['Name'], $bucketData->uncheck)){
        $objects = $s3Client->getIterator('ListObjects', array(
            "Bucket" => $bucket['Name'],
            "Prefix" => searchForName($bucket['Name'], $bucketData->bucket) //must have the trailing forward slash "/"
        ));
        $getbackup_result = recent_backup_verify($objects);
        if($getbackup_result != false){
            $backup_array[$bucket['Name']]['status'] = 'Taken';
            $backup_array[$bucket['Name']]['date'] = $getbackup_result;
        }else{
            $backup_array[$bucket['Name']]['status'] = 'Not Taken';
            $backup_array[$bucket['Name']]['date'] = '-';
        }

    }
}

sendgrid_form($backup_array);
function sendgrid_form($backup_array){

    $msg = '<table border="1" cellpadding="5" cellspacing="0" width="500px" style="border-color:#ddd;">';
    $msg .= '<tr bgcolor="#555" style="color:#fff;">';
    $msg .= '<th>S.No</th><th>Site Name</th><th width="100px">Backup Date</th><th width="100px">Backup Status</th>';
    $msg .= '</tr>';
    $s_no = 1;
    foreach($backup_array as $site=>$val){
        if($val['status'] == 'Taken'){$color = 'green';}else{$color='red';}
        $msg .= '<tr>';
        $msg .= '<td align="center">'.$s_no.'</td><td>'.$site.'</td><td align="center" >'.$val['date'].'</td><td align="center" style="color:'.$color.'">'.$val['status'].'</td>';
        $msg .= '</tr>';
        $s_no++;

    }
    $msg .= '</table>';

    $message_html = "<hr width='20%' align='left'>
                    <img src='logo.png' width='100px'>
                    <hr width='20%' align='left'>
                    <h3>Hi Team,</h3>
                    <p>This is the list that has the every week backup status of our websites/applications that received in our AWS S3. If the 'Backup Status' is 'Not Taken' please check with the script/plugin immediately.</p>
                    ".$msg."
                    <p>Thank You</p>";

    $to = 'reciever@example.com';
    $json_string = array(
        'to' => array($to),
        'category' => 's3_backup'
    );

    $params = array(
    'api_user' => 'xxxxx',
    'api_key' => 'yyyy',
    'x-smtpapi' => json_encode($json_string),
    'to' => $to,
    'subject' => 'Backup S3 Report!',
    'html' => $message_html,
    'from' => 'info@example.com',
    );

    $request = 'https://api.sendgrid.com/api/mail.send.json';
    $session = curl_init($request);
    curl_setopt ($session, CURLOPT_POST, true);
    curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
    curl_setopt($session, CURLOPT_HEADER, false);
    curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($session);
    curl_close($session);
    $temp = json_decode($response);

    if($temp->message == 'success'){
        $data['success'] = "Email Send Successfully!";
    }else{
        $data['success'] = "Email Send Failed!";
    }
    echo json_encode($data);
}


问:
ThreadSanitizer deadlock not detected and no result at the end (du to the deadlocked program)
I would like to know where is a deadlock with the thread sanitizer (clang) but the problem is that the program is blocked and the deadlock is not detected during the compilation with -fsanitize=thread option. And there no result at the end of the execution cuz the program is blocked (impossible to quit the program due to the deadlock).</p>

答: If the program is already blocked you don't need ThreadSanitizer to debug it. You can attach to a deadlocked process with gdb and see all threads stacktraces with thread apply all bt. You should see attempts to lock the same mutex from different threads in thread apply all bt output.


问:
Sortying array by two criteria
I have array like this:

```<code>const array = [{
    id: 1,
    date: 591020824000,
    isImportant: false,
  },
  {
    id: 2,
    date: 591080224000,
    isImportant: false,
  },
  {
    id: 3,
    date: 591080424000,
    isImportant: true,
  },
  {
    id: 4,
    date: 591080225525,
    isImportant: false,
  },
  {
    id: 5,
    date: 591020225525,
    isImportant: true,
  },
];
</code>```

And I'm trying to sort this array so elements that are isImportant: true with the most recent date are displayed first and then elements that have isImportant:false with the most recent date

答:
```<code>array.sort((a,b)=>{
    if(a.isImportant==b.isImportant){
        return b.date-a.date;
    }else{
        return a.isImportant?-1:1;
    }
})
</code>```

duplicate of this

Title: Sortying array by two criteria

Body:
I have array like this:

const array = [{
    id: 1,
    date: 591020824000,
    isImportant: false,
  },
  {
    id: 2,
    date: 591080224000,
    isImportant: false,
  },
  {
    id: 3,
    date: 591080424000,
    isImportant: true,
  },
  {
    id: 4,
    date: 591080225525,
    isImportant: false,
  },
  {
    id: 5,
    date: 591020225525,
    isImportant: true,
  },
];

And I'm trying to sort this array so elements that are isImportant: true with the most recent date are displayed first and then elements that have isImportant:false with the most recent date

Body:
array.sort((a,b)=>{
    if(a.isImportant==b.isImportant){
        return b.date-a.date;
    }else{
        return a.isImportant?-1:1;
    }
})

duplicate of this


问:
How to implement server side pagination in Angular Mat-table
Current Implementation:
I am pre-loading all the data in a single api call then loading into the mat-table.This is what i have implemented so far. Oninit of the component i am calling an api and loading all the data into the table.

Desired Implementation:
When the table data has 1000s of rows, I want to call an api to load data for each page of the mat-table.

```<code>        <mat-table [dataSource]="dataSource">

          <ng-container *ngFor="let item of headerRow; let i = index" matColumnDef={{headerRow[i]}}>
            <mat-header-cell *matHeaderCellDef> {{headerRow[i]}} </mat-header-cell>
            <mat-cell *matCellDef="let row">

              <mat-form-field floatLabel="never">
                <input matInput placeholder="Name" [value]="row[i]" [(ngModel)]="row[i]">

              </mat-form-field>
            </mat-cell>
          </ng-container>
          <mat-header-row *matHeaderRowDef="headerRow"></mat-header-row>
          <mat-row *matRowDef="let row; columns: headerRow;">
          </mat-row>
        </mat-table>
        <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</code>```

答:
Basically if You want server side pagination You have to introduce some changes to You API and pass the desired parameters into it. Then make mat-table's data to be refreshed each time user is doing something that cause change as You will be keeping only 1 fixed set of rows (page). As I don't know the server's technology, allow me to just sketch a resolution for You.

Create an API that will return only selected items:

Introduce query parameters like ?page=n&size=m and modify Your API to read those parameters from the query.

Use parameters page and size to make Your SQL to use SKIP (page-1)*size) and TAKE (size). Remember that You have to define them after sorting/filtering or anything that will change the number of rows. Search for Your language how to do that. I give the generic idea. For example in C# You can use LINQ to do the job very easily: skip, take.

Get info from paginator about current state to call API with valid parameter`s values:

Use @ViewChild() to get a reference to Your paginator. Then inside Your code You can use .pageIndex and .pageSize (inputs of MatPaginator). You can use those values to build a valid query.

Use page EventEmmiter (again MatPaginator but outputs), subscribe to it and pipe the complete reload of the data set for the table.

Remember that for now on You are responsible for refreshing data on every sorting/filtering/page resizing/page changing.

Body:
Current Implementation:
I am pre-loading all the data in a single api call then loading into the mat-table.This is what i have implemented so far. Oninit of the component i am calling an api and loading all the data into the table.

Desired Implementation:
When the table data has 1000s of rows, I want to call an api to load data for each page of the mat-table.

        <mat-table [dataSource]="dataSource">

          <ng-container *ngFor="let item of headerRow; let i = index" matColumnDef={{headerRow[i]}}>
            <mat-header-cell *matHeaderCellDef> {{headerRow[i]}} </mat-header-cell>
            <mat-cell *matCellDef="let row">

              <mat-form-field floatLabel="never">
                <input matInput placeholder="Name" [value]="row[i]" [(ngModel)]="row[i]">

              </mat-form-field>
            </mat-cell>
          </ng-container>
          <mat-header-row *matHeaderRowDef="headerRow"></mat-header-row>
          <mat-row *matRowDef="let row; columns: headerRow;">
          </mat-row>
        </mat-table>
        <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>


问:
is it possible to make equalizer android
Doing a little search i realized that to make an equalizer. I need to use C or C++ That would also mean that i have to use the NDK to integrate that with my Java code. The question is, how can i make the C and Java code interact with each other. I don't even know C but i really want that equalizer in my music player. Do you guys know of any good C book which is the best for beginners?

Thanks.

答: you'll also need to get familiar with the NDK for making the java portion of your app utilize c or c++ methods.</p>


问:
Using Tkinter to disable entry with specified input
I would like to use Tkinter to be able to disable one entry if 'no' is selected from a drop down menu.

```<code>from tkinter import *

def disableEntry(entry):
    entry.config(state='disable')

def allowEntry(entry):
    entry.config(state='normal')

def main():
    print("test")

root = Tk() #create a TK root window
root.title("Lunch and Learn")  #Title of the window

L1 = Label(root, text = "Label 1").grid(row=0, column=0, padx=30, pady=(20,5))
L2 = Label(root, text = "Label 2").grid(row=1, column=0, pady=5)

var = StringVar()

E1 = Entry(root,bd =3)
E1.grid(row=0, column=1)
D1 = OptionMenu(root,var,"yes","no")
D1.grid(row=1,column=1)

if var.get() == 'no':
    disableEntry(E1)
elif var.get() == 'yes':
    allowEntry(E1)

B2 = Button(text = "Submit", command=main).grid(row=4, column=2)

root.mainloop()
</code>```

the above code is a simple example of what i have tried. I have created two functions called 'disableEntry' and 'allowEntry' which should change the state of the entry box but they don't appear to do anything when i change the input of the drop down menu.

i dont know if i am approaching this the wrong way or if there is a standardized way to do this.

any help would be appreciated.

答:
You need a way to check the state of the selection after it is changed. That can be achieved with adding a callback command to the OptionMenu widget.

You were checking the correct variable, but the point you were checking it at was before the screen window had even displayed.

```<code>from tkinter import Label, StringVar, OptionMenu, Entry, Tk, Button

# change the state of the Entry widget
def change_state(state='normal'):
    E1.config(state=state)

def main():
    print("test")

# callback function triggered by selecting from OptionMenu widget
def callback(*args):
    if var.get() == 'no':
        change_state(state='disable')
    elif var.get() == 'yes':
        change_state(state='normal')

root = Tk() #create a TK root window
root.title("Lunch and Learn")  #Title of the window

L1 = Label(root, text="Label 1").grid(row=0, column=0, padx=30, pady=(20, 5))
L2 = Label(root, text="Label 2").grid(row=1, column=0, pady=5)

var = StringVar()

E1 = Entry(root, bd=3)
E1.grid(row=0, column=1)
D1 = OptionMenu(root, var, "yes", "no", command=callback)
D1.grid(row=1, column=1)

B2 = Button(text = "Submit", command=main).grid(row=4, column=2)

root.mainloop()
</code>```

Body:
I would like to use Tkinter to be able to disable one entry if 'no' is selected from a drop down menu.

from tkinter import *

def disableEntry(entry):
    entry.config(state='disable')

def allowEntry(entry):
    entry.config(state='normal')

def main():
    print("test")

root = Tk() #create a TK root window
root.title("Lunch and Learn")  #Title of the window

L1 = Label(root, text = "Label 1").grid(row=0, column=0, padx=30, pady=(20,5))
L2 = Label(root, text = "Label 2").grid(row=1, column=0, pady=5)

var = StringVar()

E1 = Entry(root,bd =3)
E1.grid(row=0, column=1)
D1 = OptionMenu(root,var,"yes","no")
D1.grid(row=1,column=1)

if var.get() == 'no':
    disableEntry(E1)
elif var.get() == 'yes':
    allowEntry(E1)

B2 = Button(text = "Submit", command=main).grid(row=4, column=2)

root.mainloop()

the above code is a simple example of what i have tried. I have created two functions called 'disableEntry' and 'allowEntry' which should change the state of the entry box but they don't appear to do anything when i change the input of the drop down menu.

i dont know if i am approaching this the wrong way or if there is a standardized way to do this.

any help would be appreciated.

Body:
You need a way to check the state of the selection after it is changed. That can be achieved with adding a callback command to the OptionMenu widget.

You were checking the correct variable, but the point you were checking it at was before the screen window had even displayed.

from tkinter import Label, StringVar, OptionMenu, Entry, Tk, Button

# change the state of the Entry widget
def change_state(state='normal'):
    E1.config(state=state)

def main():
    print("test")

# callback function triggered by selecting from OptionMenu widget
def callback(*args):
    if var.get() == 'no':
        change_state(state='disable')
    elif var.get() == 'yes':
        change_state(state='normal')

root = Tk() #create a TK root window
root.title("Lunch and Learn")  #Title of the window

L1 = Label(root, text="Label 1").grid(row=0, column=0, padx=30, pady=(20, 5))
L2 = Label(root, text="Label 2").grid(row=1, column=0, pady=5)

var = StringVar()

E1 = Entry(root, bd=3)
E1.grid(row=0, column=1)
D1 = OptionMenu(root, var, "yes", "no", command=callback)
D1.grid(row=1, column=1)

B2 = Button(text = "Submit", command=main).grid(row=4, column=2)

root.mainloop()


问:
How to convert a (java) List to a (scala) ListBuffer (not Buffer) in java?
Is there a way to convert a java.util.List to a Scala.mutable.ListBuffer ?

In JavaConverter asScalaBufferConverter return a Buffer but the method from the scala project accept only ListBuffer.

Is there a way to convert the list to a ListBuffer ? or should I check with the other team lib so they change it to buffer or list ?

答:
As Luis tends to not post one-liners as answers, here is ever-so-slightly expanded answer so I can harvest his upvotes

Scala 2.12

```<code>import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer

val jlist = List(1,2,3).asJava
jlist.asScala.to[ListBuffer]   // res0: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)
</code>```

Scala 2.13

```<code>import scala.jdk.CollectionConverters._
import scala.collection.mutable.ListBuffer

val jlist = List(1,2,3).asJava
jlist.asScala.to(ListBuffer)
</code>```

Note Scala 2.13 introduced the following changes

New to(Collection) method

List Replaces old to[Collection] method.

The argument is the companion object of the desired collection type, for example .to(Vector).

The API change enables support for all collection types (including Map, BitSet, et al).

Body:
As Luis tends to not post one-liners as answers, here is ever-so-slightly expanded answer so I can harvest his upvotes

Scala 2.12

import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer

val jlist = List(1,2,3).asJava
jlist.asScala.to[ListBuffer]   // res0: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 2, 3)

Scala 2.13

import scala.jdk.CollectionConverters._
import scala.collection.mutable.ListBuffer

val jlist = List(1,2,3).asJava
jlist.asScala.to(ListBuffer)

Note Scala 2.13 introduced the following changes

New to(Collection) method

List Replaces old to[Collection] method.

The argument is the companion object of the desired collection type, for example .to(Vector).

The API change enables support for all collection types (including Map, BitSet, et al).


问:
Aviso Same-Site/Aviso Same-Site
My site is showing some warnings on my site about the Same Site attribute, I found in another question (question link below) a solution but it uses Web.config and I can't find it in my Cpanel
I use Wordpress hosted on Cpanel
Could you give me a hand over? I can't find a solution
Thanks in advance

Image Error Console

Same-Site

答:
These warnings are all related to google.com sites, not your site. You are only responsible for cookies from your domain. Try testing the functionality you are concerned about in an incognito window. If anything is broken, then check the console for warnings specifically linked to your domain.

You can find more context on this on https://web.dev/samesite-cookies-explained.

Title: Aviso Same-Site/Aviso Same-Site


问:
How do I debug "Error: spawn ENOENT" on node.js?

When I get the following error:

```<code>events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)
</code>```

What procedure can I follow to fix it?

Author note: Lots of issues with this error encouraged me to post this question for future references.

Related questions:

using spawn function with NODE_ENV=production

node.js child_process.spawn ENOENT error - only under supervisord

spawn ENOENT node.js error

https://stackoverflow.com/questions/27603713/nodejs-spawn-enoent-error-on-travis-calling-global-npm-package

Node JS - child_process spawn('npm install') in Grunt task results in ENOENT error

Running "foreman" task Fatal error: spawn ENOENT

unhandled error event in node js Error: spawn ENOENT at errnoException (child_process.js:975:11)

Node.js SpookyJS: error executing hello.js

https://stackoverflow.com/questions/26572214/run-grunt-on-a-directory-nodewebkit

Run exe file with Child Process NodeJS

Node: child_process.spawn not working on Java even though it's in the path (ENOENT)

spawn ENOENT error with NodeJS (PYTHON related)

image resizing is not working in node.js (partial.js) (non-installed dependency)

npm install error ENOENT (build dependency problem)

Cannot install node.js - oracle module on Windows 7 (build dependency problem)

Error installing gulp using nodejs on windows (strange case)

答:
Before anyone spends to much time debugging this problem, most of the time it can be resolved by deleting node_modules and reinstalling the packages.

To Install:

If a lockfile exists you might use

```<code>yarn install --frozen-lockfile
</code>```

or

```<code>npm ci
</code>```

respectivly. if not then

```<code>yarn install
</code>```

or

```<code>npm i
</code>```

Body:
When I get the following error:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

What procedure can I follow to fix it?

Author note: Lots of issues with this error encouraged me to post this question for future references.

Related questions:

using spawn function with NODE_ENV=production

node.js child_process.spawn ENOENT error - only under supervisord

spawn ENOENT node.js error

https://stackoverflow.com/questions/27603713/nodejs-spawn-enoent-error-on-travis-calling-global-npm-package

Node JS - child_process spawn('npm install') in Grunt task results in ENOENT error

Running "foreman" task Fatal error: spawn ENOENT

unhandled error event in node js Error: spawn ENOENT at errnoException (child_process.js:975:11)

Node.js SpookyJS: error executing hello.js

https://stackoverflow.com/questions/26572214/run-grunt-on-a-directory-nodewebkit

Run exe file with Child Process NodeJS

Node: child_process.spawn not working on Java even though it's in the path (ENOENT)

spawn ENOENT error with NodeJS (PYTHON related)

image resizing is not working in node.js (partial.js) (non-installed dependency)

npm install error ENOENT (build dependency problem)

Cannot install node.js - oracle module on Windows 7 (build dependency problem)

Error installing gulp using nodejs on windows (strange case)

Body:
Before anyone spends to much time debugging this problem, most of the time it can be resolved by deleting node_modules and reinstalling the packages.

To Install:

If a lockfile exists you might use

yarn install --frozen-lockfile

or

npm ci

respectivly. if not then

yarn install

or

npm i


问:
Where does 'Hello world' come from?
'hello, world' is usually the first example for any programming language. I've always wondered where this sentence came from and where was it first used.

I've once been told that it was the first sentence ever to be displayed on a computer screen, but I've not been able to find any reference to this.

So my question is:

Where does the practice to use 'hello, world' as the first example for computer languages originate from?

Where was it first used?

Update

Although the answers are quite interesting, I should have noted that I had read the Wikipedia article. It does answer the question about the first use in literature, but does not answer when 'hello world' was first used.

So I think that it is safe to conclude that it was not the first sentence ever to be displayed on a computer screen and that there is no record about when it was first used?

答:
From Wikipedia

While small test programs existed since the development of programmable computers, the tradition of using the phrase "Hello world!" as a test message was influenced by an example program in the seminal book The C Programming Language. The example program from that book prints "hello, world" (without capital letters or exclamation mark), and was inherited from a 1974 Bell Laboratories internal memorandum by Brian Kernighan, Programming in C: A Tutorial, which contains the first known version:

http://en.wikipedia.org/wiki/Hello_world_program

OwnerDisplayName: Jacco

Title: Where does 'Hello world' come from?

LastEditorDisplayName: Jacco

OwnerDisplayName: Tuoski

ContentLicense: CC BY-SA 2.5


问:
How to stop an Apache 2 HTTP server from a Java program?
I start an Apache HTTP server within my Java program. Unfortunately, I cannot stop the server from the program through the "httpd.exe -k stop" command. The error message is "(OS 5)Access is denied. : Failed to open the Apache2.2 Service". My OS is Windows 7.
How can I stop the server from my Java program? (Stopping manually the server is not an option.) </p>

<p>UPDATE: I cannot change the Windows permissions. </p>

答:
It might be possible to write a CGI script, deploy it into Apache and call that from Java.

In theory the script would run with the same privileges as Apache itself and could contain the code necessary to stop the server ( apachectl -k stop ).

For security , the CGI script would only accept localhost connections and would require a password. If all requirements are met, it would issue the call above.

Body:
I start an Apache HTTP server within my Java program. Unfortunately, I cannot stop the server from the program through the "httpd.exe -k stop" command. The error message is "(OS 5)Access is denied. : Failed to open the Apache2.2 Service". My OS is Windows 7.
How can I stop the server from my Java program? (Stopping manually the server is not an option.)

UPDATE: I cannot change the Windows permissions.