问:
Advantage of switching from ASP.NET to bread & butter HTML/jQuery
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

```

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

```

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

答:
You don't have to give up everything, like MasterPages. You might try to turn off ViewState, turn off EventValidation and use as little ASP.NET controls as possible (basically - if some functionality can be easily achieved with XHTML, write it as XHTML). You can still use ASP.NET controls where you need them.

I think that you're not alone. After two years of working with WebForms I also got tired of them and after I discovered how wonderful jQuery was and how well it worked with web services I vastly changed my development model. I am slowly moving towards MVC right now, as I find it the ultimate solution, but for some other apps (small and/or targetting 2.0) I just try to use less server controls, get rid of ViewState, use more AJAX (web services). It works fine. I'd recommend Dave Ward's Encosia - start with this article. I admit it opened my eyes on some other ways to developing web applications using .NET Framework. Good luck!

OwnerDisplayName: Martin

Body:
I have been getting more and more sick of all the quirks about control ids, trying to get your data in serverside (based on client-side events). I seem to spend more time fighting with controls in asp.net, that I think it takes me more time than I gain by using it.

I was thinking about using plain html/javascript with jQuery and a web service that returns json for the data.

The only thing I think I would miss from webforms is the MasterPages, the session management, authentication based on windows login and possibly validators(although they have some quirks too). (In fact, maybe not for sessions and auth, but I have never developped webservices)

Is there something wrong with the way
I am thinking about this, or
something I didn't think about ?

Are there things in asp.net that you
think I will miss ?

Has anyone done this before and wants to share experience ?

Please, also take note, that I only have the Framework 2.0 available for development.

Edit: The kind of things giving me troubles in asp.net that makes me wonder for the switch:

Here is a sample of a page giving me problems.

There is a tree table (master / details)

You can edit fields on each child row.

When you press the save button, the data from the group row must be updated (just data from a select, no modification in database), as
the data from the child row.

I don't want to refresh the whole page because the displayed records are based from search criterias.

The Master / Details are generated using Repeaters

Trying to update a record from code behind is really quirky, and still have no clue about updating the display.

Using jQuery and a web service, my guess would be that i could update directly to the database, request what I want to be displayed and just update that record. This is the kind of things that make me wonder if asp.net is just getting in my way.

 ________________________________________________________________________
| -  Some             Details           About            Group           |
|________________________________________________________________________|
    |¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    | ChildRecord Some  Editable  Fields       SaveButton   |
    |_______________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|
 ________________________________________________________________________
| +  Some             Details           About            Group           |
|________________________________________________________________________|

Edit2:
The problem I have about ASP.NET is not related to ajax. Yes, I use jQuery to make the interfaces more dynamic like showing / hiding the search section when not needed and collapsing details from the tree, but this is all I do with it.

What bothers me is that if I want to check which button has been clicked in this example, I have to use some tricks that feel a bit haky.

If you want to use databound comboboxes in a repeater, you have to use codebehind to set the selected value, it will be a pain to retreive the data selected.

Next, if you want to check what data was modified, you have to save the datatable in the viewstate, read data from all controls in the repeater, then compare with the datatable to make an update. This is this kind of things that bother me with asp.net.

LastEditorDisplayName: Martin

OwnerDisplayName: Pawel Krakowiak


来源: stackexchange

问:
Function pointers and functors
Are function pointers functors ? Is there a virtual functor in use that helps sibling functors compile silently ? </p>

