问:
random image on load
I have found several scripts but i don't get them to work:
What am i doing wrong;

I want to change the color and some images on my page, so the second time you visite the page you may get another color.

I get the font color to change, but having problems with my image.

the js:

```<code>$(document).ready(function(){
  var colors = ["#D4FF00","#E18000","#ED4498","#0080C0"];
  var Rlogo= ['BIMP_groen.jpg','BIMP_oranje.jpg','BIMP_roze.jpg','BIMP_blauw.jpg'];
  var rand = Math.floor(Math.random()*colors.length);
  $('a').css("color", colors[rand]);
  $('h2').css("color", colors[rand]);
  $('<img src="images/logo/' + Rlogo[rand] + '">').appendTo('#logo');
  });
</code>```

in my html i have;

```<code><img src="images/logo/BIMP_oranje.jpg" id="logo" align="right" alt='align="right"'>
</code>```

the image doesn;t change on refresh.

please help

答:
"appendTo" add some content to an element but the #logo element ( which is an "img" element ) does not have inner html.

You should do something like this instead :

```<code>$("#logo").attr("src","images/logo/"+Rlogo[rand]);
</code>```

Title: random image on load

Body:
I have found several scripts but i don't get them to work:
What am i doing wrong;

I want to change the color and some images on my page, so the second time you visite the page you may get another color.

I get the font color to change, but having problems with my image.

the js:

$(document).ready(function(){
  var colors = ["#D4FF00","#E18000","#ED4498","#0080C0"];
  var Rlogo= ['BIMP_groen.jpg','BIMP_oranje.jpg','BIMP_roze.jpg','BIMP_blauw.jpg'];
  var rand = Math.floor(Math.random()*colors.length);
  $('a').css("color", colors[rand]);
  $('h2').css("color", colors[rand]);
  $('').appendTo('#logo');
  });

in my html i have;

the image doesn;t change on refresh.

please help

Body:
"appendTo" add some content to an element but the #logo element ( which is an "img" element ) does not have inner html.

You should do something like this instead :

$("#logo").attr("src","images/logo/"+Rlogo[rand]);


来源: stackexchange

问:
Pymongo.db.create_collection with validator returns 'unknown operator: $jsonSchema'
I am trying to create a schema for my mongoDB database in order to ensure data format in the Database.

I am using pymongo to make sure this happens in my docker container when application starts, if the database is not initialized.

self.client = MongoClient(conn_string)
self.db = self.client[db_name]
# ...
# I am looping over in my json and 'stuff' is the collection name
# and json['stuff'] is the schema, so:
# collection = 'stuff'
# schema = json[collection]
# ...
self.db.create_collection(collection, validator= { "validator": { "$jsonSchema": schema} })

```
<p>The schema looks like that, and is loaded from a <code>json</code> file. (and that work)</p>
<pre class="lang-json prettyprint-override"><code>{
   "stuff": {
      "bsonType": "object",
      "required": [ "sid", "name", "url" ],
      "properties": {
         "sid": {
            "bsonType": "string",
            "pattern": "^[a-z_]{3-20}$",
            "description": "must be a string 3-20 lowercase chars and is required"
         },
         "name": {
            "bsonType": "string",
            "minLength": 2,
            "maxLength": 30,
            "description": "must be a string 2-30 chars and is required"
         },
         "url": {
            // etc.
         }
      }
   }
}
</code>```

But I  get this error:

pymongo.errors.OperationFailure: unknown operator: $jsonSchema, full error:
  {'ok': 0.0, 'errmsg': 'unknown operator: $jsonSchema', 'code': 2, 'codeName': 'BadValue'}
```

答:
So I found the answer, also thanks to @prasad_ comment:
The problem was a syntax error here are the bad and good version side to side :

# Bad version :
self.db.create_collection(collection, validator= { "validator": { "$jsonSchema": schema} })
# Good version :
self.db.create_collection(collection, validator= { "$jsonSchema": schema})
```

So because the validator is passed as parameter, it shouldn't be named inside itself, only the $jsonSchema

I hope it helps some people, it is hard to find proper documentation about pymongo usage, so let me know.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a schema for my mongoDB database in order to ensure data format in the Database.

I am using pymongo to make sure this happens in my docker container when application starts, if the database is not initialized.

self.client = MongoClient(conn_string)
self.db = self.client[db_name]
# ...
# I am looping over in my json and 'stuff' is the collection name
# and json['stuff'] is the schema, so:
# collection = 'stuff'
# schema = json[collection]
# ...
self.db.create_collection(collection, validator= { "validator": { "$jsonSchema": schema} })

The schema looks like that, and is loaded from a json file. (and that work)

{
   "stuff": {
      "bsonType": "object",
      "required": [ "sid", "name", "url" ],
      "properties": {
         "sid": {
            "bsonType": "string",
            "pattern": "^[a-z_]{3-20}$",
            "description": "must be a string 3-20 lowercase chars and is required"
         },
         "name": {
            "bsonType": "string",
            "minLength": 2,
            "maxLength": 30,
            "description": "must be a string 2-30 chars and is required"
         },
         "url": {
            // etc.
         }
      }
   }
}

But I  get this error:

pymongo.errors.OperationFailure: unknown operator: $jsonSchema, full error:
  {'ok': 0.0, 'errmsg': 'unknown operator: $jsonSchema', 'code': 2, 'codeName': 'BadValue'}

Body:
So I found the answer, also thanks to @prasad_ comment:
The problem was a syntax error here are the bad and good version side to side :

# Bad version :
self.db.create_collection(collection, validator= { "validator": { "$jsonSchema": schema} })
# Good version :
self.db.create_collection(collection, validator= { "$jsonSchema": schema})

So because the validator is passed as parameter, it shouldn't be named inside itself, only the $jsonSchema

I hope it helps some people, it is hard to find proper documentation about pymongo usage, so let me know.


问:
How to lazily define an element in a list based on a previous element?
Essentially, what I'm trying to achieve is similar to the functionality that exists for function arguments -

```<code>xx <- function(x, y = 2 * x){message('y is ', y)} # y is defined even when only the value of 'x' is supplied
xx(2) # Outputs "y is 4"
</code>```

Similar to how y is lazily defined in the above, can I do something like this -

```<code>l <- list(x = 2, y = 2 * x) # This returns "Error: object 'x' not found" which I understand
</code>```

I have tried a kludgy workaround involving l <- list(x <<- 2, y = 2 * x) which works but creates variables in the global environment. So, I'm not too keen on using <<-

This is very similar to Using list elements in its' definition, but I'm interested in an r-base solution that involves defining the least amount variables in the global environment (including functions)

答:
for base R, You could use within:

```<code>l <- within(list(x = 2), {y = x*2; z =y+3})
</code>```

in tidyverse, use the dplyr::lst or tibble::lst

Body:
Essentially, what I'm trying to achieve is similar to the functionality that exists for function arguments -

xx <- function(x, y = 2 * x){message('y is ', y)} # y is defined even when only the value of 'x' is supplied
xx(2) # Outputs "y is 4"

Similar to how y is lazily defined in the above, can I do something like this -

l <- list(x = 2, y = 2 * x) # This returns "Error: object 'x' not found" which I understand

I have tried a kludgy workaround involving l <- list(x <<- 2, y = 2 * x) which works but creates variables in the global environment. So, I'm not too keen on using <<-

This is very similar to Using list elements in its' definition, but I'm interested in an r-base solution that involves defining the least amount variables in the global environment (including functions)

Body:
for base R, You could use within:

l <- within(list(x = 2), {y = x*2; z =y+3})

in tidyverse, use the dplyr::lst or tibble::lst


问:
Should operator !() be defined in a class if bool() operator is already defined?
I have a simple class which is a concrete class and is not designed to be inherited. Also I want to be able to say !myobject where myobject is an instance of this class. I've already define operator bool(). Should I also define bool operator!()?

Here is trivial example of the class:

```<code>class Test
{
  public:
    ...
    explicit operator bool() {
      return error_ == 0;
    }

    bool operator!() {
      return error_ != 0;
    }

  private:
    int error_;
};
</code>```

I tried it as !myobject and it works independent of !() operator is being defined or not.
Looks like it is a silly question, but I couldn't find an answer for it.

答:
Use the operator bool() const in your class:

```<code> explicit operator bool() const {
     return error_ == 0;
 }
</code>```

and no need to define overload !().

Body:
I have a simple class which is a concrete class and is not designed to be inherited. Also I want to be able to say !myobject where myobject is an instance of this class. I've already define operator bool(). Should I also define bool operator!()?

Here is trivial example of the class:

class Test
{
  public:
    ...
    explicit operator bool() {
      return error_ == 0;
    }

    bool operator!() {
      return error_ != 0;
    }

  private:
    int error_;
};

I tried it as !myobject and it works independent of !() operator is being defined or not.
Looks like it is a silly question, but I couldn't find an answer for it.

Body:
Use the operator bool() const in your class:

 explicit operator bool() const {
     return error_ == 0;
 }

and no need to define overload !().


问:
Transform table structure
Hello is any sensible algorithm for transforming data table (Table A to Table B) ?

I trying to moving cells , but have no idea how to calculate a place where I should place additional row after my key field Name.

Table A origin

Name
Salary
Bonus
Amount

John S.
5000
Bonus A
50

John S.

Bonus B
100

Alex G.
7000
Bonus C
150

Alex G.

Bonus D
300

Table B (Expected outcome)

Name
Salary
Bonus
Amount

John S.

5000

John S.

Bonus A
50

John S.

Bonus B
100

Alex G.

7000

Alex G.

Bonus C
150

Alex G.

Bonus D
300

```<code>Sub TransformTable()

' Setting variables
Dim Name As String
Dim BaseSalary As String
Dim BonusName As String
Dim BonusAmount As Double

'Setting worksheet object
Dim SheetData As Worksheet
Set SheetData = Sheets("SheetData")

'counter for main loop
Dim x As Long

'Setting main object array
Dim MyArray As Variant

Dim Item As Integer
    Item = 1

'reading values from table
    MyArray = Worksheets("SheetData").ListObjects("Table1").DataBodyRange.Value

'counting last row value

'main loop
    For x = LBound(MyArray) To UBound(MyArray)

'condition check how many costcenter ids with fixed value
     lstRowSrs = SheetData.Cells(Rows.Count, 1).End(xlUp).Row
     Worksheets("SheetData").Cells(Item + 1, 13).Value = MyArray(x, 1)
     Worksheets("SheetData").Cells(Item + 1, 14).Value = MyArray(x, 2)

    If MyArray(x, 3) <> "" Then

    ' Cells(x, lstRowSrs).EntireRow.Insert

     Worksheets("SheetData").Cells(Item + 2, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 2, 16).Value = MyArray(x, 4)
     Item = Item + 1

    Else
     Worksheets("SheetData").Cells(Item + 1, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 1, 16).Value = MyArray(x, 4)

      Item = Item + 1
    End If
    Next x

End Sub
</code>```

答:
Solution

I changed the logic that you posted as follows

Identify the rows to be added

Insert them at once (to save memory instead of inserting one by one)

Append the data needed by looping again in the rows

For demonstration purposes, I limited the logic to the active sheet and with the data sample shown.
Demo