答:
At least as the term is normally used in C++ (Warning: it's used entirely differently relative to other languages such as Haskell), a functor is a class (or an instance of a class) that overloads operator() so it can be invoked like a function.

Since they use the same syntax, a template can be written to accept either a pointer to a function or an instance of a functor interchangeably. Not all algorithms will do so however -- some expect (for example) that you supply something with typedefs for things like argument_type and result_type. The standard library provides a couple of classes (unary_function and binary_function) to use as base classes for your functors to supply these. You can supply them on your own if you prefer -- these base classes are purely for convenience (and some people don't find them particularly convenient).

ContentLicense: CC BY-SA 3.0

Title: Function pointers and functors


问:
How can I use two columns to create date forcasts - e.g use the alternative column if the main column is blank? (automated ideally)
I'm trying to create a spreadsheet which automates dates based on two columns. I would like it to mainly work of 'Confirmed Delivery (column P)' but if the date is blank can I automate a formula to use the 'Estimated Delivery' (Column O)?

So far I have:
=ARRAYFORMULA(IF(T3:T<>"",O3:O+5,""))

but ideally I need this to be P3:P+5 or if blank O3:0.

Is this possible?

答:
You can create an extra column Q which contains the value from column P if there is a value and column O otherwise by:

=IF(P1, P1, O1) in the Q1 cell and then drag down.

Now you can use column Q in your new formula.

ContentLicense: CC BY-SA 4.0


问:
Unable to install Dotnet Stryker
I have tried the below commands to install dotnet stryker to my project to improve the mutation testing but getting below error message and it does not allow me to install the tool.
Could you please help on this.

Thanks in advance

```<code>PS C:\Users> dotnet tool install -g dotnet-stryker
C:\Program Files\dotnet\sdk\6.0.101\NuGet.targets(130,5): error : Unable to load the service index for source https://api.nuget.org/v3/index.json. [C:\Users\AppData\Local\Temp\evv2az1v.kwa\restore.csproj]
C:\Program Files\dotnet\sdk\6.0.101\NuGet.targets(130,5): error :   A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (api.nuget.org:443) [C:\Users\AppData\Local\Temp\evv2az1v.kwa\restore.csproj]
C:\Program Files\dotnet\sdk\6.0.101\NuGet.targets(130,5): error :   A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. [C:\Users\AppData\Local\Temp\evv2az1v.kwa\restore.csproj]
The tool package could not be restored.
Tool 'dotnet-stryker' failed to install. This failure may have been caused by:

* You are attempting to install a preview release and did not use the --version option to specify the version.
* A package by this name was found, but it was not a .NET tool.
* The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
* You mistyped the name of the tool.
</code>```

Below commands are also getting the same error message

PS C:\Users> dotnet tool install -g dotnet-stryker dotnet tool install --global dotnet-stryker --version 1.0.0

答:
This is most probably not related to Stryker but to some weird NuGet situation.  You can check it by installing some common tool, e.g dotnet-reportgenerator-globaltool. I think I have seen this kind of error when setting up local feeds for dev purposes.

So try this:

dotnet nuget list source - list feeds

dotnet nuget remove source <feed_name> - remove everything you don't need or understand

And then try installing Stryker once again.

Title: Unable to install Dotnet Stryker

Body:
I have tried the below commands to install dotnet stryker to my project to improve the mutation testing but getting below error message and it does not allow me to install the tool.
Could you please help on this.

Thanks in advance

PS C:\Users> dotnet tool install -g dotnet-stryker
C:\Program Files\dotnet\sdk\6.0.101\NuGet.targets(130,5): error : Unable to load the service index for source https://api.nuget.org/v3/index.json. [C:\Users\AppData\Local\Temp\evv2az1v.kwa\restore.csproj]
C:\Program Files\dotnet\sdk\6.0.101\NuGet.targets(130,5): error :   A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. (api.nuget.org:443) [C:\Users\AppData\Local\Temp\evv2az1v.kwa\restore.csproj]
C:\Program Files\dotnet\sdk\6.0.101\NuGet.targets(130,5): error :   A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. [C:\Users\AppData\Local\Temp\evv2az1v.kwa\restore.csproj]
The tool package could not be restored.
Tool 'dotnet-stryker' failed to install. This failure may have been caused by:

* You are attempting to install a preview release and did not use the --version option to specify the version.
* A package by this name was found, but it was not a .NET tool.
* The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
* You mistyped the name of the tool.

Below commands are also getting the same error message

PS C:\Users> dotnet tool install -g dotnet-stryker dotnet tool install --global dotnet-stryker --version 1.0.0


问:
How to change the host to use GeoLite2
hello i am new to coding and i wanted to build something for a personal project and i came across MaxMind's ip finding api. Their paid version which is GeoIp2 is a bit expensive for me but they do have a free version which is GeoLite2. But their documentation dont have any example to how to import it.

Python documentation for GeoIp2

>>> import geoip2.webservice
>>>
>>> # This creates a Client object that can be reused across requests.
>>> # Replace "42" with your account ID and "license_key" with your license
>>> # key. Set the "host" keyword argument to "geolite.info" to use the
>>> # GeoLite2 web service instead of GeoIP2 Precision.
>>> with geoip2.webservice.Client(42, 'license_key') as client:
>>>
>>>     # Replace "city" with the method corresponding to the web service
>>>     # that you are using, i.e., "country", "city", or "insights". Please
>>>     # note that Insights is not supported by the GeoLite2 web service.
>>>     response = client.city('203.0.113.0')
```

In the comments they have mentioned to change the host to use GeoLite2 but i dont understand what i need to change. I tried every possible thing from my side and failed. If anyone can help me with this ;-;

答:
if you leave out the 'host =' it works.
so just .Client(ID, License_key, "geolite.info")</p>

Title: How to change the host to use GeoLite2

Body:
hello i am new to coding and i wanted to build something for a personal project and i came across MaxMind's ip finding api. Their paid version which is GeoIp2 is a bit expensive for me but they do have a free version which is GeoLite2. But their documentation dont have any example to how to import it.

Python documentation for GeoIp2

>>> import geoip2.webservice
>>>
>>> # This creates a Client object that can be reused across requests.
>>> # Replace "42" with your account ID and "license_key" with your license
>>> # key. Set the "host" keyword argument to "geolite.info" to use the
>>> # GeoLite2 web service instead of GeoIP2 Precision.
>>> with geoip2.webservice.Client(42, 'license_key') as client:
>>>
>>>     # Replace "city" with the method corresponding to the web service
>>>     # that you are using, i.e., "country", "city", or "insights". Please
>>>     # note that Insights is not supported by the GeoLite2 web service.
>>>     response = client.city('203.0.113.0')

In the comments they have mentioned to change the host to use GeoLite2 but i dont understand what i need to change. I tried every possible thing from my side and failed. If anyone can help me with this ;-;


问:
Not able to launch Flutter app on Android device
I am trying to launch my Flutter app on an Android device, I was able just until yesterday, but suddenly today I am getting this error when launching it:

```<code>Launching lib/main.dart on Moto G 5S in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings remapped class cache for 7yvt6la2007dno98lt3rzbguf (/Users/modestovascofornas/.gradle/caches/6.3/scripts-remapped/settings_bwqg3axqhj874bje5e9od2vqv/7yvt6la2007dno98lt3rzbguf/settingsdeec0faa97453e2ce860d75e6bf1604b).
> Could not open settings generic class cache for settings file '/Users/modestovascofornas/desarrollo/DESARROLLO 2022 SSD-2/2022-G2-CAPENERGY-FLUTTER-PROFESIONAL/FLUTTER/flutter_capenergy/android/settings.gradle' (/Users/modestovascofornas/.gradle/caches/6.3/scripts/7yvt6la2007dno98lt3rzbguf/settings/settingsdeec0faa97453e2ce860d75e6bf1604b).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 24s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

I have tried deleting .gradle folder, but not working

EDIT

This is my ~/.zshrc file

```<code>export PATH=/Users/modestovascofornas/flutter/bin:$PATH
export PATH=/Users/modestovascofornas/flutter/.pub-cache/bin:$PATH
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home
</code>```

答:
You could try this:

Open the terminal in your IDE and issue the command:

```<code>flutter clean
</code>```

Try to launch the app again.

Body:
I am trying to launch my Flutter app on an Android device, I was able just until yesterday, but suddenly today I am getting this error when launching it:

Launching lib/main.dart on Moto G 5S in debug mode...
Running Gradle task 'assembleDebug'...

FAILURE: Build failed with an exception.

* What went wrong:
Could not open settings remapped class cache for 7yvt6la2007dno98lt3rzbguf (/Users/modestovascofornas/.gradle/caches/6.3/scripts-remapped/settings_bwqg3axqhj874bje5e9od2vqv/7yvt6la2007dno98lt3rzbguf/settingsdeec0faa97453e2ce860d75e6bf1604b).
> Could not open settings generic class cache for settings file '/Users/modestovascofornas/desarrollo/DESARROLLO 2022 SSD-2/2022-G2-CAPENERGY-FLUTTER-PROFESIONAL/FLUTTER/flutter_capenergy/android/settings.gradle' (/Users/modestovascofornas/.gradle/caches/6.3/scripts/7yvt6la2007dno98lt3rzbguf/settings/settingsdeec0faa97453e2ce860d75e6bf1604b).
   > BUG! exception in phase 'semantic analysis' in source unit '_BuildScript_' Unsupported class file major version 61

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 24s
Exception: Gradle task assembleDebug failed with exit code 1

I have tried deleting .gradle folder, but not working

EDIT

This is my ~/.zshrc file

export PATH=/Users/modestovascofornas/flutter/bin:$PATH
export PATH=/Users/modestovascofornas/flutter/.pub-cache/bin:$PATH
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home

Body:
You could try this:

Open the terminal in your IDE and issue the command:

flutter clean

Try to launch the app again.


问:
Closest subsequent index for a specified value
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)
```
<p>I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.</p>
<p>For instance,</p>
<pre class="lang-r prettyprint-override"><code>f(int, 0)
# [1] 2 1 0 2 1 0 0 NA
</code>```

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA
```
<p>This should also work for character vectors:</p>
<pre class="lang-r prettyprint-override"><code>char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0
</code>```

答:
Another possible solution, based on purrr::map2_dbl:

library(purrr)

int = c(1, 1, 0, 5, 2, 0, 0, 2)

f <- function(int, num)
{
  n <- length(int)

  map2_dbl(num, 1:n, ~ ifelse(length(which(.x == int[.y:n])) == 0, NA,
      min(which(.x == int[.y:n])) - 1))
}

f(int, 0)
#> [1]  2  1  0  2  1  0  0 NA

f(int, 1)
#> [1]  0  0 NA NA NA NA NA NA

f(int, 2)
#> [1] 4 3 2 1 0 2 1 0

f(int, 3)
#> [1] NA NA NA NA NA NA NA NA

char = c("A", "B", "C", "A", "A")

f(char, "A")
#> [1] 0 2 1 0 0
```

Body:
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)

I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.

For instance,

f(int, 0)
# [1] 2 1 0 2 1 0 0 NA

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA

This should also work for character vectors:

char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0


问:
Neo4j Dgs.fastrp.write returnsUnionProperties must all have the same type, but found [LONG, DOUBLE, DOUBLE, DOUBLE]" error
I am working on a large graph consisting of different type of labels, and these labels have their own properties.

```<code>CALL gds.graph.create(
'derin',
{
Transaction: {
label: 'Transaction',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Withdraw: {
label: 'Withdraw',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Loan: {
label: 'Loan',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Customer: {
label: 'Customer',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}}, {
SENDS: {type: 'SENDS', orientation: 'UNDIRECTED'},
RECEIVES: {type: 'RECEIVES', orientation: 'UNDIRECTED'},
INSPECTS: {type: 'INSPECTS', orientation: 'UNDIRECTED'},
WITHDRAWS: {type: 'WITHDRAWS', orientation: 'UNDIRECTED'},
APPLIES: {type: 'APPLIES', orientation: 'UNDIRECTED'}
})
</code>```

I created a graph with default values because of missing properties. After creation, I am running the query;

```<code>CALL gds.fastRP.write('derin'
,{
embeddingDimension: 32,
writeProperty: 'fast_embedding',
propertyRatio: 0.2,
featureProperties: ['legacy_customer', 'trx_amount', 'atm_trx', 'fast_credit_flag', 'silver_bullet_flag']
}
)
</code>```

I got the error "Failed to invoke procedure gds.fastRP.write: Caused by: java.lang.IllegalArgumentException: UnionProperties must all have the same type, but found [LONG, DOUBLE, DOUBLE, DOUBLE]". Any help or suggestion would be great. Thanks.

答:
Thanks to @jose_bacoy, my answer is inspired from bacoy's response. When I check existing types after graph creation with query

```<code> MATCH (n:Transaction)
 RETURN DISTINCT apoc.meta.type(n.trx_amount)  limit 25
</code>```

And repeat it for all labels. I saw the some missing (null, trx_amount) values are exists for Transaction label. Non-missing values are all float type. So, I updated my graph creation query with default value in float type (1000.0 instead 1000) as shown in below;

```<code>CALL gds.graph.create(
'derin',
{
Transaction: {
label: 'Transaction',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000.0}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Withdraw: {
label: 'Withdraw',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000.0}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Loan: {
label: 'Loan',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000.0}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Customer: {
label: 'Customer',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000.0}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}}, {
SENDS: {type: 'SENDS', orientation: 'UNDIRECTED'},
RECEIVES: {type: 'RECEIVES', orientation: 'UNDIRECTED'},
INSPECTS: {type: 'INSPECTS', orientation: 'UNDIRECTED'},
WITHDRAWS: {type: 'WITHDRAWS', orientation: 'UNDIRECTED'},
APPLIES: {type: 'APPLIES', orientation: 'UNDIRECTED'}
})
</code>```

That solves my problem.

Body:
I am working on a large graph consisting of different type of labels, and these labels have their own properties.

CALL gds.graph.create(
'derin',
{
Transaction: {
label: 'Transaction',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Withdraw: {
label: 'Withdraw',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Loan: {
label: 'Loan',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Customer: {
label: 'Customer',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}}, {
SENDS: {type: 'SENDS', orientation: 'UNDIRECTED'},
RECEIVES: {type: 'RECEIVES', orientation: 'UNDIRECTED'},
INSPECTS: {type: 'INSPECTS', orientation: 'UNDIRECTED'},
WITHDRAWS: {type: 'WITHDRAWS', orientation: 'UNDIRECTED'},
APPLIES: {type: 'APPLIES', orientation: 'UNDIRECTED'}
})

I created a graph with default values because of missing properties. After creation, I am running the query;

CALL gds.fastRP.write('derin'
,{
embeddingDimension: 32,
writeProperty: 'fast_embedding',
propertyRatio: 0.2,
featureProperties: ['legacy_customer', 'trx_amount', 'atm_trx', 'fast_credit_flag', 'silver_bullet_flag']
}
)

I got the error "Failed to invoke procedure gds.fastRP.write: Caused by: java.lang.IllegalArgumentException: UnionProperties must all have the same type, but found [LONG, DOUBLE, DOUBLE, DOUBLE]". Any help or suggestion would be great. Thanks.

Body:
Thanks to @jose_bacoy, my answer is inspired from bacoy's response. When I check existing types after graph creation with query

 MATCH (n:Transaction)
 RETURN DISTINCT apoc.meta.type(n.trx_amount)  limit 25

And repeat it for all labels. I saw the some missing (null, trx_amount) values are exists for Transaction label. Non-missing values are all float type. So, I updated my graph creation query with default value in float type (1000.0 instead 1000) as shown in below;

CALL gds.graph.create(
'derin',
{
Transaction: {
label: 'Transaction',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000.0}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Withdraw: {
label: 'Withdraw',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000.0}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Loan: {
label: 'Loan',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000.0}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}
, Customer: {
label: 'Customer',
properties: {legacy_customer: {defaultValue: 0}
, trx_amount: {defaultValue: 1000.0}
, atm_trx: {defaultValue: 0}
, fast_credit_flag: {defaultValue: 0}
, silver_bullet_flag: {defaultValue: 0}
}
}}, {
SENDS: {type: 'SENDS', orientation: 'UNDIRECTED'},
RECEIVES: {type: 'RECEIVES', orientation: 'UNDIRECTED'},
INSPECTS: {type: 'INSPECTS', orientation: 'UNDIRECTED'},
WITHDRAWS: {type: 'WITHDRAWS', orientation: 'UNDIRECTED'},
APPLIES: {type: 'APPLIES', orientation: 'UNDIRECTED'}
})

That solves my problem.


问:
Package not detected after renamed in Intellij
I have a project in intellij and when I created my packages I made a mistake because they all start in capital letter, for example my previous package name was "Main" then I changed it to "main" and I did it to all of my packages.

error: package com.myproject.thesis.main does not exist import
  com.myproject.thesis.main.Main;

but the "main" package and "Main" class does exist and already imported on the class that needs it. Also what should I name the package where I put my main class?

答: Just clean the contents in /target (or "mvn clean"), and Intellij can find your new package correctly.</p>


问:
Can not get Fragment Tag That I set
I make a transition and then I gave a tag to the fragment while transition but
when I tried to find my fragment via tag fragment tag is null  here is my code

Main Activity.java

HomeFragment homeFragment = new HomeFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainerView, homeFragment, HomeFragment.class.getName()).addToBackStack("HomeFragment");

Then I go Home Fragment and pass Fragment manager to adapter

```<code> homePageRecyclerViewAdapter = new HomePageRecyclerViewAdapter(AppRepository.get_instance().setMenuItems(), container.getContext(), requireActivity().getSupportFragmentManager());
</code>```

After that  I navigate to another fragment and I want to remove Home fragment
I want to find my fragment via tag but when I debug it  I check fragmentManager.getFragments() I see Home fragment but is tag is null

```<code> String TAG = selectedFragment.getClass().getName();

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.add(R.id.fragmentContainerView,selectedFragment,TAG).addToBackStack(TAG).commit();

    HomeFragment homeFragment = (HomeFragment) fragmentManager.findFragmentByTag(HomeFragment.class.getName());

    if (homeFragment != null){

        fragmentTransaction.remove(homeFragment);
    }
</code>```

答:
Dont know if it helps, but try to add a constant as you TAG variable and assign a string to it. Ex in kotlin:

```<code>const val TAG_HOME_FRAG: "Home Fragment"
</code>```

And when making the transition and removing it, call the constant.

Title: Can not get Fragment Tag That I set

Body:
I make a transition and then I gave a tag to the fragment while transition but
when I tried to find my fragment via tag fragment tag is null  here is my code

Main Activity.java

HomeFragment homeFragment = new HomeFragment(); getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainerView, homeFragment, HomeFragment.class.getName()).addToBackStack("HomeFragment");

Then I go Home Fragment and pass Fragment manager to adapter

 homePageRecyclerViewAdapter = new HomePageRecyclerViewAdapter(AppRepository.get_instance().setMenuItems(), container.getContext(), requireActivity().getSupportFragmentManager());

After that  I navigate to another fragment and I want to remove Home fragment
I want to find my fragment via tag but when I debug it  I check fragmentManager.getFragments() I see Home fragment but is tag is null

 String TAG = selectedFragment.getClass().getName();

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    fragmentTransaction.add(R.id.fragmentContainerView,selectedFragment,TAG).addToBackStack(TAG).commit();

    HomeFragment homeFragment = (HomeFragment) fragmentManager.findFragmentByTag(HomeFragment.class.getName());

    if (homeFragment != null){

        fragmentTransaction.remove(homeFragment);
    }

Body:
Dont know if it helps, but try to add a constant as you TAG variable and assign a string to it. Ex in kotlin:

const val TAG_HOME_FRAG: "Home Fragment"

And when making the transition and removing it, call the constant.


问:
Standardized md5 hashing in typescript (Angular)
I am trying to generate an id that is generated in the backend, in the frontend (not the best of practices, I know). The id is an Md5 hash of several (dynamically generated, i.e, I don't know the hash in advance) strings concatenated together. So what I tried to do is to use the Md5 class (in ts-md5/dist/md5) to create an Md5 hash:

```<code>getId(s1: string, s2: string, s3: string) : string {
    return Md5.hashStr(`${s1}/${s2}/${s3}`);
}
</code>```

But, the hash returned by the backend did not match the hash returned by getId().

Here is how I create the hash in the backend (Python):

id = hashlib.md5("some_string_seed".encode("utf-8")).hexdigest()
```
<p>I thought that maybe the problem is in the encoding, but adding encoding didn't change anything:</p>
```encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}
return Md5.hashStr(encode_utf8(`${s1}/${s2}/${s3}`));
```

I tried some basic examples but the hashes just don't match.

How do I make the hashes the same? (cannot modify the backend)

答: The solution for me was to use crypto-js, whose md5 hashing algorithm produces the same result as the hashlib, Python library.

Body:
I am trying to generate an id that is generated in the backend, in the frontend (not the best of practices, I know). The id is an Md5 hash of several (dynamically generated, i.e, I don't know the hash in advance) strings concatenated together. So what I tried to do is to use the Md5 class (in ts-md5/dist/md5) to create an Md5 hash:

getId(s1: string, s2: string, s3: string) : string {
    return Md5.hashStr(`${s1}/${s2}/${s3}`);
}

But, the hash returned by the backend did not match the hash returned by getId().

Here is how I create the hash in the backend (Python):

id = hashlib.md5("some_string_seed".encode("utf-8")).hexdigest()

I thought that maybe the problem is in the encoding, but adding encoding didn't change anything:

encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}
return Md5.hashStr(encode_utf8(`${s1}/${s2}/${s3}`));

I tried some basic examples but the hashes just don't match.

How do I make the hashes the same? (cannot modify the backend)


问:
Python 2D image generation
What are some of the better libraries for image generation in Python? If I were to implement a GOTCHA (for example's sake), thereby having to manipulate an image on the pixel level, what would my options be? Ideally I would like to save resulting image as a low-resolution jpeg, but this is mere wishing, I'll settle for any common image format.

Thank you for your attention.

答:
If you should generate text or other vector based images (and then save to .png or .jpg), you could also consider Cairo (PyCairo, in this case). I use it a lot.
Otherwise, for pixel-level manipulation, PIL is the obvious choice.</p>

ContentLicense: CC BY-SA 2.5

Title: Python 2D image generation


问:
Using conda-forge as default channel with Anaconda to install packages on Mac Pro M1
I just started a new job, and they gave me a Mac pro to work with. I was reading about the new M1 processor and everything, I found this article particularly useful.

However, I still have one doubt about it. If I didn’t misunderstand, in the article they suggest using either Anaconda (with Rosetta2 translation), OR to install Miniforge, which sets conda-forge as default and only channel, in order to download packages compiled specifically for the M1. I found different tutorials, and they all suggest using Miniforge to install packages on the M1.

My question is…can’t I just use Anaconda, and set conda-forge as the only installation channel, to get M1-compiled packages, like it would do with Miniforge? Or am I misunderstanding something?
Thanks!

答:
Update

I stand corrected. A bit of explanation: In each channel, there exist subdirs for different OS and architectures. When you install conda, then it will automatically look in the correct subdir for all channels that you configure. The difference between a conda that was installed for arm and x64 will be in what subdirs it looks. E.g. for my conda on a linux machine (installed through miniconda) where I added the conda-forge channel manually, the list of channels actually looks like this:

```<code>           channel URLs : https://conda.anaconda.org/conda-forge/linux-64
                          https://conda.anaconda.org/conda-forge/noarch
                          https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
</code>```

On your MAC, it will look similar for your 64bit installation of anaconda/miniconda. Now to the difference between miniforge and anaconda/miniconda: The first is already preconfigured to use the conda-forge channel, the latter ones can be configured to to the same. So far, no difference. The sole difference will be that you can only install x64 versions of anaconda and miniconda, but miniforge can be installed as an arm64 installation, which will look into different sub-directories of conda-forge, i.e. conda-forge/osx-arm64.

You can however modify which sub-directory is considered when a conda command is run. I have no experience on how stable that works though. This can be achieved by setting the environment variable CONDA_SUBDIR=osx-arm64 which you can set each time before running a specific command, or you just set it using the conda env config command for your environment. You will have to make sure that all packages in an env will be installed while the CONDA_SUBDIR=osx-arm64 variable is set though.

Old

There are currently only 64 bit installers for anaconda. All that come along it will be 64bit. All modules installed will be targeted for 64 bit and conda will download 64bit modules. You cannot install arm modules to a 64 bit conda installation. You will need to decide:

"Convenience" (very subjective) of anaconda, i.e. getting a bunch of pre installed packages targeted for 64 bit

An installation specific for your architecture with possible speed and other advantages

Body:
Update

I stand corrected. A bit of explanation: In each channel, there exist subdirs for different OS and architectures. When you install conda, then it will automatically look in the correct subdir for all channels that you configure. The difference between a conda that was installed for arm and x64 will be in what subdirs it looks. E.g. for my conda on a linux machine (installed through miniconda) where I added the conda-forge channel manually, the list of channels actually looks like this:

           channel URLs : https://conda.anaconda.org/conda-forge/linux-64
                          https://conda.anaconda.org/conda-forge/noarch
                          https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch

On your MAC, it will look similar for your 64bit installation of anaconda/miniconda. Now to the difference between miniforge and anaconda/miniconda: The first is already preconfigured to use the conda-forge channel, the latter ones can be configured to to the same. So far, no difference. The sole difference will be that you can only install x64 versions of anaconda and miniconda, but miniforge can be installed as an arm64 installation, which will look into different sub-directories of conda-forge, i.e. conda-forge/osx-arm64.

You can however modify which sub-directory is considered when a conda command is run. I have no experience on how stable that works though. This can be achieved by setting the environment variable CONDA_SUBDIR=osx-arm64 which you can set each time before running a specific command, or you just set it using the conda env config command for your environment. You will have to make sure that all packages in an env will be installed while the CONDA_SUBDIR=osx-arm64 variable is set though.

Old

There are currently only 64 bit installers for anaconda. All that come along it will be 64bit. All modules installed will be targeted for 64 bit and conda will download 64bit modules. You cannot install arm modules to a 64 bit conda installation. You will need to decide:

"Convenience" (very subjective) of anaconda, i.e. getting a bunch of pre installed packages targeted for 64 bit

An installation specific for your architecture with possible speed and other advantages


问:
An AWS CI/CD Pipeline that allows manual deploy by commit

Background

I want to create the following CI/CD flow in AWS and Github, for a react app using Amplify:

A single main branch, with short-lived feature branches and PRs into main.

Each PR triggers its own test environment in Amplify, with its own temporary subdomain, which gets torn down when the PR is merged, as described here.

Merging into main does not automatically trigger a deploy to production.

Instead, there is a separate mechanism (a web page, or amplify command, or even triggers based on git tags) for manually selecting a commit from main to deploy to production.

Questions

It's not clear to me if...

Support for this flow is already built into Amplify (based on the docs I've read, I think the answer is "no", but I'm not sure).

Support for this flow is already built into AWS CodePipeline, or if it can be configured there.

There is another AWS tool that solves this.

I'm looking for answers to those questions, or specific references in the docs which address them.

答:
The answers for Amplify are Yes, Yes, Yes, Partially.

(1) A single main branch, with short-lived feature branches and PRs into main.

Yes.  Feature branch deploys.  Can define which branch patterns, such as feature*/, you wish to auto-deploy.

(2) Each PR triggers its own test environment in Amplify, with its own temporary subdomain,

Yes.  Web Previews for PRs.  "A web preview deploys every pull request made to your GitHub repository to a unique preview URL which is completely different from the URL your main site uses."

(3) Merging into main does not automatically trigger a deploy to production.

Yes.  Disable automatic builds on main.

(4) Instead, there is a separate mechanism ... for manually selecting a commit from main to deploy to production.

Partially (HEAD only?).  Call the StartJob API to manually trigger a build from, say, Lambda.  The job type RELEASE starts a new job with the latest change from the specified branch.  I am not sure if jobType: MANUAL with a commitId starts a job from an arbitrary commit hash.

Another workaround for 3+4 is to skip the build for an arbitrary commit.  Amplify will skip building if [skip-cd] appears at the end of a commit message.


问:
How to add multiple conditions in JSON schema?
I have the below JSON schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "op": {
        "type": "string",
        "minLength": 1,
        "enum": [
          "add",
          "remove",
          "replace"
        ]
      },
      "path": {
        "type": "string",
        "minLength": 1,
        "enum": [
          "/name",
          "/description",
          "/prefix"
        ]
      },
      "value": {
        "type": "string",
        "minLength": 1
      }
    },
    "additionalProperties": false,
    "required": [
      "op",
      "path",
      "value"
    ],
    "minItems": 1,
    "allOf": [
      {
        "if" : {
          "properties": {
            "path" : {
              "const": "/name"
            }
          }
        },
        "then": {
          "properties": {
            "op": {
              "const": "replace"
            }
          }
        }
      },
      {
        "if" : {
          "properties": {
            "path" : {
              "const": "/description"
            }
          }
        },
        "then": {
          "properties": {
            "op": {
              "const": "replace"
            }
          }
        }
      }
    ]
  }
}
```

As above we can see , if name and description are there ,then op will be replace and for path prefix I have all the operations i.e  add , remove and replace , but i want a special condition to be applied for remove operation
Like if path is xFix and op is remove then required parameters should not contain value attrribute , so only op and path.

答:
I think you'll want to turn the logic of that around.  Do not include "value" in the "required" list.  Instead, add a condition that says, basically, "if op is not 'remove', then value is required".</p>
```<code>  {
    "if" : {
      "not": {
        "properties": {
          "op" : {
            "const": "remove"
          }
        }
      }
    },
    "then": {
      "required": ["value"]
    }
  }
</code>```

Body:
I have the below JSON schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "op": {
        "type": "string",
        "minLength": 1,
        "enum": [
          "add",
          "remove",
          "replace"
        ]
      },
      "path": {
        "type": "string",
        "minLength": 1,
        "enum": [
          "/name",
          "/description",
          "/prefix"
        ]
      },
      "value": {
        "type": "string",
        "minLength": 1
      }
    },
    "additionalProperties": false,
    "required": [
      "op",
      "path",
      "value"
    ],
    "minItems": 1,
    "allOf": [
      {
        "if" : {
          "properties": {
            "path" : {
              "const": "/name"
            }
          }
        },
        "then": {
          "properties": {
            "op": {
              "const": "replace"
            }
          }
        }
      },
      {
        "if" : {
          "properties": {
            "path" : {
              "const": "/description"
            }
          }
        },
        "then": {
          "properties": {
            "op": {
              "const": "replace"
            }
          }
        }
      }
    ]
  }
}

As above we can see , if name and description are there ,then op will be replace and for path prefix I have all the operations i.e  add , remove and replace , but i want a special condition to be applied for remove operation
Like if path is xFix and op is remove then required parameters should not contain value attrribute , so only op and path.

Body:
I think you'll want to turn the logic of that around.  Do not include "value" in the "required" list.  Instead, add a condition that says, basically, "if op is not 'remove', then value is required".

  {
    "if" : {
      "not": {
        "properties": {
          "op" : {
            "const": "remove"
          }
        }
      }
    },
    "then": {
      "required": ["value"]
    }
  }


问:
How do I browse a Websphere MQ message without removing it?
I'm writing a .NET Windows Forms application that will post a message to a Websphere MQ queue and then poll a different queue for a response. If a response is returned, the application will partially process the response in real time. But the response needs to stay in the queue so that a daily batch job, which also reads from the response queue, can do the rest of the processing.

I've gotten as far as reading the message. What I haven't been able to figure out is how to read it without removing it.

Here's what I've got so far. I'm an MQ newbie, so any suggestions will be appreciated. And feel free to respond in C#.

```<code>Public Function GetMessage(ByVal msgID As String) As MQMessage
    Dim q = ConnectToResponseQueue()
    Dim msg As New MQMessage()
    Dim getOpts As New MQGetMessageOptions()
    Dim runThru = Now.AddMilliseconds(CInt(ConfigurationManager.AppSettings("responseTimeoutMS")))
    System.Threading.Thread.Sleep(1000) 'Wait for one second before checking for the first response'
    While True
        Try
            q.Get(msg, getOpts)
            Return msg
        Catch ex As MQException When ex.Reason = MQC.MQRC_NO_MSG_AVAILABLE
            If Now > runThru Then Throw ex
            System.Threading.Thread.Sleep(3000)
        Finally
            q.Close()
        End Try
    End While
    Return Nothing 'Should never reach here'
End Function
</code>```

NOTE: I haven't verified that my code actually removes the message. But that's how I understand MQ to work, and that appears to be what's happening. Please correct me if that's not the default behavior.

答:
FOR READ :

AccessQueue Option : MQOO_BROWSE And MQGetMessageOptions : MQGMO_BROWSE_NEXT

Body:
I'm writing a .NET Windows Forms application that will post a message to a Websphere MQ queue and then poll a different queue for a response. If a response is returned, the application will partially process the response in real time. But the response needs to stay in the queue so that a daily batch job, which also reads from the response queue, can do the rest of the processing.

I've gotten as far as reading the message. What I haven't been able to figure out is how to read it without removing it.

Here's what I've got so far. I'm an MQ newbie, so any suggestions will be appreciated. And feel free to respond in C#.

Public Function GetMessage(ByVal msgID As String) As MQMessage
    Dim q = ConnectToResponseQueue()
    Dim msg As New MQMessage()
    Dim getOpts As New MQGetMessageOptions()
    Dim runThru = Now.AddMilliseconds(CInt(ConfigurationManager.AppSettings("responseTimeoutMS")))
    System.Threading.Thread.Sleep(1000) 'Wait for one second before checking for the first response'
    While True
        Try
            q.Get(msg, getOpts)
            Return msg
        Catch ex As MQException When ex.Reason = MQC.MQRC_NO_MSG_AVAILABLE
            If Now > runThru Then Throw ex
            System.Threading.Thread.Sleep(3000)
        Finally
            q.Close()
        End Try
    End While
    Return Nothing 'Should never reach here'
End Function

NOTE: I haven't verified that my code actually removes the message. But that's how I understand MQ to work, and that appears to be what's happening. Please correct me if that's not the default behavior.


问:
How to code and plot the performance of two trading strategies
So I have the monthly returns on the SP500 in addition to the risk free rate in a zoo timeseries object called SP500.df . I want to backtest two different trading strategies and plot them in a graph. In form of either cumulative return, or just how much 1$ intial investment would be at end of period.

Strategy 1:  buy and hold SP500 the whole period.

Strategy 2: Hold SP500 from nov - april (winter), then switch to risk free rate from may - october (summer).

Notice that I also have extracted the winter and summer return in two respective vectors. called Winter_returns and summer_returns.

mkt= returns

rf= risk free rate

this is how dataframe SP500.df looks:

```<code>dput(head(SP500.df, 10))

structure(c(0.0286195, 0.03618317, -0.01363269, 0.02977401, 0.04461314,
0.0015209, -0.03207303, -0.0079275, 0.01882991, 0.00584478, 0.02372219,
0.03299206, -0.017908, 0.02540426, 0.04163062, -0.00317315, -0.03732322,
-0.0109474, 0.0147047, 0.00087712, 0.00608527826274047, 0.00495046849033236,
0.00503506482970477, 0.00481634688889247, 0.00424210936461577,
0.00358500724272255, 0.00424210936461577, 0.00480928182207086,
0.00485872460615713, 0.00487990531586144, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
0, 0), .Dim = c(10L, 6L), .Dimnames = list(NULL, c("MKT", "CAP",
"RF", "dummy", "dummyJAN", "adjdummy")), index = structure(c(-36494,
-36466, -36435, -36405, -36374, -36344, -36313, -36282, -36252,
-36221), class = "Date"), class = "zoo")
</code>```

答:
Here is a way.

Define a calculations function calc and apply it to the column MKT to have  strategy 1 then create a vector of all returns/rates rates and apply the function to it. The plot uses base R graphics.

library(zoo)

calc <- function(x, returns) x*cumprod((1 + returns))

strat1 <- calc(1, SP500.df$MKT)
strat1
#> 1870-01-31 1870-02-28 1870-03-31 1870-04-30 1870-05-31 1870-06-30 1870-07-31
#>   1.028620   1.065838   1.051308   1.082610   1.130908   1.132628   1.096301
#> 1870-08-31 1870-09-30 1870-10-31
#>   1.087610   1.108090   1.114567

i_winter <- SP500.df$dummy == 1
rates <- numeric(NROW(SP500.df))
rates[i_winter] <- SP500.df$MKT[i_winter]
rates[!i_winter] <- SP500.df$RF[!i_winter]
strat2 <- calc(1, rates)
strat2
#>  [1] 1.028620 1.065838 1.051308 1.082610 1.087202 1.091100 1.095728 1.100998
#>  [9] 1.106347 1.111746

matplot(cbind(strat1, strat2), pch = 19)
matlines(cbind(strat1, strat2), lty = "solid")
legend("bottomright", legend = c("strategy 1", "strategy 2"),
       col = 1:2, lty = "solid", pch = 19)
```
<p><img src="https://i.imgur.com/xx93wQE.png" alt="" /></p>
<p><sup>Created on 2022-02-07 by the reprex package (v2.0.1)</sup></p>
<p>With <code>ggplot2</code> graphics, create a temporary data.frame and pipe it to package <code>tidyr</code>'s reshaping function <code>pivot_longer</code>. Then pipe the result to <code>ggplot</code>.</p>
<pre class="lang-r prettyprint-override"><code>library(ggplot2)

data.frame(
  date = index(SP500.df),
  strategy1 = strat1,
  strategy2 = strat2
) |>
  tidyr::pivot_longer(-date) |>
  ggplot(aes(date, value, color = name)) +
  geom_line() +
  geom_point() +
  scale_color_manual(values = c("black", "red")) +
  theme_bw()
</code>```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
So I have the monthly returns on the SP500 in addition to the risk free rate in a zoo timeseries object called SP500.df . I want to backtest two different trading strategies and plot them in a graph. In form of either cumulative return, or just how much 1$ intial investment would be at end of period.

Strategy 1:  buy and hold SP500 the whole period.

Strategy 2: Hold SP500 from nov - april (winter), then switch to risk free rate from may - october (summer).

Notice that I also have extracted the winter and summer return in two respective vectors. called Winter_returns and summer_returns.

mkt= returns

rf= risk free rate

this is how dataframe SP500.df looks:

dput(head(SP500.df, 10))

structure(c(0.0286195, 0.03618317, -0.01363269, 0.02977401, 0.04461314,
0.0015209, -0.03207303, -0.0079275, 0.01882991, 0.00584478, 0.02372219,
0.03299206, -0.017908, 0.02540426, 0.04163062, -0.00317315, -0.03732322,
-0.0109474, 0.0147047, 0.00087712, 0.00608527826274047, 0.00495046849033236,
0.00503506482970477, 0.00481634688889247, 0.00424210936461577,
0.00358500724272255, 0.00424210936461577, 0.00480928182207086,
0.00485872460615713, 0.00487990531586144, 1, 1, 1, 1, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
0, 0), .Dim = c(10L, 6L), .Dimnames = list(NULL, c("MKT", "CAP",
"RF", "dummy", "dummyJAN", "adjdummy")), index = structure(c(-36494,
-36466, -36435, -36405, -36374, -36344, -36313, -36282, -36252,
-36221), class = "Date"), class = "zoo")

Body:
Here is a way.

Define a calculations function calc and apply it to the column MKT to have  strategy 1 then create a vector of all returns/rates rates and apply the function to it. The plot uses base R graphics.

library(zoo)

calc <- function(x, returns) x*cumprod((1 + returns))

strat1 <- calc(1, SP500.df$MKT)
strat1
#> 1870-01-31 1870-02-28 1870-03-31 1870-04-30 1870-05-31 1870-06-30 1870-07-31
#>   1.028620   1.065838   1.051308   1.082610   1.130908   1.132628   1.096301
#> 1870-08-31 1870-09-30 1870-10-31
#>   1.087610   1.108090   1.114567

i_winter <- SP500.df$dummy == 1
rates <- numeric(NROW(SP500.df))
rates[i_winter] <- SP500.df$MKT[i_winter]
rates[!i_winter] <- SP500.df$RF[!i_winter]
strat2 <- calc(1, rates)
strat2
#>  [1] 1.028620 1.065838 1.051308 1.082610 1.087202 1.091100 1.095728 1.100998
#>  [9] 1.106347 1.111746

matplot(cbind(strat1, strat2), pch = 19)
matlines(cbind(strat1, strat2), lty = "solid")
legend("bottomright", legend = c("strategy 1", "strategy 2"),
       col = 1:2, lty = "solid", pch = 19)

Created on 2022-02-07 by the reprex package (v2.0.1)

With ggplot2 graphics, create a temporary data.frame and pipe it to package tidyr's reshaping function pivot_longer. Then pipe the result to ggplot.

library(ggplot2)

data.frame(
  date = index(SP500.df),
  strategy1 = strat1,
  strategy2 = strat2
) |>
  tidyr::pivot_longer(-date) |>
  ggplot(aes(date, value, color = name)) +
  geom_line() +
  geom_point() +
  scale_color_manual(values = c("black", "red")) +
  theme_bw()

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
Is conversion of a function pointer to a uintptr_t / intptr_t invalid?
Microsoft extensions to C and C++:

To perform the same cast and also maintain ANSI compatibility, you can cast the function pointer
to a uintptr_t before you cast it to a data pointer:

```<code>int ( * pfunc ) ();
int *pdata;
pdata = ( int * ) (uintptr_t) pfunc;
</code>```

Rationale for C, Revision 5.10, April-2003:

Even with an explicit cast, it is invalid to convert a function pointer to an object pointer
or a pointer to void, or vice versa.

C11:

7.20.1.4 Integer types capable of holding object pointers

Does it mean that pdata = ( int * ) (uintptr_t) pfunc; in invalid?

As Steve Summit says:

The C standard is written to assume that pointers to different object types, and especially pointers to function as opposed to object types, might have different representations.

While pdata = ( int * ) pfunc; leads to UB, it seems that pdata = ( int * ) (uintptr_t) pfunc; leads to IB. This is because "Any pointer type may be converted to an integer type" and "An integer may be converted to any pointer type" and uintptr_t is integer type.

答:
Given the definitions

```<code>int (*pfunc)();
int *pdata;
</code>```

, the assignments

```<code>pdata = (int *)pfunc;
pdata = (int *)(uintptr_t)pfunc;
</code>```

are, IMO, equivalent.  On a platform where data pointers are of the same size as, or larger than, function pointers, both assignments will work as desired.  But on a platform where data pointers are smaller than function pointers, both assignments will inevitably scrape off some of the bits of the function pointer, resulting in a data pointer which can not be converted back to the original function pointer later.

In particular, I believe that both assignments are equivalent despite the presence of the (uintptr_t) cast in the second one.  I believe that cast accomplishes precisely nothing.

On a platform where data pointers are smaller than function pointers, and where type uintptr_t is of the same size as data pointers, in the assignment

```<code>pdata = (int *)(uintptr_t)pfunc;
</code>```

, the cast to (uintptr_t) will scrape off some of the bits of pfunc's value.

On a platform where data pointers are smaller than function pointers, and where type uintptr_t is of the same size as function pointers, in the assignment

```<code>pdata = (int *)(uintptr_t)pfunc;
</code>```

, the cast to (int *) will scrape off some of the bits of pfunc's value.

In both cases pdata will end up with only some fraction of pfunc's original value.

(Here I disregard the possibility of architectures with padding bits or the like.  On some bizarre, hypothetical platform where function pointers are larger than data pointers, but the extra bits are always 0, both assignments would again work.)

(I've also disregarded the possibility that int * is a different size than void *.  I'm not sure whether that would affect the answer, whether a "detour" via void * is more or less un- or necessary when attempting a conversion from int (*)() to int *.)

Body:
Microsoft extensions to C and C++:

To perform the same cast and also maintain ANSI compatibility, you can cast the function pointer
to a uintptr_t before you cast it to a data pointer:

int ( * pfunc ) ();
int *pdata;
pdata = ( int * ) (uintptr_t) pfunc;

Rationale for C, Revision 5.10, April-2003:

Even with an explicit cast, it is invalid to convert a function pointer to an object pointer
or a pointer to void, or vice versa.

C11:

7.20.1.4 Integer types capable of holding object pointers

Does it mean that pdata = ( int * ) (uintptr_t) pfunc; in invalid?

As Steve Summit says:

The C standard is written to assume that pointers to different object types, and especially pointers to function as opposed to object types, might have different representations.

While pdata = ( int * ) pfunc; leads to UB, it seems that pdata = ( int * ) (uintptr_t) pfunc; leads to IB. This is because "Any pointer type may be converted to an integer type" and "An integer may be converted to any pointer type" and uintptr_t is integer type.

Body:
Given the definitions

int (*pfunc)();
int *pdata;

, the assignments

pdata = (int *)pfunc;
pdata = (int *)(uintptr_t)pfunc;

are, IMO, equivalent.  On a platform where data pointers are of the same size as, or larger than, function pointers, both assignments will work as desired.  But on a platform where data pointers are smaller than function pointers, both assignments will inevitably scrape off some of the bits of the function pointer, resulting in a data pointer which can not be converted back to the original function pointer later.

In particular, I believe that both assignments are equivalent despite the presence of the (uintptr_t) cast in the second one.  I believe that cast accomplishes precisely nothing.

On a platform where data pointers are smaller than function pointers, and where type uintptr_t is of the same size as data pointers, in the assignment

pdata = (int *)(uintptr_t)pfunc;

, the cast to (uintptr_t) will scrape off some of the bits of pfunc's value.

On a platform where data pointers are smaller than function pointers, and where type uintptr_t is of the same size as function pointers, in the assignment

pdata = (int *)(uintptr_t)pfunc;

, the cast to (int *) will scrape off some of the bits of pfunc's value.

In both cases pdata will end up with only some fraction of pfunc's original value.

(Here I disregard the possibility of architectures with padding bits or the like.  On some bizarre, hypothetical platform where function pointers are larger than data pointers, but the extra bits are always 0, both assignments would again work.)

(I've also disregarded the possibility that int * is a different size than void *.  I'm not sure whether that would affect the answer, whether a "detour" via void * is more or less un- or necessary when attempting a conversion from int (*)() to int *.)


问:
Save a PCL specific view as image
I am new to C++ and the use of the Pointcloud Library PCL (https://pointclouds.org/). At the moment I am able to generate a viewer of the point cloud by using the <pcl::visualization::PCLVisualizer> and I was wondering if it would be possible to save an image of the current viewer "view".

Imagine I have a picture like the following:

At the moment I just take a screenshot manually of what it looks like. However, since I will be processing many point clouds, I would like to have a way to convert this "viewer view" to an image.

答:
Of course I posted the question after researching online. However, I could not find the super easy solution available already in PCL.

You just need to use the function:

void pcl::visualization::PCLVisualizer::saveScreenshot (   const std::string &     file    )

Documentation here

I hope this will be helpful for someone else in the same situation.

Title: Save a PCL specific view as image


问:
VSCode `.devcontainer`: how to install personal packages with dotfiles?
I start diving deep in VSCode Remote-container with customization. I use a dotfiles repo to feel at home but my dotfiles (specially .zshrc) is packages (like: bat, exa, jq and more). I don't want to push it directly in the devcontainer because my other co-worker don't need them.

I try to do it in my dotfiles/install script using apt-get install -y jq but I receive and error:

```<code>E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
</code>```

I wonder what is the solution to customize the devcontainer without sharing these customization with my co-worker?

Thanks in advance

答:
It sounds like you may be using a non-root user in your container. If that is the case, you need to do two things:

Install the sudo package and give your user sudo privileges. The VSCode Dev Container docs explain how to do that. You'll need to add this to your Dockerfile:

```<code>ARG USERNAME=user-name-goes-here
ARG USER_UID=1000
ARG USER_GID=$USER_UID

# Create the user
RUN groupadd --gid $USER_GID $USERNAME \
    && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME \
    #
    # [Optional] Add sudo support. Omit if you don't need to install software after connecting.
    && apt-get update \
    && apt-get install -y sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
    && chmod 0440 /etc/sudoers.d/$USERNAME

# ********************************************************
# * Anything else you want to do like clean up goes here *
# ********************************************************

# [Optional] Set the default user. Omit if you want to keep the default as root.
USER $USERNAME
</code>```

Update your install script to use sudo:

```<code>sudo apt-get install -y jq
</code>```

Body:
I start diving deep in VSCode Remote-container with customization. I use a dotfiles repo to feel at home but my dotfiles (specially .zshrc) is packages (like: bat, exa, jq and more). I don't want to push it directly in the devcontainer because my other co-worker don't need them.

I try to do it in my dotfiles/install script using apt-get install -y jq but I receive and error:

E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?

I wonder what is the solution to customize the devcontainer without sharing these customization with my co-worker?

Thanks in advance

Body:
It sounds like you may be using a non-root user in your container. If that is the case, you need to do two things:

Install the sudo package and give your user sudo privileges. The VSCode Dev Container docs explain how to do that. You'll need to add this to your Dockerfile:

ARG USERNAME=user-name-goes-here
ARG USER_UID=1000
ARG USER_GID=$USER_UID

# Create the user
RUN groupadd --gid $USER_GID $USERNAME \
    && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME \
    #
    # [Optional] Add sudo support. Omit if you don't need to install software after connecting.
    && apt-get update \
    && apt-get install -y sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
    && chmod 0440 /etc/sudoers.d/$USERNAME

# ********************************************************
# * Anything else you want to do like clean up goes here *
# ********************************************************

# [Optional] Set the default user. Omit if you want to keep the default as root.
USER $USERNAME

Update your install script to use sudo:

sudo apt-get install -y jq


问:
WordPress 5.9 editor-style.css not working anymore and adds css properties that overrides block styling
I have a WP site with the Gutenberg editor styled (the place where you are writing the entry). It worked perfectly until this 5.9 update, where there have been added styles like these ones:

```<code>html :where(.editor-styles-wrapper) h1,
html :where(.editor-styles-wrapper) h2,
html :where(.editor-styles-wrapper) h3,
html :where(.editor-styles-wrapper) h4,
html :where(.editor-styles-wrapper) h5,
html :where(.editor-styles-wrapper) h6,
html :where(.editor-styles-wrapper) select {
    font-size: revert;
    margin: revert;
    color: revert;
    line-height: revert;
    font-weight: revert
}
</code>```

Is there any way to dequeue those styles? I don't want to dequeue all the editor-styles and calling 1 by 1 each needed style, I need a more scalable solution (because I would have to check if they added new css in every update).

I've noticed that this is not working anymore, maybe it's related:

```<code>add_theme_support('editor-styles');
add_editor_style( 'editor-style.css' );
</code>```

答:
In WordPress 5.9, many changes were introduced to how styling/theming is done including theme.json and block themes as part of Full Site Editing. Rather than trying to remove or dequeue the base Editor style defaults, I would try adapting what you have in your themes editor-style.css to support blocks and move towards theme.json gradually where you can.

For reference, the where:(.editor-styles-wrapper) is defined in the Block Library reset.scss and its stated that those rules are only needed when the block editor is not being loaded in an iframe.

Also, add_theme_support('editor-styles') and add_editor_style('editor-style.css' ) are still supported, its likely that your style being overriden by the Editors CSS reset.

Body:
I have a WP site with the Gutenberg editor styled (the place where you are writing the entry). It worked perfectly until this 5.9 update, where there have been added styles like these ones:

html :where(.editor-styles-wrapper) h1,
html :where(.editor-styles-wrapper) h2,
html :where(.editor-styles-wrapper) h3,
html :where(.editor-styles-wrapper) h4,
html :where(.editor-styles-wrapper) h5,
html :where(.editor-styles-wrapper) h6,
html :where(.editor-styles-wrapper) select {
    font-size: revert;
    margin: revert;
    color: revert;
    line-height: revert;
    font-weight: revert
}

Is there any way to dequeue those styles? I don't want to dequeue all the editor-styles and calling 1 by 1 each needed style, I need a more scalable solution (because I would have to check if they added new css in every update).

I've noticed that this is not working anymore, maybe it's related:

add_theme_support('editor-styles');
add_editor_style( 'editor-style.css' );


问:
is there an api for word meaning or dicitonary?
I have an app that checks the spelling entered by the user. What i am trying to do is when user corrects there spelling it shows them the complete meaning of the word. Is there any free api i can use to do this? With no limitations?

Also i tried finding a dictionary with meaning that i can upload to my server which will have over 200k words and all the meanings in it. But i am unable to find any. Have anyone here used a dictionary like this that you can refer me to?

I looked at this:

English dictionary SQL dump?
but these also dont have meanings with them

答: How about exporting the data from Wiktionary? You could write a script to automatically export the entries you need (maybe based on some wordlist). See http://en.wiktionary.org/wiki/Special:Export</p>


问:
Rearranging list with sublist
I'm a newbie to python and trying to figure this part out. I would like to rearrange this list with sublists from this:

```<code>holidays = [  ["Finland","Europe","12D9N Winter Wonderland Finland",4899],
["Switzerland","Europe", "11D8N Swiss Alps Ski Fun",3698],
["Germany","Europe", "11D8N German Beer and Food Feast",4697],
["Los Angeles (LA)","USA", "9D7N Disneyland Hollywood Fantasy",4799],
["Korea","Asia","8D7N Train to Busan",6789],
["Kuala Lumpur","Asia","4D3N Makan and Shopping Getaway",2899]
]
</code>```

to something like this:

```<code>holidays = [  ["Finland","Switzerland","Germany","Los Angeles (LA)","Korea","Kuala Lumpur",4899],
["Europe","Europe","Europe","USA","Asia","Asia", 3698],
["12D9N Winter Wonderland Finland","11D8N Swiss Alps Ski Fun","11D8N German Beer and Food Feast","9D7N Disneyland Hollywood Fantasy","8D7N Train to Busan","4D3N Makan and Shopping Getaway"],
[4697,4799,6789,2899]
]
</code>```

How should I do it? Please help! :X

答:
```<code>h = [[l[i] for l in holidays] for i in range(len(holidays[0]))]
</code>```

or

```<code>h = list(map(list, zip(*holidays)))
</code>```

Title: Rearranging list with sublist

Body:
I'm a newbie to python and trying to figure this part out. I would like to rearrange this list with sublists from this:

holidays = [  ["Finland","Europe","12D9N Winter Wonderland Finland",4899],
["Switzerland","Europe", "11D8N Swiss Alps Ski Fun",3698],
["Germany","Europe", "11D8N German Beer and Food Feast",4697],
["Los Angeles (LA)","USA", "9D7N Disneyland Hollywood Fantasy",4799],
["Korea","Asia","8D7N Train to Busan",6789],
["Kuala Lumpur","Asia","4D3N Makan and Shopping Getaway",2899]
]

to something like this:

holidays = [  ["Finland","Switzerland","Germany","Los Angeles (LA)","Korea","Kuala Lumpur",4899],
["Europe","Europe","Europe","USA","Asia","Asia", 3698],
["12D9N Winter Wonderland Finland","11D8N Swiss Alps Ski Fun","11D8N German Beer and Food Feast","9D7N Disneyland Hollywood Fantasy","8D7N Train to Busan","4D3N Makan and Shopping Getaway"],
[4697,4799,6789,2899]
]

How should I do it? Please help! :X

Body:
h = [[l[i] for l in holidays] for i in range(len(holidays[0]))]

or

h = list(map(list, zip(*holidays)))