Code

```<code>Sub Exec_DivideSalary()
Dim CounterRow As Long
Dim RangeRowsToAdd As Range
    For CounterRow = 2 To Cells.SpecialCells(xlCellTypeLastCell).Row
    If Cells(CounterRow, 2).Value <> "" Then ' 1. If Cells(CounterRow, 2).Value <> ""
    If RangeRowsToAdd Is Nothing Then ' 2. If RangeRowsToAdd Is Nothing
    Set RangeRowsToAdd = Rows(CounterRow + 1)
    Else ' 2. If RangeRowsToAdd Is Nothing
    Set RangeRowsToAdd = Union(RangeRowsToAdd, Rows(CounterRow + 1))
    End If ' 2. If RangeRowsToAdd Is Nothing
    End If ' 1. If Cells(CounterRow, 2).Value <> ""
    Next CounterRow
    RangeRowsToAdd.Insert Shift:=xlDown
    For CounterRow = 2 To Cells.SpecialCells(xlCellTypeLastCell).Row
    If Cells(CounterRow, 2).Value <> "" Then ' 3. If Cells(CounterRow, 2).Value <> ""
    Cells(CounterRow + 1, 1).Value = Cells(CounterRow, 1).Value: Cells(CounterRow + 1, 3).Value = Cells(CounterRow, 3).Value: Cells(CounterRow + 1, 4).Value = Cells(CounterRow, 4).Value
    Cells(CounterRow, 4).Value = Cells(CounterRow, 2).Value
    Cells(CounterRow, 2).Value = "": Cells(CounterRow, 3).Value = ""
    End If ' 3. If Cells(CounterRow, 2).Value <> ""
    Next CounterRow
End Sub
</code>```

Title: Transform table structure

Body:
Hello is any sensible algorithm for transforming data table (Table A to Table B) ?

I trying to moving cells , but have no idea how to calculate a place where I should place additional row after my key field Name.

Table A origin

Name
Salary
Bonus
Amount

John S.
5000
Bonus A
50

John S.

Bonus B
100

Alex G.
7000
Bonus C
150

Alex G.

Bonus D
300

Table B (Expected outcome)

Name
Salary
Bonus
Amount

John S.

5000

John S.

Bonus A
50

John S.

Bonus B
100

Alex G.

7000

Alex G.

Bonus C
150

Alex G.

Bonus D
300

Sub TransformTable()

' Setting variables
Dim Name As String
Dim BaseSalary As String
Dim BonusName As String
Dim BonusAmount As Double

'Setting worksheet object
Dim SheetData As Worksheet
Set SheetData = Sheets("SheetData")

'counter for main loop
Dim x As Long

'Setting main object array
Dim MyArray As Variant

Dim Item As Integer
    Item = 1

'reading values from table
    MyArray = Worksheets("SheetData").ListObjects("Table1").DataBodyRange.Value

'counting last row value

'main loop
    For x = LBound(MyArray) To UBound(MyArray)

'condition check how many costcenter ids with fixed value
     lstRowSrs = SheetData.Cells(Rows.Count, 1).End(xlUp).Row
     Worksheets("SheetData").Cells(Item + 1, 13).Value = MyArray(x, 1)
     Worksheets("SheetData").Cells(Item + 1, 14).Value = MyArray(x, 2)

    If MyArray(x, 3) <> "" Then

    ' Cells(x, lstRowSrs).EntireRow.Insert

     Worksheets("SheetData").Cells(Item + 2, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 2, 16).Value = MyArray(x, 4)
     Item = Item + 1

    Else
     Worksheets("SheetData").Cells(Item + 1, 15).Value = MyArray(x, 3)
     Worksheets("SheetData").Cells(Item + 1, 16).Value = MyArray(x, 4)

      Item = Item + 1
    End If
    Next x

End Sub

Body:
Solution

I changed the logic that you posted as follows

Identify the rows to be added

Insert them at once (to save memory instead of inserting one by one)

Append the data needed by looping again in the rows

For demonstration purposes, I limited the logic to the active sheet and with the data sample shown.
Demo

Code

Sub Exec_DivideSalary()
Dim CounterRow As Long
Dim RangeRowsToAdd As Range
    For CounterRow = 2 To Cells.SpecialCells(xlCellTypeLastCell).Row
    If Cells(CounterRow, 2).Value <> "" Then ' 1. If Cells(CounterRow, 2).Value <> ""
    If RangeRowsToAdd Is Nothing Then ' 2. If RangeRowsToAdd Is Nothing
    Set RangeRowsToAdd = Rows(CounterRow + 1)
    Else ' 2. If RangeRowsToAdd Is Nothing
    Set RangeRowsToAdd = Union(RangeRowsToAdd, Rows(CounterRow + 1))
    End If ' 2. If RangeRowsToAdd Is Nothing
    End If ' 1. If Cells(CounterRow, 2).Value <> ""
    Next CounterRow
    RangeRowsToAdd.Insert Shift:=xlDown
    For CounterRow = 2 To Cells.SpecialCells(xlCellTypeLastCell).Row
    If Cells(CounterRow, 2).Value <> "" Then ' 3. If Cells(CounterRow, 2).Value <> ""
    Cells(CounterRow + 1, 1).Value = Cells(CounterRow, 1).Value: Cells(CounterRow + 1, 3).Value = Cells(CounterRow, 3).Value: Cells(CounterRow + 1, 4).Value = Cells(CounterRow, 4).Value
    Cells(CounterRow, 4).Value = Cells(CounterRow, 2).Value
    Cells(CounterRow, 2).Value = "": Cells(CounterRow, 3).Value = ""
    End If ' 3. If Cells(CounterRow, 2).Value <> ""
    Next CounterRow
End Sub


问:
Set-AuthenticodeSignature returns access to the path is denied error
I have a simple powershell script that I use to send me an email when there is an issue on a server.  Scripts are restricted from running on that server unless they're signed.  So, I created a self signed certificate, moved it to the trusted root folder, and when I run Get-ChildItem on it I see the thumbprint returned, and the properties look correct to me (though I admit I don't know much about certificates).  The last step is to sign the script, which I'm attempting to do with:

```<code>$cert=(Get-ChildItem -Path Cert:\LocalMachine\Root -CodeSigningCert)[0]
Set-AuthenticodeSignature -FilePath "C:\Scripts\ServiceFailureAlert.PS1" $cert
</code>```

But I'm getting Access to the path is denied.
I'm sure that its something super simple, but I'm banging my head against the wall at this point.  The script is something that I created.  Its not read only, the directory isn't read only, all users have full rights, I'm an admin on the server, I'm running powershell as an admin.  Any help would be greatly appreciated.

答:
I was getting the same issue and under the Security event log I found the following:

```<code>Audit Failure:

Cryptographic Operation:
Operation:  Open Key.
Return Code:    0x80090016
</code>```

The problem for me was that the user which was signing the scripts was a different user than the one I had used to import the certificates, and didn't have access to the private keys. To fix, I did the following:

Manage Certificates for Local Computer

Locate the Authenticode Certificate with the private key

Right click > All tasks > Manage private keys...

Granted the user Full Control over the private keys

After this I was able to use Set-AuthenticodeSignature under my desired user credential with no issues

Body:
I have a simple powershell script that I use to send me an email when there is an issue on a server.  Scripts are restricted from running on that server unless they're signed.  So, I created a self signed certificate, moved it to the trusted root folder, and when I run Get-ChildItem on it I see the thumbprint returned, and the properties look correct to me (though I admit I don't know much about certificates).  The last step is to sign the script, which I'm attempting to do with:

$cert=(Get-ChildItem -Path Cert:\LocalMachine\Root -CodeSigningCert)[0]
Set-AuthenticodeSignature -FilePath "C:\Scripts\ServiceFailureAlert.PS1" $cert

But I'm getting Access to the path is denied.
I'm sure that its something super simple, but I'm banging my head against the wall at this point.  The script is something that I created.  Its not read only, the directory isn't read only, all users have full rights, I'm an admin on the server, I'm running powershell as an admin.  Any help would be greatly appreciated.

Body:
I was getting the same issue and under the Security event log I found the following:

Audit Failure:

Cryptographic Operation:
Operation:  Open Key.
Return Code:    0x80090016

The problem for me was that the user which was signing the scripts was a different user than the one I had used to import the certificates, and didn't have access to the private keys. To fix, I did the following:

Manage Certificates for Local Computer

Locate the Authenticode Certificate with the private key

Right click > All tasks > Manage private keys...

Granted the user Full Control over the private keys

After this I was able to use Set-AuthenticodeSignature under my desired user credential with no issues


问:
Failed to precompile StatsPlots.jl
This might be connected to this or this. However, none of the suggested solutions works for me.

I'm using VSCode with the Julia extension and I run everything in a Jupyter notebook. My first cell looks as follows.

```<code>using Distributions
using StatsBase
using CSV
using DataFrames
using HypothesisTests
using Plots
using GLM
using StatsPlots
</code>```

Executing the cell yields to the following error.

```<code>ailed to precompile StatsPlots [f3b207a7-027a-5e70-b257-86293d7955fd] to /home/david/.julia/compiled/v1.7/StatsPlots/jl_27z7QU.

Stacktrace:
  [1] compilecache(pkg::Base.PkgId, path::String, internal_stderr::IO, internal_stdout::IO, ignore_loaded_modules::Bool)
    @ Base ./loading.jl:1466
  [2] compilecache(pkg::Base.PkgId, path::String)
    @ Base ./loading.jl:1410
  [3] _require(pkg::Base.PkgId)
    @ Base ./loading.jl:1120
  [4] require(uuidkey::Base.PkgId)
    @ Base ./loading.jl:1013
  [5] require(into::Module, mod::Symbol)
    @ Base ./loading.jl:997
  [6] eval
    @ ./boot.jl:373 [inlined]
  [7] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
    @ Base ./loading.jl:1196
  [8] #invokelatest#2
    @ ./essentials.jl:716 [inlined]
  [9] invokelatest
    @ ./essentials.jl:714 [inlined]
 [10] (::VSCodeServer.var"#150#151"{VSCodeServer.NotebookRunCellArguments, String})()
    @ VSCodeServer ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/VSCodeServer/src/serve_notebook.jl:18
 [11] withpath(f::VSCodeServer.var"#150#151"{VSCodeServer.NotebookRunCellArguments, String}, path::String)
    @ VSCodeServer ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/VSCodeServer/src/repl.jl:185
 [12] notebook_runcell_request(conn::VSCodeServer.JSONRPC.JSONRPCEndpoint{Base.PipeEndpoint, Base.PipeEndpoint}, params::VSCodeServer.NotebookRunCellArguments)
    @ VSCodeServer ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/VSCodeServer/src/serve_notebook.jl:14
 [13] dispatch_msg(x::VSCodeServer.JSONRPC.JSONRPCEndpoint{Base.PipeEndpoint, Base.PipeEndpoint}, dispatcher::VSCodeServer.JSONRPC.MsgDispatcher, msg::Dict{String, Any})
    @ VSCodeServer.JSONRPC ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/JSONRPC/src/typed.jl:67
 [14] serve_notebook(pipename::String; crashreporting_pipename::String)
    @ VSCodeServer ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/VSCodeServer/src/serve_notebook.jl:94
 [15] top-level scope
    @ ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/notebook/notebook.jl:12
</code>```

Next, I have opened the Julia command line and removed the StatsPlots extensions using ] rm "StatsPlots" and readded it using ] add "StatsPlots" with no success. I have tried to execute precompile in the command line by hand which yields to the following output.

```<code>(@v1.7) pkg> precompile
Precompiling project...
  ✗ Arpack
  ✗ MultivariateStats
  ✗ StatsPlots
  0 dependencies successfully precompiled in 11 seconds (216 already precompiled)

ERROR: The following 1 direct dependency failed to precompile:

StatsPlots [f3b207a7-027a-5e70-b257-86293d7955fd]

Failed to precompile StatsPlots [f3b207a7-027a-5e70-b257-86293d7955fd] to /home/david/.julia/compiled/v1.7/StatsPlots/jl_1XjxNk.
ERROR: LoadError: InitError: could not load library "/home/david/.julia/artifacts/cdf6dc8aa6771a61c6c65a5a5c1a8d1b75f50a2f/lib/libarpack.so"
libopenblas64_.so: cannot open shared object file: No such file or directory
Stacktrace:
 [1] macro expansion
   @ ~/.julia/packages/JLLWrappers/QpMQW/src/products/library_generators.jl:54 [inlined]
 [2] __init__()
   @ Arpack_jll ~/.julia/packages/Arpack_jll/zfgpQ/src/wrappers/x86_64-linux-gnu-libgfortran5.jl:10
 [3] top-level scope (repeats 2 times)
   @ none:1
during initialization of module Arpack_jll
in expression starting at /home/david/.julia/packages/Arpack/pLziT/src/Arpack.jl:2
ERROR: LoadError: Failed to precompile Arpack [7d9fca2a-8960-54d3-9f78-7d1dccf2cb97] to /home/david/.julia/compiled/v1.7/Arpack/jl_fCy8AR.
Stacktrace:
 [1] include(x::String)
   @ MultivariateStats ~/.julia/packages/MultivariateStats/zLpz8/src/MultivariateStats.jl:1
 [2] top-level scope
   @ ~/.julia/packages/MultivariateStats/zLpz8/src/MultivariateStats.jl:113
 [3] top-level scope (repeats 2 times)
   @ none:1
in expression starting at /home/david/.julia/packages/MultivariateStats/zLpz8/src/kpca.jl:3
in expression starting at /home/david/.julia/packages/MultivariateStats/zLpz8/src/MultivariateStats.jl:1
ERROR: LoadError: Failed to precompile MultivariateStats [6f286f6a-111f-5878-ab1e-185364afe411] to /home/david/.julia/compiled/v1.7/MultivariateStats/jl_8Rrih5.
Stacktrace:
 [1] top-level scope (repeats 2 times)
   @ none:1
in expression starting at /home/david/.julia/packages/StatsPlots/CpWiU/src/StatsPlots.jl:1
</code>```

I have tried to restart the Julia kernel, restart VSCode, and I've tried the solution suggested in the second link that I have provided, meaning removing the package and run gc.

I have also removed and readded MultivariateStats and Arpack but the above error remains.

It might be from interest that it has worked before. I run into a different error first by executing the following cell.

```<code>@df data density(:Age, group = :Treatment, title = "Distribution of ages by treatment group", xlab = "Age", ylab="Distribution", legend=:topright)
</code>```

The above yielded to the following error message.

```<code>LoadError: UndefVarError: @df not defined
</code>```

It might have been the case that I accidently added the outdated extension StatPlots and that might have caused the above issue. However, I've removed the old extension and added the new one.

How can I resolve the above problem?

Edit: Running Pkg.status() yields to the following output.

```<code>(@v1.7) pkg> status
      Status `~/.julia/environments/v1.7/Project.toml`
  [336ed68f] CSV v0.10.2
  [8f4d0f93] Conda v1.6.0
  [a93c6f00] DataFrames v1.3.2
  [31c24e10] Distributions v0.25.48
  [38e38edf] GLM v1.6.1
  [a2cc645c] GraphPlot v0.5.0
  [86223c79] Graphs v1.6.0
  [09f84164] HypothesisTests v0.10.6
  [7073ff75] IJulia v1.23.2
  [91a5bcdd] Plots v1.25.8
  [c3e4b0f8] Pluto v0.18.0
  [7f904dfe] PlutoUI v0.7.23
  [438e738f] PyCall v1.93.0
  [d330b81b] PyPlot v2.10.0
  [aa4a32ff] SimpleHypergraphs v0.2.0
  [2913bbd2] StatsBase v0.33.14
  [f3b207a7] StatsPlots v0.14.33
</code>```

答:
I was able to resolve the problem. The root of the problem was the missing library libopenblas64. This could be due to a faulty Julia installation. Here is what I have done.

First, open the Julia command line and execute the following two commands.

```<code>using Libdl
filter!(p -> occursin("blas", p), Libdl.dllist())
</code>```

In my case, this yielded to the following output.

```<code>1-element Array{String,1}:
 "/usr/bin/../lib/libblas.so"
</code>```

I have found a similar issue in this Github issue. The correct hint is given there as well. Since I am using Manjaro (built on the Arch Linux operating system), there might have been a problem with the Julia installation package that I used.

I removed my Julia installation and installed the official binaries: julia-bin by executing the following command.

```<code>yay -S julia-bin
</code>```

Open the Julia command line again and run the first two commands. This time the output is as follows.

```<code>julia> filter!(p -> occursin("blas", p), Libdl.dllist())
2-element Vector{String}:
 "/usr/bin/../lib/julia/libopenblas64_.so"
 "/usr/bin/../lib/julia/libblastrampoline.so"
</code>```

Executing my notebook works as expected now.

Title: Failed to precompile StatsPlots.jl

Body:
This might be connected to this or this. However, none of the suggested solutions works for me.

I'm using VSCode with the Julia extension and I run everything in a Jupyter notebook. My first cell looks as follows.

using Distributions
using StatsBase
using CSV
using DataFrames
using HypothesisTests
using Plots
using GLM
using StatsPlots

Executing the cell yields to the following error.

ailed to precompile StatsPlots [f3b207a7-027a-5e70-b257-86293d7955fd] to /home/david/.julia/compiled/v1.7/StatsPlots/jl_27z7QU.

Stacktrace:
  [1] compilecache(pkg::Base.PkgId, path::String, internal_stderr::IO, internal_stdout::IO, ignore_loaded_modules::Bool)
    @ Base ./loading.jl:1466
  [2] compilecache(pkg::Base.PkgId, path::String)
    @ Base ./loading.jl:1410
  [3] _require(pkg::Base.PkgId)
    @ Base ./loading.jl:1120
  [4] require(uuidkey::Base.PkgId)
    @ Base ./loading.jl:1013
  [5] require(into::Module, mod::Symbol)
    @ Base ./loading.jl:997
  [6] eval
    @ ./boot.jl:373 [inlined]
  [7] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
    @ Base ./loading.jl:1196
  [8] #invokelatest#2
    @ ./essentials.jl:716 [inlined]
  [9] invokelatest
    @ ./essentials.jl:714 [inlined]
 [10] (::VSCodeServer.var"#150#151"{VSCodeServer.NotebookRunCellArguments, String})()
    @ VSCodeServer ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/VSCodeServer/src/serve_notebook.jl:18
 [11] withpath(f::VSCodeServer.var"#150#151"{VSCodeServer.NotebookRunCellArguments, String}, path::String)
    @ VSCodeServer ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/VSCodeServer/src/repl.jl:185
 [12] notebook_runcell_request(conn::VSCodeServer.JSONRPC.JSONRPCEndpoint{Base.PipeEndpoint, Base.PipeEndpoint}, params::VSCodeServer.NotebookRunCellArguments)
    @ VSCodeServer ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/VSCodeServer/src/serve_notebook.jl:14
 [13] dispatch_msg(x::VSCodeServer.JSONRPC.JSONRPCEndpoint{Base.PipeEndpoint, Base.PipeEndpoint}, dispatcher::VSCodeServer.JSONRPC.MsgDispatcher, msg::Dict{String, Any})
    @ VSCodeServer.JSONRPC ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/JSONRPC/src/typed.jl:67
 [14] serve_notebook(pipename::String; crashreporting_pipename::String)
    @ VSCodeServer ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/packages/VSCodeServer/src/serve_notebook.jl:94
 [15] top-level scope
    @ ~/.vscode/extensions/julialang.language-julia-1.5.11/scripts/notebook/notebook.jl:12

Next, I have opened the Julia command line and removed the StatsPlots extensions using ] rm "StatsPlots" and readded it using ] add "StatsPlots" with no success. I have tried to execute precompile in the command line by hand which yields to the following output.

(@v1.7) pkg> precompile
Precompiling project...
  ✗ Arpack
  ✗ MultivariateStats
  ✗ StatsPlots
  0 dependencies successfully precompiled in 11 seconds (216 already precompiled)

ERROR: The following 1 direct dependency failed to precompile:

StatsPlots [f3b207a7-027a-5e70-b257-86293d7955fd]

Failed to precompile StatsPlots [f3b207a7-027a-5e70-b257-86293d7955fd] to /home/david/.julia/compiled/v1.7/StatsPlots/jl_1XjxNk.
ERROR: LoadError: InitError: could not load library "/home/david/.julia/artifacts/cdf6dc8aa6771a61c6c65a5a5c1a8d1b75f50a2f/lib/libarpack.so"
libopenblas64_.so: cannot open shared object file: No such file or directory
Stacktrace:
 [1] macro expansion
   @ ~/.julia/packages/JLLWrappers/QpMQW/src/products/library_generators.jl:54 [inlined]
 [2] __init__()
   @ Arpack_jll ~/.julia/packages/Arpack_jll/zfgpQ/src/wrappers/x86_64-linux-gnu-libgfortran5.jl:10
 [3] top-level scope (repeats 2 times)
   @ none:1
during initialization of module Arpack_jll
in expression starting at /home/david/.julia/packages/Arpack/pLziT/src/Arpack.jl:2
ERROR: LoadError: Failed to precompile Arpack [7d9fca2a-8960-54d3-9f78-7d1dccf2cb97] to /home/david/.julia/compiled/v1.7/Arpack/jl_fCy8AR.
Stacktrace:
 [1] include(x::String)
   @ MultivariateStats ~/.julia/packages/MultivariateStats/zLpz8/src/MultivariateStats.jl:1
 [2] top-level scope
   @ ~/.julia/packages/MultivariateStats/zLpz8/src/MultivariateStats.jl:113
 [3] top-level scope (repeats 2 times)
   @ none:1
in expression starting at /home/david/.julia/packages/MultivariateStats/zLpz8/src/kpca.jl:3
in expression starting at /home/david/.julia/packages/MultivariateStats/zLpz8/src/MultivariateStats.jl:1
ERROR: LoadError: Failed to precompile MultivariateStats [6f286f6a-111f-5878-ab1e-185364afe411] to /home/david/.julia/compiled/v1.7/MultivariateStats/jl_8Rrih5.
Stacktrace:
 [1] top-level scope (repeats 2 times)
   @ none:1
in expression starting at /home/david/.julia/packages/StatsPlots/CpWiU/src/StatsPlots.jl:1

I have tried to restart the Julia kernel, restart VSCode, and I've tried the solution suggested in the second link that I have provided, meaning removing the package and run gc.

I have also removed and readded MultivariateStats and Arpack but the above error remains.

It might be from interest that it has worked before. I run into a different error first by executing the following cell.

@df data density(:Age, group = :Treatment, title = "Distribution of ages by treatment group", xlab = "Age", ylab="Distribution", legend=:topright)

The above yielded to the following error message.

LoadError: UndefVarError: @df not defined

It might have been the case that I accidently added the outdated extension StatPlots and that might have caused the above issue. However, I've removed the old extension and added the new one.

How can I resolve the above problem?

Edit: Running Pkg.status() yields to the following output.

(@v1.7) pkg> status
      Status `~/.julia/environments/v1.7/Project.toml`
  [336ed68f] CSV v0.10.2
  [8f4d0f93] Conda v1.6.0
  [a93c6f00] DataFrames v1.3.2
  [31c24e10] Distributions v0.25.48
  [38e38edf] GLM v1.6.1
  [a2cc645c] GraphPlot v0.5.0
  [86223c79] Graphs v1.6.0
  [09f84164] HypothesisTests v0.10.6
  [7073ff75] IJulia v1.23.2
  [91a5bcdd] Plots v1.25.8
  [c3e4b0f8] Pluto v0.18.0
  [7f904dfe] PlutoUI v0.7.23
  [438e738f] PyCall v1.93.0
  [d330b81b] PyPlot v2.10.0
  [aa4a32ff] SimpleHypergraphs v0.2.0
  [2913bbd2] StatsBase v0.33.14
  [f3b207a7] StatsPlots v0.14.33

Body:
I was able to resolve the problem. The root of the problem was the missing library libopenblas64. This could be due to a faulty Julia installation. Here is what I have done.

First, open the Julia command line and execute the following two commands.

using Libdl
filter!(p -> occursin("blas", p), Libdl.dllist())

In my case, this yielded to the following output.

1-element Array{String,1}:
 "/usr/bin/../lib/libblas.so"

I have found a similar issue in this Github issue. The correct hint is given there as well. Since I am using Manjaro (built on the Arch Linux operating system), there might have been a problem with the Julia installation package that I used.

I removed my Julia installation and installed the official binaries: julia-bin by executing the following command.

yay -S julia-bin

Open the Julia command line again and run the first two commands. This time the output is as follows.

julia> filter!(p -> occursin("blas", p), Libdl.dllist())
2-element Vector{String}:
 "/usr/bin/../lib/julia/libopenblas64_.so"
 "/usr/bin/../lib/julia/libblastrampoline.so"

Executing my notebook works as expected now.


问:
There is no extension able to load the configuration for "when@test"
I have a problem on my symfony project version 4.4.9, when i type php bin/console make:entity this errors it display to me

There is no extension able to load the configuration for "when@test"

composer.json

```<code>"require": {
    "php": ">=7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "doctrine/annotations": "^1.13",
    "doctrine/doctrine-bundle": "^2.5",
    "doctrine/doctrine-migrations-bundle": "^3.2",
    "doctrine/orm": "^2.11",
    "symfony/console": "4.4.*",
    "symfony/dotenv": "4.4.*",
    "symfony/flex": "^1.3.1",
    "symfony/framework-bundle": "4.4.*",
    "symfony/proxy-manager-bridge": "4.4.*",
    "symfony/twig-bundle": "4.4.*",
    "symfony/yaml": "4.4.*",
    "twig/extra-bundle": "^2.12|^3.0",
    "twig/twig": "^2.12|^3.0"
},
</code>```

PHP 7

答:
problem solved :
i delete this part of code from config>packages>doctrine.yaml  :

when@test:
doctrine:
dbal:
# "TEST_TOKEN" is typically set by ParaTest
dbname_suffix: '_test%env(default::TEST_TOKEN)%'

when@prod:
doctrine:
orm:
auto_generate_proxy_classes: false
query_cache_driver:
type: pool
pool: doctrine.system_cache_pool
result_cache_driver:
type: pool
pool: doctrine.result_cache_pool

```<code>framework:
    cache:
        pools:
            doctrine.result_cache_pool:
                adapter: cache.app
            doctrine.system_cache_pool:
                adapter: cache.system
</code>```

Body:
I have a problem on my symfony project version 4.4.9, when i type php bin/console make:entity this errors it display to me

There is no extension able to load the configuration for "when@test"

composer.json

"require": {
    "php": ">=7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "doctrine/annotations": "^1.13",
    "doctrine/doctrine-bundle": "^2.5",
    "doctrine/doctrine-migrations-bundle": "^3.2",
    "doctrine/orm": "^2.11",
    "symfony/console": "4.4.*",
    "symfony/dotenv": "4.4.*",
    "symfony/flex": "^1.3.1",
    "symfony/framework-bundle": "4.4.*",
    "symfony/proxy-manager-bridge": "4.4.*",
    "symfony/twig-bundle": "4.4.*",
    "symfony/yaml": "4.4.*",
    "twig/extra-bundle": "^2.12|^3.0",
    "twig/twig": "^2.12|^3.0"
},

PHP 7

Body:
problem solved :
i delete this part of code from config>packages>doctrine.yaml  :

when@test:
doctrine:
dbal:
# "TEST_TOKEN" is typically set by ParaTest
dbname_suffix: '_test%env(default::TEST_TOKEN)%'

when@prod:
doctrine:
orm:
auto_generate_proxy_classes: false
query_cache_driver:
type: pool
pool: doctrine.system_cache_pool
result_cache_driver:
type: pool
pool: doctrine.result_cache_pool

framework:
    cache:
        pools:
            doctrine.result_cache_pool:
                adapter: cache.app
            doctrine.system_cache_pool:
                adapter: cache.system


问:
Create a network of unconnected, very small, full connected components
My final aim would be an undirected edgelist of this kind:

Per a network of 3 components, full connected, one with 1 node, one with 2 nodes, one with 3 nodes:

There would be 6 nodes, but since the first component is made only of 1 node, node1 has no edges.

```<code>tibble(from = c(2,4,4,5),
       to = (3,5,6,6)
)
</code>```

But the number of components may higher then 3, let's say 30. The average number of edges within component would be ruled after rpois(30,1)+1.

In tidygraph, the function to create a complete graph would be create_complete, and in theory I could just keep generating complete graph and binding their edgelist. But in that case I would have a problem of naming the edges, and I could miss the unconnected nodes.

答:
Update

If you want to show the cluster labels, you can use membership + components to add this attribute like below

```<code>set.seed(1)
do.call(
  graph.disjoint.union,
  lapply(
    rpois(30, 1) + 1,
    make_full_graph
  )
) %>%
  set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
  set_vertex_attr(name = "cluster_label", value = membership(components(.))) %>%
  as_tbl_graph(directed = FALSE)
</code>```

which gives

```<code># A tbl_graph: 62 nodes and 49 edges
#
# An undirected simple graph with 30 components
#
# Node Data: 62 x 2 (active)
  names cluster_label
  <int>         <dbl>
1     1             1
2     2             2
3     3             2
4     4             3
5     5             3
6     6             4
# ... with 56 more rows
#
# Edge Data: 49 x 2
   from    to
  <int> <int>
1     2     3
2     4     5
3     6     7
# ... with 46 more rows
</code>```

You can use disjoint.union + make_full_graph like below (assuming you have 3 fully connected components with 1,2, and 3 nodes respectively)

```<code>library(tidygraph)
library(igraph)
do.call(
  graph.disjoint.union,
  lapply(
    1:3,
    make_full_graph
  )
) %>%
  set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
  as_tbl_graph(directed = FALSE)
</code>```

which gives you

```<code># A tbl_graph: 6 nodes and 4 edges
#
# An undirected simple graph with 3 components
#
# Node Data: 6 x 1 (active)
  names
  <int>
1     1
2     2
3     3
4     4
5     5
6     6
#
# Edge Data: 4 x 2
   from    to
  <int> <int>
1     2     3
2     4     5
3     4     6
# ... with 1 more row
</code>```

Regarding the use of rpois(30,1)+1, perhaps this could help if you replace 1:3 with rpois(30,1)+1, e.g.,

```<code>set.seed(1)
do.call(
  graph.disjoint.union,
  lapply(
    rpois(30,1)+1,
    make_full_graph
  )
) %>%
  set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
  as_tbl_graph(directed = FALSE)
</code>```

and a graph is generated with the following info

```<code># A tbl_graph: 62 nodes and 49 edges
#
# An undirected simple graph with 30 components
#
# Node Data: 62 x 1 (active)
  names
  <int>
1     1
2     2
3     3
4     4
5     5
6     6
# ... with 56 more rows
#
# Edge Data: 49 x 2
   from    to
  <int> <int>
1     2     3
2     4     5
3     6     7
# ... with 46 more rows
</code>```

Body:
My final aim would be an undirected edgelist of this kind:

Per a network of 3 components, full connected, one with 1 node, one with 2 nodes, one with 3 nodes:

There would be 6 nodes, but since the first component is made only of 1 node, node1 has no edges.

tibble(from = c(2,4,4,5),
       to = (3,5,6,6)
)

But the number of components may higher then 3, let's say 30. The average number of edges within component would be ruled after rpois(30,1)+1.

In tidygraph, the function to create a complete graph would be create_complete, and in theory I could just keep generating complete graph and binding their edgelist. But in that case I would have a problem of naming the edges, and I could miss the unconnected nodes.

Body:
Update

If you want to show the cluster labels, you can use membership + components to add this attribute like below

set.seed(1)
do.call(
  graph.disjoint.union,
  lapply(
    rpois(30, 1) + 1,
    make_full_graph
  )
) %>%
  set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
  set_vertex_attr(name = "cluster_label", value = membership(components(.))) %>%
  as_tbl_graph(directed = FALSE)

which gives

# A tbl_graph: 62 nodes and 49 edges
#
# An undirected simple graph with 30 components
#
# Node Data: 62 x 2 (active)
  names cluster_label
  <int>         <dbl>
1     1             1
2     2             2
3     3             2
4     4             3
5     5             3
6     6             4
# ... with 56 more rows
#
# Edge Data: 49 x 2
   from    to
  <int> <int>
1     2     3
2     4     5
3     6     7
# ... with 46 more rows

You can use disjoint.union + make_full_graph like below (assuming you have 3 fully connected components with 1,2, and 3 nodes respectively)

library(tidygraph)
library(igraph)
do.call(
  graph.disjoint.union,
  lapply(
    1:3,
    make_full_graph
  )
) %>%
  set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
  as_tbl_graph(directed = FALSE)

which gives you

# A tbl_graph: 6 nodes and 4 edges
#
# An undirected simple graph with 3 components
#
# Node Data: 6 x 1 (active)
  names
  <int>
1     1
2     2
3     3
4     4
5     5
6     6
#
# Edge Data: 4 x 2
   from    to
  <int> <int>
1     2     3
2     4     5
3     4     6
# ... with 1 more row

Regarding the use of rpois(30,1)+1, perhaps this could help if you replace 1:3 with rpois(30,1)+1, e.g.,

set.seed(1)
do.call(
  graph.disjoint.union,
  lapply(
    rpois(30,1)+1,
    make_full_graph
  )
) %>%
  set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
  as_tbl_graph(directed = FALSE)

and a graph is generated with the following info

# A tbl_graph: 62 nodes and 49 edges
#
# An undirected simple graph with 30 components
#
# Node Data: 62 x 1 (active)
  names
  <int>
1     1
2     2
3     3
4     4
5     5
6     6
# ... with 56 more rows
#
# Edge Data: 49 x 2
   from    to
  <int> <int>
1     2     3
2     4     5
3     6     7
# ... with 46 more rows


问:
How to keep value of String after clicking Submit button in .jsp?
I have a problem, that after clicking submit button I'm loosing what is already in my textToConsole variable. After submitting, I only have "hello" in it.  How can I prevent from losing the text: "world!"?</p>
```<code><% String textToConsole = "hello"; %>

<form method="POST">
        <div align="center">
            <select name="chooseComboBox" id="chooseComboBox" size="3">
               <option>Option 1</option>
               <option>Option 2</option>
               <option>Option 3</option>
               <option>Option 4</option>
            </select>

            <h2 align="center">Enter the range of dates: </h2>

            <label>Od:</label>
            <input type="date" name="inputFrom"
               value="2020-01-01"
               min="2000-01-01" max="2022-12-31">

            <br><br>
            <label for="inputTo">Do:</label>
            <input type="date" name="inputTo"
               value="2021-01-01"
               min="2000-01-01" max="2022-12-31">

            <br><br><br>
                <input type="submit" style="font-size: 20px;" value="Wyeksportuj do pliku">
            </div>
    </form>

    String chooseComboBox = request.getParameter("chooseComboBox");

    if(chooseComboBox != null) {
          textToConsole += "world!";
    }

    <div align="center" id="logConsole">
        <% out.print(textToConsole); %>
    </div>
</code>```

答: In order to achieve this, store that value inside Httpsession and get it from there!</p>

Body:
I have a problem, that after clicking submit button I'm loosing what is already in my textToConsole variable. After submitting, I only have "hello" in it.  How can I prevent from losing the text: "world!"?

<% String textToConsole = "hello"; %>

<form method="POST">

            <select name="chooseComboBox" id="chooseComboBox" size="3">
               <option>Option 1</option>
               <option>Option 2</option>
               <option>Option 3</option>
               <option>Option 4</option>
            </select>

Enter the range of dates:

            Od:
            <input type="date" name="inputFrom"
               value="2020-01-01"
               min="2000-01-01" max="2022-12-31">

            Do:
            <input type="date" name="inputTo"
               value="2021-01-01"
               min="2000-01-01" max="2022-12-31">

                <input type="submit" style="font-size: 20px;" value="Wyeksportuj do pliku">

    </form>

    String chooseComboBox = request.getParameter("chooseComboBox");

    if(chooseComboBox != null) {
          textToConsole += "world!";
    }

        <% out.print(textToConsole); %>


问:
show dynamic title on a animate matplotlib hist
I'm trying to add a title or a note (the year actualy plot) who change at each itteration of this annimated plot. The code follow show my last attempt with a note "plt.text".
The variable "yrs" is a list like this [1950, 1951, 1952...2020] I want these value to be show at each frame itteration.</p>
```<code># Fixing bin edges
HIST_BINS = np.linspace(data[3].min(), data[var].max(), round(data[var].max())+1)
# histogram our data with numpy
dt = data[var]
dt2 = data[var] # ref
dt2 = dt2[dt2 > 1]
n, _ = np.histogram(dt2, HIST_BINS)

def prepare_animation(bar_container):

    def animate(frame_number):
        # simulate new data coming in
        dt = data.iloc[data.index.year.isin([frame_number]), var]
        dt = dt[dt > 1]
        n, _ = np.histogram(dt, HIST_BINS)
        for count, rect in zip(n, bar_container.patches):
            rect.set_height(count)
        return bar_container.patches

        plt.text(0, 2, str(frame_number),
                 horizontalalignment='left',
                 verticalalignment='center')
     return animate

fig, ax = plt.subplots()
ax.hist(dt2, HIST_BINS, lw=1, weights=np.ones(len(dt2)) / len(dt2)*100,
        color='steelblue', alpha=0.5, label='histo')
_, _, bar_container = ax.hist(dt, HIST_BINS, lw=1, weights=np.ones(len(dt)) / len(dt),
                              color='orange', alpha=0.5, label='window')

ax.set_ylim(top=40)  # set safe limit to ensure that all data is visible.
# ax.set_yscale('log')
plt.legend()
plt.xlabel('mm')
plt.ylabel("freq. %")

ani = animation.FuncAnimation(fig, prepare_animation(bar_container), frames=yrs,
                              repeat=False, blit=True)
plt.show()
</code>```

答: It finally work... when plot to the screen it doesn't work but the saved .gif work fine....</p>

Body:
I'm trying to add a title or a note (the year actualy plot) who change at each itteration of this annimated plot. The code follow show my last attempt with a note "plt.text".
The variable "yrs" is a list like this [1950, 1951, 1952...2020] I want these value to be show at each frame itteration.

# Fixing bin edges
HIST_BINS = np.linspace(data[3].min(), data[var].max(), round(data[var].max())+1)
# histogram our data with numpy
dt = data[var]
dt2 = data[var] # ref
dt2 = dt2[dt2 > 1]
n, _ = np.histogram(dt2, HIST_BINS)

def prepare_animation(bar_container):

    def animate(frame_number):
        # simulate new data coming in
        dt = data.iloc[data.index.year.isin([frame_number]), var]
        dt = dt[dt > 1]
        n, _ = np.histogram(dt, HIST_BINS)
        for count, rect in zip(n, bar_container.patches):
            rect.set_height(count)
        return bar_container.patches

        plt.text(0, 2, str(frame_number),
                 horizontalalignment='left',
                 verticalalignment='center')
     return animate

fig, ax = plt.subplots()
ax.hist(dt2, HIST_BINS, lw=1, weights=np.ones(len(dt2)) / len(dt2)*100,
        color='steelblue', alpha=0.5, label='histo')
_, _, bar_container = ax.hist(dt, HIST_BINS, lw=1, weights=np.ones(len(dt)) / len(dt),
                              color='orange', alpha=0.5, label='window')

ax.set_ylim(top=40)  # set safe limit to ensure that all data is visible.
# ax.set_yscale('log')
plt.legend()
plt.xlabel('mm')
plt.ylabel("freq. %")

ani = animation.FuncAnimation(fig, prepare_animation(bar_container), frames=yrs,
                              repeat=False, blit=True)
plt.show()


问:
FileNotFoundError, when I run shutil.copy, 1 particular ".dylib" file throws FileNotFoundError error every time
I am making a python app and one of it's functions involves copying the contents of one directory to several different locations. Some of these files are copied to the same directory in which they currently reside and are renamed. It almost always works except when it hit this one particular file.

This is the code that does the copying.

```<code>shutil.copy(original_path_and_file,os.path.join(redun.path, redun.file_name))
</code>```

The particular copy that causes the crash is when it's trying to copy /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib to /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.0.dylib

This is the error that appears in my terminal:

```<code>FileNotFoundError: [Errno 2] No such file or directory: '/Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib'
</code>```

Why does this file throw the error and none of the other files that it copies throw any errors?

Update

The file is actually an "Alias" according to finder:

答:
The way I fixed this was by having the app ignore link files. I wrote this:

```<code>if not os.path.islink(original_path_and_file):
    shutil.copy(original_path_and_file,os.path.join(redun.path, redun.file_name))
</code>```

This is technically more of a work-around than a fix because it doesn't actually copy the file but I decided the app still works fine when not copying link files.

Body:
I am making a python app and one of it's functions involves copying the contents of one directory to several different locations. Some of these files are copied to the same directory in which they currently reside and are renamed. It almost always works except when it hit this one particular file.

This is the code that does the copying.

shutil.copy(original_path_and_file,os.path.join(redun.path, redun.file_name))

The particular copy that causes the crash is when it's trying to copy /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib to /Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.0.dylib

This is the error that appears in my terminal:

FileNotFoundError: [Errno 2] No such file or directory: '/Users/<myusername>/Desktop/archive1/test_2_here/myproject/liboqs.dylib'

Why does this file throw the error and none of the other files that it copies throw any errors?

Update

The file is actually an "Alias" according to finder:

Body:
The way I fixed this was by having the app ignore link files. I wrote this:

if not os.path.islink(original_path_and_file):
    shutil.copy(original_path_and_file,os.path.join(redun.path, redun.file_name))

This is technically more of a work-around than a fix because it doesn't actually copy the file but I decided the app still works fine when not copying link files.


问:
Can I use a 3rd party React Native library within a cloud function?
I want to do some functionality where my Cloud Function will securely store information it retrieves from firestore into react-native-keychain. My question is I can import the keychain library into my index.js file in my functions folder to use.
Such as this:

```<code>const keyChain = require("react-native-keychain");
</code>```

Which gives me this error:

答:
Cloud Functions run on Google's servers, where no React Native Keychain is available.

If you need the functionality that library provides in your Cloud Functions code, you'll need to look for a different library that provides the functionality in a server-side Node.js environment.

If you need the information from the keychain inside the React Native app to be available to the Cloud Function, you'll need to read it inside your React Native code, and pass it to the Cloud Function when you call it.

Body:
I want to do some functionality where my Cloud Function will securely store information it retrieves from firestore into react-native-keychain. My question is I can import the keychain library into my index.js file in my functions folder to use.
Such as this:

const keyChain = require("react-native-keychain");

Which gives me this error:


问:
dealloc doesn't work in cocos2d
i have game with cocos2d and method dealloc
i use this to change scene.

```<code>CGSize size = [[CCDirector sharedDirector] winSize];
CCMoveTo* move = [CCMoveTo actionWithDuration:1.0f position:CGPointMake(-(size.width), 0)];
CCEaseBackInOut* ease = [CCEaseBackInOut actionWithAction:move];
CCCallFunc* func = [CCCallFunc actionWithTarget:self selector:@selector(changeScene:)];
CCSequence* sequence = [CCSequence actions:ease, func, nil];
[self runAction:sequence];
</code>```

or this in another scene.

```<code>CCScene* scene = [levelScene scene];
[userName removeFromSuperview];
CCTransitionFlipAngular *transitionScene=[CCTransitionFlipAngular transitionWithDuration:1 scene:scene];
[[CCDirector sharedDirector] replaceScene:transitionScene];
</code>```

whene i changing scene the dealloc method doesn't do anything and onExit method too.
where i can releas my pointers ?or i have and constants wnat to equal to 0 when change scene.
whene i can do it?or why i can use dealloc.

答:
dealloc is only called on an object when the memory management system determines that the object is no longer in use, when the retain count goes to zero.  What are you doing to cause that to happen?  I don't see any release or autorelease methods in your code samples.

You're going to have to be more specific about what you're doing to change scenes for a better answer.

ContentLicense: CC BY-SA 3.0

Title: dealloc doesn't work in cocos2d

Body:
i have game with cocos2d and method dealloc
i use this to change scene.

CGSize size = [[CCDirector sharedDirector] winSize];
CCMoveTo* move = [CCMoveTo actionWithDuration:1.0f position:CGPointMake(-(size.width), 0)];
CCEaseBackInOut* ease = [CCEaseBackInOut actionWithAction:move];
CCCallFunc* func = [CCCallFunc actionWithTarget:self selector:@selector(changeScene:)];
CCSequence* sequence = [CCSequence actions:ease, func, nil];
[self runAction:sequence];

or this in another scene.

CCScene* scene = [levelScene scene];
[userName removeFromSuperview];
CCTransitionFlipAngular *transitionScene=[CCTransitionFlipAngular transitionWithDuration:1 scene:scene];
[[CCDirector sharedDirector] replaceScene:transitionScene];

whene i changing scene the dealloc method doesn't do anything and onExit method too.
where i can releas my pointers ?or i have and constants wnat to equal to 0 when change scene.
whene i can do it?or why i can use dealloc.


答:
According to the C++ 17 Standard (8.3.1 Unary operators)

9 The operand of the logical negation operator ! is contextually
converted to bool (Clause 7); its value is true if the converted
operand is false and false otherwise. The type of the result is bool.

So there is no need to overload the operator !() when there is the conversion operator to the type bool.

Title: Should operator !() be defined in a class if bool() operator is already defined?

Body:
I have a simple class which is a concrete class and is not designed to be inherited. Also I want to be able to say !myobject where myobject is an instance of this class. I've already define operator bool(). Should I also define bool operator!()?

Here is trivial example of the class:

class Test
{
  public:
    ...
    explicit operator bool() {
      return error_ == 0;
    }

    bool operator!() {
      return error_ != 0;
    }

  private:
    int error_;
};

I tried it as !myobject and it works independent of !() operator is being defined or not.
Looks like it is a silly question, but I couldn't find an answer for it.


问:
Loop through dictionary to create a dataframe from function without repeating keys
```<code>dict = {'A': ndarray_1, 'B': ndarray_2, 'C': ndarray_3}
</code>```

I'm trying, without success so far, to use a for loop it in a callable function of a package that return two results and make a dataframe like this:

```<code>Letter | Letter |             Result 1            |          Result 2

  A    |    B   |    result1(ndarray_1,ndarray_2) |  result2(ndarray_1,ndarray_2)
  A    |    C   |    result1(ndarray_1,ndarray_3) |  result2(ndarray_1,ndarray_3)
  B    |    C   |    result1(ndarray_2,ndarray_3) |  result2(ndarray_2,ndarray_3)
</code>```

I'm having trouble acessing the value of each key to use in the function and not repeating ({A,B}, {B,A}, for example)

答:
There might be built-in functions to do this, but here's a simple way to do it from scratch:

Create an ordered list of the keys: keys = dict.keys()

Loop through the indices of the ordered list: for i in range(len(keys)):

Inside that, loop through the indices starting at i+1: for j in range(i + 1, len(keys)):

Inside that, add whatever results to your dataframe using the keys at i and j.

All together:

```<code>keys = dict.keys()

for i in range(len(keys)):
    for j in range(i + 1, len(keys)):
        # add a new row to the dataframe using keys[i] and keys[j]
</code>```

For the intuition, imagine taking a matrix of all dividing it in half diagonally, and then iterating through only the top half:

Body:
dict = {'A': ndarray_1, 'B': ndarray_2, 'C': ndarray_3}

I'm trying, without success so far, to use a for loop it in a callable function of a package that return two results and make a dataframe like this:

Letter | Letter |             Result 1            |          Result 2

  A    |    B   |    result1(ndarray_1,ndarray_2) |  result2(ndarray_1,ndarray_2)
  A    |    C   |    result1(ndarray_1,ndarray_3) |  result2(ndarray_1,ndarray_3)
  B    |    C   |    result1(ndarray_2,ndarray_3) |  result2(ndarray_2,ndarray_3)

I'm having trouble acessing the value of each key to use in the function and not repeating ({A,B}, {B,A}, for example)

Body:
There might be built-in functions to do this, but here's a simple way to do it from scratch:

Create an ordered list of the keys: keys = dict.keys()

Loop through the indices of the ordered list: for i in range(len(keys)):

Inside that, loop through the indices starting at i+1: for j in range(i + 1, len(keys)):

Inside that, add whatever results to your dataframe using the keys at i and j.

All together:

keys = dict.keys()

for i in range(len(keys)):
    for j in range(i + 1, len(keys)):
        # add a new row to the dataframe using keys[i] and keys[j]

For the intuition, imagine taking a matrix of all dividing it in half diagonally, and then iterating through only the top half:


问:
Docker timing out in Azure App Service - using Nextjs
I'm using a Linux server in azure app service. Previously, I was able to deploy my nextjs app with no problems on app service, and it ran just fine. However, after another deployment the docker image suddenly kept timing out. After hours of being unable to fix this, I deleted the app on azure, recreated it, and deployed and everything worked smoothly once again. After another deployment recently, it happened again and the docker image is timing out, and I'm unable to find what the problem is. Before anyone asks, yes, nextjs is starting on port 8080 and I have the PORT and WEBSITES_PORT app variables set to 8080 in app service, you'll also see this in the logs below. My web.config and server.js files are in the root directory. I also used this tutorial to publish the nextjs app on app service: https://parveensingh.com/next-js-deployment-on-azure-app-service/

Here are the logs:

Here's my server.js:

```<code>const next = require("next");

const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    handle(req, res);
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on <http://localhost>:${port}`);
  });
});
</code>```

Here's my web.config:

```<code><!--
     This configuration file is required if iisnode is used to run node processes behind
     IIS or IIS Express.  For more information, visit:

     <https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config>
-->

<configuration>
  <system.webServer>
    <!-- Visit <http://blogs.msdn.com/b/windowsazure/archive/2013/11/14/introduction-to-websockets-on-windows-azure-web-sites.aspx> for more information on WebSocket support -->
    <webSocket enabled="false" />
    <handlers>
      <!-- Indicates that the server.js file is a node.js site to be handled by the iisnode module -->
      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>
        <!-- Do not interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\\/debug[\\/]?" />
        </rule>

        <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <!-- All other URLs are mapped to the node.js site entry point -->
        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <!-- 'bin' directory has no special meaning in node.js and apps can be placed in it -->
    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <!-- Make sure error responses are left untouched -->
    <httpErrors existingResponse="PassThrough" />

    <!--
      You can control how Node is hosted within IIS using the following options:
        * watchedFiles: semi-colon separated list of files that will be watched for changes to restart the server
        * node_env: will be propagated to node as NODE_ENV environment variable
        * debuggingEnabled - controls whether the built-in debugger is enabled

      See <https://github.com/tjanczuk/iisnode/blob/master/src/samples/configuration/web.config> for a full list of options
    -->
    <iisnode watchedFiles="web.config;*.js"/>
  </system.webServer>
</configuration>
</code>```

Here's my package.json scripts:

```<code>"scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "node server.js",
    "lint": "next lint",
    "test": "npx jest"
  },
</code>```

答:
You could try increasing the time allowed for the container to start.

Set WEBSITES_CONTAINER_START_TIME_LIMIT to 1800 (which is the max)

Body:
I'm using a Linux server in azure app service. Previously, I was able to deploy my nextjs app with no problems on app service, and it ran just fine. However, after another deployment the docker image suddenly kept timing out. After hours of being unable to fix this, I deleted the app on azure, recreated it, and deployed and everything worked smoothly once again. After another deployment recently, it happened again and the docker image is timing out, and I'm unable to find what the problem is. Before anyone asks, yes, nextjs is starting on port 8080 and I have the PORT and WEBSITES_PORT app variables set to 8080 in app service, you'll also see this in the logs below. My web.config and server.js files are in the root directory. I also used this tutorial to publish the nextjs app on app service: https://parveensingh.com/next-js-deployment-on-azure-app-service/

Here are the logs:

Here's my server.js:

const next = require("next");

const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    handle(req, res);
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on <http://localhost>:${port}`);
  });
});

Here's my web.config:

<configuration>
  <system.webServer>

    <webSocket enabled="false" />
    <handlers>

      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>
    <rewrite>
      <rules>

        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\\/debug[\\/]?" />
        </rule>

        <rule name="StaticContent">
          <action type="Rewrite" url="public{REQUEST_URI}"/>
        </rule>

        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>

    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <httpErrors existingResponse="PassThrough" />

    <iisnode watchedFiles="web.config;*.js"/>
  </system.webServer>
</configuration>

Here's my package.json scripts:

"scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "node server.js",
    "lint": "next lint",
    "test": "npx jest"
  },


问:
R - Extract Regex groups
I am working with a data frame df with a column text which contains strings of either the form "WORD" or "WORD, WORD2". More precisely, there may be some gibberish before or after these blocks, but I know how to take care of them.

I would like to use the tidyverse function extract to obtain extract the two words into two columns t1 and t2 such that the string "WORD" gets extracted into the "WORD" and NA and

the string "WORDS" gets extracted into "WORDS" and Na,

the string "WORDS, WORD2" gets extracted into "WORDS" and "WORD2".

I tried a command of the following form

```<code>df |> extract(x, c("1", "2"), "([^[:punct:]]+),?[[:space:]]?([^[:punct:]]*)",
              remove = FALSE,
              convert = TRUE)
</code>```

However, this always reads the first row into "WORD" and "" (empty string). How can I modify my version to obtain the desired behaviour?

EDIT: Here is a possible dataframe

```<code>library(tidyverse)

df <- data.frame(x = c("123 WORD", "4564 WORD, TEST 1"))

# Expected output
df_out <- data.frame(x = c("123 WORD", "4564 WORD, TEST 1"),
                     t1 = c("WORD", "WORD"),
                     t2 = c(NA, "TEST"))
</code>```

答:
Maybe something like this:</p>
```<code>df <- data.frame(x = c("123 WORD", "4564 WORD, TEST 1"))

library(tidyverse)

df %>%
  mutate(x1 = str_remove_all(x, '[0-9]*')) %>%
  separate(x1, c("t1", "t2"), sep = ', ', remove = FALSE) %>%
  select(-x1)
</code>```
```<code>                  x    t1    t2
1          123 WORD  WORD  <NA>
2 4564 WORD, TEST 1  WORD TEST
</code>```

Title: R - Extract Regex groups

Body:
I am working with a data frame df with a column text which contains strings of either the form "WORD" or "WORD, WORD2". More precisely, there may be some gibberish before or after these blocks, but I know how to take care of them.

I would like to use the tidyverse function extract to obtain extract the two words into two columns t1 and t2 such that the string "WORD" gets extracted into the "WORD" and NA and

the string "WORDS" gets extracted into "WORDS" and Na,

the string "WORDS, WORD2" gets extracted into "WORDS" and "WORD2".

I tried a command of the following form

df |> extract(x, c("1", "2"), "([^[:punct:]]+),?[[:space:]]?([^[:punct:]]*)",
              remove = FALSE,
              convert = TRUE)

However, this always reads the first row into "WORD" and "" (empty string). How can I modify my version to obtain the desired behaviour?

EDIT: Here is a possible dataframe

library(tidyverse)

df <- data.frame(x = c("123 WORD", "4564 WORD, TEST 1"))

# Expected output
df_out <- data.frame(x = c("123 WORD", "4564 WORD, TEST 1"),
                     t1 = c("WORD", "WORD"),
                     t2 = c(NA, "TEST"))

Body:
Maybe something like this:

df <- data.frame(x = c("123 WORD", "4564 WORD, TEST 1"))

library(tidyverse)

df %>%
  mutate(x1 = str_remove_all(x, '[0-9]*')) %>%
  separate(x1, c("t1", "t2"), sep = ', ', remove = FALSE) %>%
  select(-x1)

                  x    t1    t2
1          123 WORD  WORD  <NA>
2 4564 WORD, TEST 1  WORD TEST


Title: R - Extract Regex groups

Body:
df %>%
  extract(x, c('t1','t2'), '(\\w+)(?:, (\\w+).*)?$', FALSE) %>%
  mutate(across(c(t1, t2), na_if, ''))

                  x   t1   t2
1          123 WORD WORD <NA>
2 4564 WORD, TEST 1 WORD TEST


问:
FullCalendar Vue - Webpack bundling error on /node_modules/@fullcalendar/common/main.css
I am attempting to use @fullcalendar/vue3 along with webpack to bundle an example calendar -- but my webpack bundler is failing when it comes across the css file, saying unexpected token. I assume i would need a proper loader for the css, but I am not sure how it should be.

App.vue component

<template>

    <FullCalendar/>

</template>

```
<p>webpack.config.js <code>rules</code> section</p>
<pre class="lang-js prettyprint-override"><code>rules: [
    {
        test   : /\.vue$/,
        exclude: /node_modules/,
        use    : 'vue-loader'
    },

    {
        test: /\.scss$/,
        use : [
            MiniCssExtractPlugin.loader,
            {loader: 'css-loader', options: {url: false, sourceMap: argv.mode === 'development'}},
            {loader: 'postcss-loader', options: {sourceMap: argv.mode === 'development'}},
            {loader: 'sass-loader', options: {sourceMap: argv.mode === 'development'}}
        ]
    },

    {
        test   : /\.js$/,
        exclude: /node_modules/,
        use    : {
            loader: 'babel-loader'
        }
    }
]
</code>```

答:
I finally figured it out shortly after asking this question. The solution was to add a rule specific to .css files, which I just did the following:

{
    test: /\.css$/,
    use : [
        {loader: MiniCssExtractPlugin.loader},
        {loader: 'css-loader', options: {importLoaders: 1}}
    ]
}
```

Body:
I am attempting to use @fullcalendar/vue3 along with webpack to bundle an example calendar -- but my webpack bundler is failing when it comes across the css file, saying unexpected token. I assume i would need a proper loader for the css, but I am not sure how it should be.

App.vue component

<template>

    <FullCalendar/>

</template>

webpack.config.js rules section

rules: [
    {
        test   : /\.vue$/,
        exclude: /node_modules/,
        use    : 'vue-loader'
    },

    {
        test: /\.scss$/,
        use : [
            MiniCssExtractPlugin.loader,
            {loader: 'css-loader', options: {url: false, sourceMap: argv.mode === 'development'}},
            {loader: 'postcss-loader', options: {sourceMap: argv.mode === 'development'}},
            {loader: 'sass-loader', options: {sourceMap: argv.mode === 'development'}}
        ]
    },

    {
        test   : /\.js$/,
        exclude: /node_modules/,
        use    : {
            loader: 'babel-loader'
        }
    }
]


问:
Select most recent value each given day, based on the latest updated timestamp
For my data depicted below, I need to edit my SQL so that for each given day ('gas_date') I need to select only a single row for each day where this row has the most recent 'LastUpdated' value which I have highlighted in yellow below.

I tried the following sql, however this only selects the max value for LastUpdated from the entire dataset over the entire gas_date range, rather than the max LastUpdated value from each gas day.

```<code>SELECT gas_date, pipeline_point_name, value, LastUpdated from table12
WHERE LastUpdated = (SELECT MAX(LastUpdated) FROM table12)
</code>```

答:
SELECT gas_date, pipeline_point_name, value, LastUpdated
from table12
WHERE LastUpdated in
(
SELECT MAX(LastUpdated)
FROM table12 group by gas_date
)

Subquery returns the Latest Lastupdated date for each day

Body:
For my data depicted below, I need to edit my SQL so that for each given day ('gas_date') I need to select only a single row for each day where this row has the most recent 'LastUpdated' value which I have highlighted in yellow below.

I tried the following sql, however this only selects the max value for LastUpdated from the entire dataset over the entire gas_date range, rather than the max LastUpdated value from each gas day.

SELECT gas_date, pipeline_point_name, value, LastUpdated from table12
WHERE LastUpdated = (SELECT MAX(LastUpdated) FROM table12)


问:
Hide imports within another package python

Problem

I use Jupyter a lot, and while using jupyter i have the same list of imports that are long and cumbersome, something like:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.core.display import display, HTML
from ipywidgets import interact, IntSlider
from IPython.display import display

pd.options.display.max_columns = 35
pd.options.display.max_rows = 300

plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 170 # 200 e.g. is really fine, but slower

import IPython.display as ipd
plt.ion()

display(HTML("<style>.container { width:95% !important; }</style>"))

def plot_frozen(df, num_rows=30, num_columns=30, step_rows=1,
                  step_columns=1):
    """
    Freeze the headers (column and index names) of a Pandas DataFrame. A widget
    enables to slide through the rows and columns.

    Parameters
    ----------
    df : Pandas DataFrame
        DataFrame to display
    num_rows : int, optional
        Number of rows to display
    num_columns : int, optional
        Number of columns to display
    step_rows : int, optional
        Step in the rows
    step_columns : int, optional
        Step in the columns

    Returns
    -------
    Displays the DataFrame with the widget
    """
    @interact(last_row=IntSlider(min=min(num_rows, df.shape[0]),
                                 max=df.shape[0],
                                 step=step_rows,
                                 description='rows',
                                 readout=False,
                                 disabled=False,
                                 continuous_update=True,
                                 orientation='horizontal',
                                 slider_color='purple'),
              last_column=IntSlider(min=min(num_columns, df.shape[1]),
                                    max=df.shape[1],
                                    step=step_columns,
                                    description='columns',
                                    readout=False,
                                    disabled=False,
                                    continuous_update=True,
                                    orientation='horizontal',
                                    slider_color='purple'))
    def _freeze_header(last_row, last_column):
        display(df.iloc[max(0, last_row-num_rows):last_row,
                        max(0, last_column-num_columns):last_column])
</code>```

It's imports and a bunch of plotting/display helper functions.

Is there a way for me to bundle all of this up into a single pip package so that i can only have a line or two?

I'm imagining running:

```<code>pip install Genesis
</code>```

then inside my jupyter notebook have:

```<code>import Genesis
</code>```

and nothing else.

What I've tried:

I've tried making a genesis package that is basically a copy of this guide but with a single file called jupyter.py that contains the setup code above.

Then I run the following:

```<code>from Genesis import jupyter
jupyter.setup()
</code>```

But it doesn't import pandas,numpy and matplotlib.pyplot for me. It makes sense because those packages are imported within the scope of the package. But any way to avoid that? Is it even possible in Python?

答:
You can make a package with all your imports no problem, you just need to be careful of namespaces.

Say I have a file:

# genesis/__init__.py
import pandas as pd
import numpy as np
...
```
<p>Importing that genesis package will run that code, but it won't be accessible directly</p>
<pre class="lang-py prettyprint-override"><code>>>> import genesis
>>> help(np)
raceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'np' is not defined

>>> help(genesis.np) # This should succeed
...
</code>```

You could address this with from genesis import * which would bring everything into the namespace you expect

e.g.

>>> from genesis import *
>>> help(np) # This should succeed
...
```

Body:
Problem

I use Jupyter a lot, and while using jupyter i have the same list of imports that are long and cumbersome, something like:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.core.display import display, HTML
from ipywidgets import interact, IntSlider
from IPython.display import display

pd.options.display.max_columns = 35
pd.options.display.max_rows = 300

plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 170 # 200 e.g. is really fine, but slower

import IPython.display as ipd
plt.ion()

display(HTML(""))

def plot_frozen(df, num_rows=30, num_columns=30, step_rows=1,
                  step_columns=1):
    """
    Freeze the headers (column and index names) of a Pandas DataFrame. A widget
    enables to slide through the rows and columns.

    Parameters
    ----------
    df : Pandas DataFrame
        DataFrame to display
    num_rows : int, optional
        Number of rows to display
    num_columns : int, optional
        Number of columns to display
    step_rows : int, optional
        Step in the rows
    step_columns : int, optional
        Step in the columns

    Returns
    -------
    Displays the DataFrame with the widget
    """
    @interact(last_row=IntSlider(min=min(num_rows, df.shape[0]),
                                 max=df.shape[0],
                                 step=step_rows,
                                 description='rows',
                                 readout=False,
                                 disabled=False,
                                 continuous_update=True,
                                 orientation='horizontal',
                                 slider_color='purple'),
              last_column=IntSlider(min=min(num_columns, df.shape[1]),
                                    max=df.shape[1],
                                    step=step_columns,
                                    description='columns',
                                    readout=False,
                                    disabled=False,
                                    continuous_update=True,
                                    orientation='horizontal',
                                    slider_color='purple'))
    def _freeze_header(last_row, last_column):
        display(df.iloc[max(0, last_row-num_rows):last_row,
                        max(0, last_column-num_columns):last_column])

It's imports and a bunch of plotting/display helper functions.

Is there a way for me to bundle all of this up into a single pip package so that i can only have a line or two?

I'm imagining running:

pip install Genesis

then inside my jupyter notebook have:

import Genesis

and nothing else.

What I've tried:

I've tried making a genesis package that is basically a copy of this guide but with a single file called jupyter.py that contains the setup code above.

Then I run the following:

from Genesis import jupyter
jupyter.setup()

But it doesn't import pandas,numpy and matplotlib.pyplot for me. It makes sense because those packages are imported within the scope of the package. But any way to avoid that? Is it even possible in Python?

Body:
You can make a package with all your imports no problem, you just need to be careful of namespaces.

Say I have a file:

# genesis/__init__.py
import pandas as pd
import numpy as np
...

Importing that genesis package will run that code, but it won't be accessible directly

>>> import genesis
>>> help(np)
raceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'np' is not defined

>>> help(genesis.np) # This should succeed
...

You could address this with from genesis import * which would bring everything into the namespace you expect

e.g.

>>> from genesis import *
>>> help(np) # This should succeed
...


问:
ctags.exe & etags.exe return Permission denied
I have ctags.exe and etags.exe installed via scoop installer and emacs app.

No matter how I run it, I always get a Permission denied error output.

Whether with CMD user or admin permissions (elevated permissions thing).

```<code>tomas@NUC8I7HVK D:\playground\c\milton\src
# ctags.exe .
.: Permission denied

$ C:\Users\tomas\scoop\apps\emacs\current\bin\ctags.exe .
.: Permission denied
</code>```

This is the version used:

```<code># ctags.exe -V
ctags (GNU Emacs 26.2)
Copyright (C) 2019 Free Software Foundation, Inc.
This program is distributed under the terms in ETAGS.README
</code>```

I would say this is a Windows 10 thing, though I haven't found any help online.

答:
I found a work around for using etags on directory trees that you might interested in.  You can run a for loop and use the -a flag to append to the TAGS file like so:

```<code>for /r %y in (*.c) do etags -a %y
</code>```

The /r option in the for loop will execute the for loop in each directory of the tree.

You can also make a bat script:

```<code>for /r %%y in (*.c) do etags -a %%y
for /r %%y in (*.h) do etags -a %%y
</code>```

Body:
I have ctags.exe and etags.exe installed via scoop installer and emacs app.

No matter how I run it, I always get a Permission denied error output.

Whether with CMD user or admin permissions (elevated permissions thing).

tomas@NUC8I7HVK D:\playground\c\milton\src
# ctags.exe .
.: Permission denied

$ C:\Users\tomas\scoop\apps\emacs\current\bin\ctags.exe .
.: Permission denied

This is the version used:

# ctags.exe -V
ctags (GNU Emacs 26.2)
Copyright (C) 2019 Free Software Foundation, Inc.
This program is distributed under the terms in ETAGS.README

I would say this is a Windows 10 thing, though I haven't found any help online.

Body:
I found a work around for using etags on directory trees that you might interested in.  You can run a for loop and use the -a flag to append to the TAGS file like so:

for /r %y in (*.c) do etags -a %y

The /r option in the for loop will execute the for loop in each directory of the tree.

You can also make a bat script:

for /r %%y in (*.c) do etags -a %%y
for /r %%y in (*.h) do etags -a %%y


问:
swapaxes and how it is implemented?
I'm wondering if someone can explain this code to me?

```<code>c = self.config

assert len(pair_act.shape) == 3
assert len(pair_mask.shape) == 2
assert c.orientation in ['per_row', 'per_column']

if c.orientation == 'per_column':
  pair_act = jnp.swapaxes(pair_act, -2, -3)
  pair_mask = jnp.swapaxes(pair_mask, -1, -2)
</code>```

It looks like pair_act is a 3D array and pair_mask is a 2D array? What are the numbers -1, -2, and -3? For 3D arrays, my initial thought is that the array is 0, column is 1, and row is 2. So where does the - sign come from? Any array examples would be appreciated. Thanks for the help.

答:
The documentation for jax.numpy.swapaxes is here: https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.swapaxes.html

The effect of swapaxes is essentially to transpose the two provided axes, resulting in a differently shaped array:

import jax.numpy as jnp

x = jnp.arange(24).reshape((2, 3, 4))
print(x.shape)
# (2, 3, 4)

y = jnp.swapaxes(x, 1, 2)
print(y.shape)
# (2, 4, 3)
```
<p>As is standard in numpy indexing, negative numbers count backward from the end; here the indices refer to entries in the shape (which has length 3), so <code>-2, -1</code> is equivalent to <code>1, 2</code>:</p>
<pre class="lang-python prettyprint-override"><code>y = jnp.swapaxes(x, -2, -1)
print(y.shape)
# (2, 4, 3)
</code>```

The result of a swapaxes is equivalent to an appropriately constructed transpose operation:

y2 = jnp.transpose(x, (0, 2, 1))
print((y == y2).all())
# True
```

Title: swapaxes and how it is implemented?

Body:
I'm wondering if someone can explain this code to me?

c = self.config

assert len(pair_act.shape) == 3
assert len(pair_mask.shape) == 2
assert c.orientation in ['per_row', 'per_column']

if c.orientation == 'per_column':
  pair_act = jnp.swapaxes(pair_act, -2, -3)
  pair_mask = jnp.swapaxes(pair_mask, -1, -2)

It looks like pair_act is a 3D array and pair_mask is a 2D array? What are the numbers -1, -2, and -3? For 3D arrays, my initial thought is that the array is 0, column is 1, and row is 2. So where does the - sign come from? Any array examples would be appreciated. Thanks for the help.

Body:
The documentation for jax.numpy.swapaxes is here: https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.swapaxes.html

The effect of swapaxes is essentially to transpose the two provided axes, resulting in a differently shaped array:

import jax.numpy as jnp

x = jnp.arange(24).reshape((2, 3, 4))
print(x.shape)
# (2, 3, 4)

y = jnp.swapaxes(x, 1, 2)
print(y.shape)
# (2, 4, 3)

As is standard in numpy indexing, negative numbers count backward from the end; here the indices refer to entries in the shape (which has length 3), so -2, -1 is equivalent to 1, 2:

y = jnp.swapaxes(x, -2, -1)
print(y.shape)
# (2, 4, 3)

The result of a swapaxes is equivalent to an appropriately constructed transpose operation:

y2 = jnp.transpose(x, (0, 2, 1))
print((y == y2).all())
# True


问:
While clicking on the tab with HorizontalPager in android Jetpack Compse, it jumps to the last tab
While clicking on the tab with HorizontalPager in android Jetpack Compse, it jumps to the last tab
I add the code to see the problem visible

This is my code ->

```<code>data class TabPage(val title: String?, val icon: ImageVector? = null, var screen: (@Composable () -> Unit)? = null)

@OptIn(ExperimentalPagerApi::class)
@Composable
fun SwipeableTabLayout(
    modifier: Modifier = Modifier,
    tabPages: List<TabPage>
) {
    val pagerState = rememberPagerState()
    val scope = rememberCoroutineScope()
    Surface(color = Color.White) {
        Column {
            TabRow(selectedTabIndex = pagerState.currentPage) {
                tabPages.forEachIndexed { index, tabPage ->
                    Tab(
                        modifier = modifier,
                        selected = index == pagerState.currentPage,
                        onClick = { scope.launch { pagerState.animateScrollToPage(index) } },
                        text = tabPage.title?.let { title -> { Text(text = title) } },
                        icon = tabPage.icon?.let { icon -> { Icon(imageVector = icon, contentDescription = null) } }
                    )
                }
            }

            HorizontalPager(
                state = pagerState,
                count = tabPages.size,
                content = { page -> tabPages[page].screen?.invoke() })
        }
    }
}

</code>```

And this is where it is used ->

```<code>enum class SnackbarType(val value: String) {
    ERROR("Error"),
    WARNING("Warning"),
    SUCCESS("Success"),
    INFO("Info")
}

@Composable
fun CoreComponentsSnackbarScreen(onNavigate: (Destination) -> Unit) {
    val tabPages = listOf(
        TabPage(title = SnackbarType.ERROR.value, screen = { LoadScreen() }),
        TabPage(title = SnackbarType.WARNING.value, screen = { LoadScreen() }),
        TabPage(title = SnackbarType.SUCCESS.value, screen = { LoadScreen() }),
        TabPage(title = SnackbarType.INFO.value, screen = { LoadScreen() })
    )

    Scaffold(
        content = {
            SwipeableTabLayout(tabPages = tabPages, scrollable = true)
        }
    )
}

@Composable
private fun LoadScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {

        Text(text = "One line")

        Text(text = "Two lines")

        Text(text = "One line with action")

        Text(text = "Two lines with action")
    }
}

</code>```

If the LoadScreen() function just loads a simple text, it works well but when you add more items, while clicking it jumps to the last tab

e.g. with this LoadScreen() works fine ->

```<code>@Composable
private fun LoadScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {

        Text(text = "One line")

}
</code>```

答: The problem exists in Kotlin version 1.5.31 and compose version 1.0.5 with upgrading to the latest Kotlin version 1.6.10 and relatively upgrading compose version, bug fixed.

Body:
While clicking on the tab with HorizontalPager in android Jetpack Compse, it jumps to the last tab
I add the code to see the problem visible

This is my code ->

data class TabPage(val title: String?, val icon: ImageVector? = null, var screen: (@Composable () -> Unit)? = null)

@OptIn(ExperimentalPagerApi::class)
@Composable
fun SwipeableTabLayout(
    modifier: Modifier = Modifier,
    tabPages: List<TabPage>
) {
    val pagerState = rememberPagerState()
    val scope = rememberCoroutineScope()
    Surface(color = Color.White) {
        Column {
            TabRow(selectedTabIndex = pagerState.currentPage) {
                tabPages.forEachIndexed { index, tabPage ->
                    Tab(
                        modifier = modifier,
                        selected = index == pagerState.currentPage,
                        onClick = { scope.launch { pagerState.animateScrollToPage(index) } },
                        text = tabPage.title?.let { title -> { Text(text = title) } },
                        icon = tabPage.icon?.let { icon -> { Icon(imageVector = icon, contentDescription = null) } }
                    )
                }
            }

            HorizontalPager(
                state = pagerState,
                count = tabPages.size,
                content = { page -> tabPages[page].screen?.invoke() })
        }
    }
}

And this is where it is used ->

enum class SnackbarType(val value: String) {
    ERROR("Error"),
    WARNING("Warning"),
    SUCCESS("Success"),
    INFO("Info")
}

@Composable
fun CoreComponentsSnackbarScreen(onNavigate: (Destination) -> Unit) {
    val tabPages = listOf(
        TabPage(title = SnackbarType.ERROR.value, screen = { LoadScreen() }),
        TabPage(title = SnackbarType.WARNING.value, screen = { LoadScreen() }),
        TabPage(title = SnackbarType.SUCCESS.value, screen = { LoadScreen() }),
        TabPage(title = SnackbarType.INFO.value, screen = { LoadScreen() })
    )

    Scaffold(
        content = {
            SwipeableTabLayout(tabPages = tabPages, scrollable = true)
        }
    )
}

@Composable
private fun LoadScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {

        Text(text = "One line")

        Text(text = "Two lines")

        Text(text = "One line with action")

        Text(text = "Two lines with action")
    }
}

If the LoadScreen() function just loads a simple text, it works well but when you add more items, while clicking it jumps to the last tab

e.g. with this LoadScreen() works fine ->

@Composable
private fun LoadScreen() {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {

        Text(text = "One line")

}


问:
AWS S3 display file inline instead of force download
For some reason files in my S3 bucket are being forced as downloads instead of displaying in-line so if I copy an image link and paste it into address bar and then navigate to it, it will promote my browser to download it. Instead I actually have to click on open image to go to the url.

Any ways to change the way files are served from S3

答: What really worked for me was to set the ContentType params to image/png  before saving the S3 file.


问:
Using Spring IoC to set up enum values
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

```<code>public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}
</code>```

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

答: Why not provide a setter (or constructor argument) that takes a String, and simply call Enum.valueOf(String s) to convert from a String to an enum. Note an exception will get thrown if this fails, and your Spring initialisation will bail out.</p>

OwnerDisplayName: Olivier

Title: Using Spring IoC to set up enum values

Body:
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

LastEditorDisplayName: Olivier

OwnerDisplayName: Brian Agnew

ContentLicense: CC BY-SA 2.5