问:
Transform only the last element of XML and copy the rest in XSLT
I have an XML like below -

```<code>   <root>
    <row>
     <col1>16</col1>
      <col2>466</col2>
        <col3>144922</col3>
        <col4>0</col4>
        <col5>5668</col5>
        <col6>475</col6>
    </row>
</root>
</code>```

The number of columns can vary inside the root element. It can also be up to col9. My requirement is to modify the last column and copy others as it is for an incoming XML.

I have something like this till now where I am assigning the value to used as the last element in a variable and then trying to call it when the last position is reached-

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"
    version="2.0">

    <xsl:param name="line88.field2" />
    <xsl:param name="rec16.col2" />

    <xsl:variable name="col3">
        <xsl:choose>
            <xsl:when test="$rec16.col2 ='165'">
                <xsl:value-of select="'Y'"/>
            </xsl:when>
            <xsl:when>
             ------
            <xsl:when>
        </xsl:choose>

    </xsl:variable>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"></xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="row[position() = last()]">
        <col9>
            <xsl:call-template name="AnotherTemplate">
                <xsl:with-param name="inputData">
                    <xsl:value-of select="$col3" />
                </xsl:with-param>
            </xsl:call-template>
        </col9>
    </xsl:template>
    <xsl:template name="AnotherTemplate">
        <xsl:param name="inputData"></xsl:param>
        <xsl:value-of select="$inputData" />
    </xsl:template>

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

But this is not working for me. Just giving me one column with the modified value.Please help.
The desired outcome should be as below where the last column has the value from the variable.

```<code><root>
<row>
        <col1>16</col1>
        <col2>466</col2>
        <col3>144922</col3>
        <col4>0</col4>
        <col5>5668</col5>
        <col6>Y</col6>
 </row>
</root>
</code>```

答:
Without knowing your whole XSLT code. You can use this row template:

```<code><xsl:template match="row/*[starts-with(local-name(),'col') and position() = last()]">
    <xsl:element name="{concat('col',position() div 2)}">
        <xsl:call-template name="AnotherTemplate">
            <xsl:with-param name="inputData">
                <xsl:value-of select="$col3" />
            </xsl:with-param>
        </xsl:call-template>
    </xsl:element>
</xsl:template>
</code>```

It replaces the last col? element by the given value (the result of the xsl:call-template code).

Body:
I have an XML like below -

   <root>
    <row>
     <col1>16</col1>
      <col2>466</col2>
        <col3>144922</col3>
        <col4>0</col4>
        <col5>5668</col5>
        <col6>475</col6>
    </row>
</root>

The number of columns can vary inside the root element. It can also be up to col9. My requirement is to modify the last column and copy others as it is for an incoming XML.

I have something like this till now where I am assigning the value to used as the last element in a variable and then trying to call it when the last position is reached-

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"
    version="2.0">

    <xsl:param name="line88.field2" />
    <xsl:param name="rec16.col2" />

    <xsl:variable name="col3">
        <xsl:choose>
            <xsl:when test="$rec16.col2 ='165'">
                <xsl:value-of select="'Y'"/>
            </xsl:when>
            <xsl:when>
             ------
            <xsl:when>
        </xsl:choose>

    </xsl:variable>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"></xsl:apply-templates>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="row[position() = last()]">
        <col9>
            <xsl:call-template name="AnotherTemplate">
                <xsl:with-param name="inputData">
                    <xsl:value-of select="$col3" />
                </xsl:with-param>
            </xsl:call-template>
        </col9>
    </xsl:template>
    <xsl:template name="AnotherTemplate">
        <xsl:param name="inputData"></xsl:param>
        <xsl:value-of select="$inputData" />
    </xsl:template>

</xsl:stylesheet>

But this is not working for me. Just giving me one column with the modified value.Please help.
The desired outcome should be as below where the last column has the value from the variable.

<root>
<row>
        <col1>16</col1>
        <col2>466</col2>
        <col3>144922</col3>
        <col4>0</col4>
        <col5>5668</col5>
        <col6>Y</col6>
 </row>
</root>

Body:
Without knowing your whole XSLT code. You can use this row template:

<xsl:template match="row/*[starts-with(local-name(),'col') and position() = last()]">
    <xsl:element name="{concat('col',position() div 2)}">
        <xsl:call-template name="AnotherTemplate">
            <xsl:with-param name="inputData">
                <xsl:value-of select="$col3" />
            </xsl:with-param>
        </xsl:call-template>
    </xsl:element>
</xsl:template>

It replaces the last col? element by the given value (the result of the xsl:call-template code).


来源: stackexchange

问:
Is it safe to inject an EJB into a servlet as an instance variable?
We all know that in the web tier there is the possibility that only a single instance of a given Servlet exists which services multiple requests. This can lead to threading issues in instance variables.

My question is, is it safe to inject an EJB using the @EJB annotation into a servlet as an instance variable?

My initial instinct would be no, under the assumption that the same instance of the EJB would service multiple requests at the same time. It would seem that this would also be the instinct of a number of other programmers: Don't inject to servlets

However have I jumped to the wrong conclusion. Clearly what is injected into the servlet is a proxy, under the hood does the container actually service each request with a different instance and maintain thread safety? As this forum would suggest: Do inject to servlets

There seems to be a lot of conflicting opinions. WHICH IS CORRECT???

答:
Your reference "Don't inject to servlets" mentions nothing about ejbs or @ejb annotation. It talks about not thread safe objects such as PersistenceContext.

Per EJB spec you can access ejbs from variety of remote clients including servlets (EJB 3.0 Specification (JSR-220) - Section 3.1). Injecting ejb using @EJB annotation is a method of obtaining EJB interface via dependency injection (section 3.4.1) which is alternative to looking up ejb objects in the JNDI namespace. So there is nothing special about @EJB annotation with respect to EJBs obtained.

So, based on EJB 3.0 Spec, it's a standard practice to obtain ejbs from servlets using @EJB annotation.

OwnerDisplayName: montyontherun

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: grigory


问:
Is un-initialized integer always default to 0 in c?
I'm reading source code of nginx and find it's not initializing many of the numerical variables, including ngx_int_t ngx_last_process;,here ngx_int_t defined as long int

```<code>#if 0
    ngx_last_process = 0;
#endif
</code>```

So here @Igor Sysoev think it unnecessary to do the initialization?

But in the programe it's assuming the default value is 0:

```<code>    for (s = 0; s < ngx_last_process; s++) {
        if (ngx_processes[s].pid == -1) {
            break;
        }
    }
</code>```

Is it guranteed that un-initialized variable will have 0 value in c at all?

答:
automatic (local) variables are not guaranteed to be zero, can contain garbage.

global variables and static variables are guaranteed to be zero.

ContentLicense: CC BY-SA 3.0

Body:
I'm reading source code of nginx and find it's not initializing many of the numerical variables, including ngx_int_t ngx_last_process;,here ngx_int_t defined as long int

#if 0
    ngx_last_process = 0;
#endif

So here @Igor Sysoev think it unnecessary to do the initialization?

But in the programe it's assuming the default value is 0:

    for (s = 0; s < ngx_last_process; s++) {
        if (ngx_processes[s].pid == -1) {
            break;
        }
    }

Is it guranteed that un-initialized variable will have 0 value in c at all?


问:
Represent file structure to JSON
I want to represent current files structure in JSON or XML code but with some conditions.

I want to my representation to not mention middle empty directories.

I want to only list files ended with Activity.*

For example:
for this structure

```<code>my_project
├── feature1
│   └── src
│       └── java
│           └── com
│               └── directory
│                   ├── MainActivity.kt
│                   └── MainFragment.kt
└── feature2
    └── src
        └── java
            └── com
                └── directory
                    ├── Feature2Activity.kt
                    └── Feature2Fragment.kt
</code>```

Should generate

```<code>{
  "my_project": {
    "feature1": {
      "directory": ["MainActivity"]
    },
    "feature2": {
      "directory": ["Feature2Activity"]
    }
  }
}
</code>```

It doesn't matter if I can't do this at runtime, think of it as a script that I will use on directory. Not at runtime of the App.

答:
The source files are compiled into JVM bytecode and then they are compiled into the Dex (Dalvik Executable) that can run on the Android platform.

You can use the Dex file of your application that can be accessed by the context.

val activityFiles = mutableListOf<String>()

DexFile(context.getPackageCodePath()).entries().apply {
    while(hasMoreElement()) {
        val fileName = nextElement.substringAfterLast('.').substringBefore('$')
        if(fileName.contains("Activity")) activityFiles.add(fileName)
    }
}

// Logic to generate Json. You may use any json library.
val innerJson = mutableMapOf(
    getAppName() to mapOf(
        "directory" to activityFiles
    )
)

// Hard-code the parent project name (holding both sub application)
val jsonRepresentation: MutableMap<String, Any> = mutableMapOf("my_project" to innerJson)

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

val json = moshi.adapter(Map::class.java).toJson(jsonRepresentation)

fun getAppName(ctx: Context) {
    val appInfo = context.getApplicationInfo()
    val id = appInfo.labelRes
    return if (id == 0) applicationInfo.nonLocalizedLabel.toString()
    else context.getString(id)
}
```

I wonder if there it is possible to have feature1 info and feature2 both, as you will be having context of that specified application. If you are writing code in feature1 then won't be able to see classes / app name of the other feature2.

References

https://developer.android.com/reference/kotlin/dalvik/system/DexFile#entries()

Is there a way to get a list of all classes from a .dex file?

Find all classes in a package in Android

Android - How to get application name? (Not package name)

ContentLicense: CC BY-SA 4.0

Title: Represent file structure to JSON

Body:
I want to represent current files structure in JSON or XML code but with some conditions.

I want to my representation to not mention middle empty directories.

I want to only list files ended with Activity.*

For example:
for this structure

my_project
├── feature1
│   └── src
│       └── java
│           └── com
│               └── directory
│                   ├── MainActivity.kt
│                   └── MainFragment.kt
└── feature2
    └── src
        └── java
            └── com
                └── directory
                    ├── Feature2Activity.kt
                    └── Feature2Fragment.kt

Should generate

{
  "my_project": {
    "feature1": {
      "directory": ["MainActivity"]
    },
    "feature2": {
      "directory": ["Feature2Activity"]
    }
  }
}

It doesn't matter if I can't do this at runtime, think of it as a script that I will use on directory. Not at runtime of the App.

Body:
The source files are compiled into JVM bytecode and then they are compiled into the Dex (Dalvik Executable) that can run on the Android platform.

You can use the Dex file of your application that can be accessed by the context.

val activityFiles = mutableListOf<String>()

DexFile(context.getPackageCodePath()).entries().apply {
    while(hasMoreElement()) {
        val fileName = nextElement.substringAfterLast('.').substringBefore('$')
        if(fileName.contains("Activity")) activityFiles.add(fileName)
    }
}

// Logic to generate Json. You may use any json library.
val innerJson = mutableMapOf(
    getAppName() to mapOf(
        "directory" to activityFiles
    )
)

// Hard-code the parent project name (holding both sub application)
val jsonRepresentation: MutableMap<String, Any> = mutableMapOf("my_project" to innerJson)

val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

val json = moshi.adapter(Map::class.java).toJson(jsonRepresentation)

fun getAppName(ctx: Context) {
    val appInfo = context.getApplicationInfo()
    val id = appInfo.labelRes
    return if (id == 0) applicationInfo.nonLocalizedLabel.toString()
    else context.getString(id)
}

I wonder if there it is possible to have feature1 info and feature2 both, as you will be having context of that specified application. If you are writing code in feature1 then won't be able to see classes / app name of the other feature2.

References

https://developer.android.com/reference/kotlin/dalvik/system/DexFile#entries()

Is there a way to get a list of all classes from a .dex file?

Find all classes in a package in Android

Android - How to get application name? (Not package name)


问:
Mysql - Specified Key is too long, max key length is 1024 bytes despite encoding type being latin1 and index contains 2 column(512 each)

Getting the following error on update with join :

Mysql - Specified Key is too long, max key length is 1024 bytes despite encoding type being latin1 and index contains 2 varchar columns(512 each)

Mysql version - 5.7.29

Details :

There are 3 columns: abc, pk1, pk2

DataTypes of columns :

abc - json

pk1 - varchar(512)

pk2 - varchar(512)

There is one composite key => (pk1, pk2)

This gives me Specified Key is too long, max key length is 1024 bytes despite encoding type being latin1.

If I change datatype for abc to varchar(512), I don't encounter this error.

Any idea on why this would happen, as abc is not a part of the composite key.

Please visit the fiddle link - https://www.db-fiddle.com/f/wB7Ee9Rz8nLS3KEKU59WPf/3 to find the issue

Sample code to reproduce the issue:

```<code>create table test (abc json default null, pk1 varchar(512) not null, pk2 varchar(512) not null, primary key (pk1, pk2), xyz int(11)) CHARACTER SET = latin1;
create table temp (abc json, pk1 varchar(512) not null, pk2 varchar(512) not null,  xyz int(11)) CHARACTER SET = latin1;

explain UPDATE `test` T1  INNER JOIN `temp` T2 ON T1.`pk1` = T2.`pk1` AND T1.`pk2` = T2.`pk2` SET T1.`abc` = T2.`abc`

  [1]: https://www.db-fiddle.com/f/wB7Ee9Rz8nLS3KEKU59WPf/3
</code>```

答:
Everything works OK while typing with accuracy.

fiddle

Search for wrong char (maybe national?).

You have changed the query to do set t1.xyz = t2.xyz, it causes a problem when it's t1.abc = t2.abc since abc is of type json => db-fiddle.com/f/wB7Ee9Rz8nLS3KEKU59WPf/6

This looks like join buffer oversize or something similar.

See fiddle. Replacing t1.field=t2.field with TRIM(t1.field)=TRIM(t2.field) removes the error.

Testing on the values which have 512 chars length (using values like REPEAT('a', 512)) shows that the query is executed without error...

Body:
Getting the following error on update with join :

Mysql - Specified Key is too long, max key length is 1024 bytes despite encoding type being latin1 and index contains 2 varchar columns(512 each)

Mysql version - 5.7.29

Details :

There are 3 columns: abc, pk1, pk2

DataTypes of columns :

abc - json

pk1 - varchar(512)

pk2 - varchar(512)

There is one composite key => (pk1, pk2)

This gives me Specified Key is too long, max key length is 1024 bytes despite encoding type being latin1.

If I change datatype for abc to varchar(512), I don't encounter this error.

Any idea on why this would happen, as abc is not a part of the composite key.

Please visit the fiddle link - https://www.db-fiddle.com/f/wB7Ee9Rz8nLS3KEKU59WPf/3 to find the issue

Sample code to reproduce the issue:

create table test (abc json default null, pk1 varchar(512) not null, pk2 varchar(512) not null, primary key (pk1, pk2), xyz int(11)) CHARACTER SET = latin1;
create table temp (abc json, pk1 varchar(512) not null, pk2 varchar(512) not null,  xyz int(11)) CHARACTER SET = latin1;

explain UPDATE `test` T1  INNER JOIN `temp` T2 ON T1.`pk1` = T2.`pk1` AND T1.`pk2` = T2.`pk2` SET T1.`abc` = T2.`abc`

  [1]: https://www.db-fiddle.com/f/wB7Ee9Rz8nLS3KEKU59WPf/3


问:
regex for group of square brackets and comma javascript
I'm trying to construct a regular expression which I can use to replace all instances of "],[" with just "," in a string.

I'm stuck on this.

I've been through a number of different combinations - currently trying:

```<code>str.replace(/(\[,\])/, ',');
</code>```

But it's not picking it up and I can't see what's wrong with it - anything obvious I'm doing wrong here?

Thanks

答:
You are using the brackets in wrong order and you need to match multiple occurrences with the g flag.

So you may use

```<code>text = text.replace(/],\[/g, ',')
</code>```

Or, if you want to use a capturing group,

```<code>text = text.replace(/](,)\[/g, '$1')
</code>```

See regex demo #1 and regex demo #2.

NOTE: If there may be any amount of whitespace between the brackets, use \s* to match it, e.g. text = text.replace(/]\s*,\s*\[/g, ',').

JS demo:

var text = "text],[text2],[text3";
console.log(text.replace(/],\[/g, ','));
console.log(text.replace(/](,)\[/g, '$1'));```

Body:
I'm trying to construct a regular expression which I can use to replace all instances of "],[" with just "," in a string.

I'm stuck on this.

I've been through a number of different combinations - currently trying:

str.replace(/(\[,\])/, ',');

But it's not picking it up and I can't see what's wrong with it - anything obvious I'm doing wrong here?

Thanks

Body:
You are using the brackets in wrong order and you need to match multiple occurrences with the g flag.

So you may use

text = text.replace(/],\[/g, ',')

Or, if you want to use a capturing group,

text = text.replace(/](,)\[/g, '$1')

See regex demo #1 and regex demo #2.

NOTE: If there may be any amount of whitespace between the brackets, use \s* to match it, e.g. text = text.replace(/]\s*,\s*\[/g, ',').

JS demo:

var text = "text],[text2],[text3";
console.log(text.replace(/],\[/g, ','));
console.log(text.replace(/](,)\[/g, '$1'));


问:
Silverlight Unit Testing, Dealing with Async calls in nested methods
When creating Unit Tests for silverlight the test framework seems to have features build in to help with Async calls but only within the test method. What if in a child method of the one you are calling there is an Async call.

As an example we use Specflow to test our ViewModels, We want to call the Execute method of a command and that command then asynchronously calls a web service. How can i ensure the while command is completed before asserting the results?

as an example this is the command

```<code>    [Asynchronous]
    [When(@"I press calculate")]
    public void WhenIPressCalculate()
    {
        _helloWorldViewModel.CalculateCommand.Execute(null);
    }
</code>```

I need to wait for the entire command to complete before continuing.

答:
A loop does not work when making a call to a network service because the callback is marshalled to the UI Thread, if it is looping for a condition it creates a deadlock as the call back is waiting for the thread to finish.

Anyway we soted this problem out. turns out the specflow guys were working on this at the same time and have a solution in progress. We got it working with a pre release build.

I wrote a blog entry about it here http://rburnham.wordpress.com/2011/05/13/testing-silverlight-asynchronous-code-with-specflow/

this may change as this was done with a pre release build, hopefully I'll get time to update it if it does.

Body:
When creating Unit Tests for silverlight the test framework seems to have features build in to help with Async calls but only within the test method. What if in a child method of the one you are calling there is an Async call.

As an example we use Specflow to test our ViewModels, We want to call the Execute method of a command and that command then asynchronously calls a web service. How can i ensure the while command is completed before asserting the results?

as an example this is the command

    [Asynchronous]
    [When(@"I press calculate")]
    public void WhenIPressCalculate()
    {
        _helloWorldViewModel.CalculateCommand.Execute(null);
    }

I need to wait for the entire command to complete before continuing.


问:
Making a Azure WebJob run a console application
I'm trying to setup a scheduled WebJob (every minute). I've made a Windows Console Application in VS 2019 like this:

```<code>using System;
using System.Net;

namespace EveryMinute
{
    class Program
    {
        static void Main(string[] args)
        {
            WebRequest request = WebRequest.Create("https://some.url.com");
            WebResponse response = request.GetResponse();
        }
    }
}
</code>```

The output of this request is not important, I just need the url to be triggered every minute.
I can run the exe on my Windows computer. But when I create a WebJob with this exe attached, I keep getting a [failed] notice every minute.

Can anyone tell me what I am doing wrong?

Thank you for your help.

答:
To make the answer visible to others, I'm summarizing the answer as below:

I don't know if I can send that dll together with other files in the
  zip?

Yes, we need to add all the contents under Bin/Debug(/net472) path in a .zip file.

We can also deploy the webjob in vs by clicking publish button.

If your job fails, you can find the detailed error message in the Run Details.

Body:
I'm trying to setup a scheduled WebJob (every minute). I've made a Windows Console Application in VS 2019 like this:

using System;
using System.Net;

namespace EveryMinute
{
    class Program
    {
        static void Main(string[] args)
        {
            WebRequest request = WebRequest.Create("https://some.url.com");
            WebResponse response = request.GetResponse();
        }
    }
}

The output of this request is not important, I just need the url to be triggered every minute.
I can run the exe on my Windows computer. But when I create a WebJob with this exe attached, I keep getting a [failed] notice every minute.

Can anyone tell me what I am doing wrong?

Thank you for your help.


问:
Scrape YouTube Videos with Python and Selenium
I want to Scrape all Videos from 'TVFilthyFrank' for a friend. I have all links to every video of him.
I want to measure the size in MB for all videos now and download them.
I know I can just say driver.get(VIDEO_URL) and then just get the src out of the player but that would take very long and wouldt look nice.
Is there anyway to get the video src (or at least some information to the vid) out of the video link ?

答:
You should try youtube-dl: https://github.com/ytdl-org/youtube-dl. It can be used in python code as modude and in shell.

To download all videos from channel TVFilthyFrank you can use youtube-dl -f bestvideo+bestaudio --write-info-json https://www.youtube.com/user/TVFilthyFrank (-f bestvideo+bestaudio means the best quality). --write-info-json means save metadata to json file.


问:
ElasticSearch Sorting using NEST 7
I'm using ElarsticSearch 7.7 & NEST 7.7 and I'm trying to use the sort function. But I'm getting an error,

I'm getting an error saying,
"Type: illegal_argument_exception Reason: "Text fields are not optimized for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted index. Note that this can use significant memory." caused by: "Type: illegal_argument_exception Reason: "Text fields are not optimized for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted

this is my code below

```<code>public SearchResult Search(string searchQuery, int storeId, int pageNumber = 1, int pageSize = 10, IList<SearchFilter> requestFilter = null, decimal? priceFrom = null, decimal? priceTo = null, string sortBy = null)
    {
        var queryContainer = new QueryContainer();
        var multiMatch = new QueryStringQuery
        {
            Fields = Infer.Field<ElasticIndexGroupProduct>(p => p.Name)
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.CategoryName))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.VendorName))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.Name)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.CategoryName)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.ManufacturerName)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.ShortDescription))),
            Boost = 1.1,
            Name = "named_query",
            Query = searchQuery,
            DefaultOperator = Operator.Or,
            Analyzer = "standard",
            QuoteAnalyzer = "keyword",
            AllowLeadingWildcard = true,
            MaximumDeterminizedStates = 2,
            Escape = true,
            FuzzyPrefixLength = 2,
            FuzzyMaxExpansions = 3,
            FuzzyRewrite = MultiTermQueryRewrite.ConstantScore,
            Rewrite = MultiTermQueryRewrite.ConstantScore,
            Fuzziness = Fuzziness.Auto,
            TieBreaker = 1,
            AnalyzeWildcard = true,
            MinimumShouldMatch = 2,
            QuoteFieldSuffix = "'",
            Lenient = true,
            AutoGenerateSynonymsPhraseQuery = false
        };
        queryContainer &= multiMatch;

        //sorting
        var sorts = new List<ISort>();
        switch (sortBy)
        {
            case "z-a":
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.Name), Order = SortOrder.Descending });
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x=>x.Name)), Order = SortOrder.Descending });
                break;
            default:
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.Name), Order = SortOrder.Ascending });
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.Name)), Order = SortOrder.Ascending });
                break;
        }

       var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
        {
            Profile = true,
            Query = queryContainer,
            From = (pageNumber - 1) * pageSize,
            Size = pageSize,
            Version = true,
            Sort = sorts
        };

        var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);
        return GenerateSearchResult(searchQuery, searchResponse);
    }
</code>```

this is the error

答:
Found a solution. Need to set fielddata=true on [Keywords] in order to load fielddata in memory by uninverting the inverted index.</p>

```<code>[ElasticsearchType(RelationName = "searchproduct")]
    public class ElasticIndexGroupProduct
    {
        [Text(Fielddata = true)]
        public string Name { get; set; }
    }
</code>```

Title: ElasticSearch Sorting using NEST 7

Body:
I'm using ElarsticSearch 7.7 & NEST 7.7 and I'm trying to use the sort function. But I'm getting an error,

I'm getting an error saying,
"Type: illegal_argument_exception Reason: "Text fields are not optimized for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted index. Note that this can use significant memory." caused by: "Type: illegal_argument_exception Reason: "Text fields are not optimized for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted

this is my code below

public SearchResult Search(string searchQuery, int storeId, int pageNumber = 1, int pageSize = 10, IList<SearchFilter> requestFilter = null, decimal? priceFrom = null, decimal? priceTo = null, string sortBy = null)
    {
        var queryContainer = new QueryContainer();
        var multiMatch = new QueryStringQuery
        {
            Fields = Infer.Field<ElasticIndexGroupProduct>(p => p.Name)
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.CategoryName))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.VendorName))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.Name)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.CategoryName)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.ManufacturerName)))
                     .And(Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.ShortDescription))),
            Boost = 1.1,
            Name = "named_query",
            Query = searchQuery,
            DefaultOperator = Operator.Or,
            Analyzer = "standard",
            QuoteAnalyzer = "keyword",
            AllowLeadingWildcard = true,
            MaximumDeterminizedStates = 2,
            Escape = true,
            FuzzyPrefixLength = 2,
            FuzzyMaxExpansions = 3,
            FuzzyRewrite = MultiTermQueryRewrite.ConstantScore,
            Rewrite = MultiTermQueryRewrite.ConstantScore,
            Fuzziness = Fuzziness.Auto,
            TieBreaker = 1,
            AnalyzeWildcard = true,
            MinimumShouldMatch = 2,
            QuoteFieldSuffix = "'",
            Lenient = true,
            AutoGenerateSynonymsPhraseQuery = false
        };
        queryContainer &= multiMatch;

        //sorting
        var sorts = new List<ISort>();
        switch (sortBy)
        {
            case "z-a":
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.Name), Order = SortOrder.Descending });
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x=>x.Name)), Order = SortOrder.Descending });
                break;
            default:
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.Name), Order = SortOrder.Ascending });
                sorts.Add(new FieldSort { Field = Infer.Field<ElasticIndexGroupProduct>(p => p.AssociatedProducts.Select(x => x.Name)), Order = SortOrder.Ascending });
                break;
        }

       var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
        {
            Profile = true,
            Query = queryContainer,
            From = (pageNumber - 1) * pageSize,
            Size = pageSize,
            Version = true,
            Sort = sorts
        };

        var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);
        return GenerateSearchResult(searchQuery, searchResponse);
    }

this is the error

Body:
Found a solution. Need to set fielddata=true on [Keywords] in order to load fielddata in memory by uninverting the inverted index.

[ElasticsearchType(RelationName = "searchproduct")]
    public class ElasticIndexGroupProduct
    {
        [Text(Fielddata = true)]
        public string Name { get; set; }
    }


问:
Display a neat set of files in my application
I have a set of files written to a temporary directory which I want to display to the user. In this instance I wish them to be able to select a file and then have the option of saving it. Is there a decent control in C# for doing this?</p>

答: Would a simple Open File Dialog be sufficent? You can restrict it to only show the files with your temporary extension. OpenFileDialog in C# gives some examples of use.


问:
How to check the installed version of React-Native
I'm going to upgrade react-native but before I do, I need to know which version I'm upgrading from to see if there are any special notes about upgrading from my version.

How do I find the version of react-native I have installed on my Mac?

答:
react-native
Usage: bin  [options]

Options:
  --version                     Print CLI version
  --verbose                     Increase logging verbosity
  -h, --help                    output usage information
react-native --version use this command


问:
Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware with redux tool
Can someone help with this,

Error: Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware

Mounted sagaMiddleware still it throw an error on the page

Added redux-saga to Store with saga Middleware

Store Js

```<code>import { createStore, applyMiddleware, compose } from "redux";
import { persistStore } from "redux-persist";
import createSagaMiddleware from 'redux-saga'
import {fetchCollectionsStart} from './shop/shop.sagas'
import logger from "redux-logger";
import rootReducer from "./root-reducer";

const sagaMiddleware = createSagaMiddleware();

const middlewares = [sagaMiddleware];

if (process.env.NODE_ENV === "development") {
  middlewares.push(logger);
}
const composeEnhancers =
  typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
        // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
      })
    : compose;

const enhancer = composeEnhancers(
  applyMiddleware(...middlewares,sagaMiddleware)
  // other store enhancers if any
);

sagaMiddleware.run(fetchCollectionsStart);

export const store = createStore(rootReducer, enhancer);
export const persistor = persistStore(store);
</code>```

Created this saga to fetch the collections once the component is mounted

Sagas.js

```<code>import {takeEvery} from 'redux-saga/effects';
import ShopActionTypes from './shop.types';

export function* fetchCollectionsAsync(){
    yield console.log('Good');
}
export function* fetchCollectionsStart(){
    yield takeEvery(ShopActionTypes.FETCH_COLLECTIONS_START,
        fetchCollectionsAsync );
}
</code>```

答:
Make sure you run sagaMiddleware.run(fetchCollectionsStart); after createStore

const { useState, useEffect } = React;
const { bindActionCreators, combineReducers, createStore, applyMiddleware, compose } = Redux;
const { connect, Provider } = ReactRedux;
const createSagaMiddleware = ReduxSaga.default;
const { takeEvery } = ReduxSagaEffects;
const sagaMiddleware = createSagaMiddleware();
const reducer = (state = {}, action) => {
  return state;
}

const enhancer = compose(
  applyMiddleware(sagaMiddleware)
);

const reducers = combineReducers({
  reducer
})

const store = createStore(
  reducers,
  enhancer
);

function* fetchCollectionsAsync(){
    yield console.log('Good');
}

function* fetchCollectionsStart(){
    yield takeEvery('FETCH_COLLECTIONS_START',
        fetchCollectionsAsync );
}

sagaMiddleware.run(fetchCollectionsStart);

const action = () => ({
  type: 'FETCH_COLLECTIONS_START'
})

const mapStateToProps = state => ({

})

const mapDispatchToProps = ({
  action
})

const _App = ({action}) => {
  useEffect(() => {
    action();
  }, [])

  return

}

const App = connect(mapStateToProps, mapDispatchToProps)(_App)

ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById('root')
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.10.1/polyfill.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/redux@4.0.5/dist/redux.js"></script>
<script src="https://unpkg.com/react-redux@latest/dist/react-redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-saga/1.1.3/redux-saga.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-saga/1.1.3/redux-saga-effects.umd.js"></script>
<div id="root"></div></code>```

Body:
Can someone help with this,

Error: Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware

Mounted sagaMiddleware still it throw an error on the page

Added redux-saga to Store with saga Middleware

Store Js

import { createStore, applyMiddleware, compose } from "redux";
import { persistStore } from "redux-persist";
import createSagaMiddleware from 'redux-saga'
import {fetchCollectionsStart} from './shop/shop.sagas'
import logger from "redux-logger";
import rootReducer from "./root-reducer";

const sagaMiddleware = createSagaMiddleware();

const middlewares = [sagaMiddleware];

if (process.env.NODE_ENV === "development") {
  middlewares.push(logger);
}
const composeEnhancers =
  typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
        // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
      })
    : compose;

const enhancer = composeEnhancers(
  applyMiddleware(...middlewares,sagaMiddleware)
  // other store enhancers if any
);

sagaMiddleware.run(fetchCollectionsStart);

export const store = createStore(rootReducer, enhancer);
export const persistor = persistStore(store);

Created this saga to fetch the collections once the component is mounted

Sagas.js

import {takeEvery} from 'redux-saga/effects';
import ShopActionTypes from './shop.types';

export function* fetchCollectionsAsync(){
    yield console.log('Good');
}
export function* fetchCollectionsStart(){
    yield takeEvery(ShopActionTypes.FETCH_COLLECTIONS_START,
        fetchCollectionsAsync );
}

Body:
Make sure you run sagaMiddleware.run(fetchCollectionsStart); after createStore

const { useState, useEffect } = React;
const { bindActionCreators, combineReducers, createStore, applyMiddleware, compose } = Redux;
const { connect, Provider } = ReactRedux;
const createSagaMiddleware = ReduxSaga.default;
const { takeEvery } = ReduxSagaEffects;
const sagaMiddleware = createSagaMiddleware();
const reducer = (state = {}, action) => {
  return state;
}

const enhancer = compose(
  applyMiddleware(sagaMiddleware)
);

const reducers = combineReducers({
  reducer
})

const store = createStore(
  reducers,
  enhancer
);

function* fetchCollectionsAsync(){
    yield console.log('Good');
}

function* fetchCollectionsStart(){
    yield takeEvery('FETCH_COLLECTIONS_START',
        fetchCollectionsAsync );
}

sagaMiddleware.run(fetchCollectionsStart);

const action = () => ({
  type: 'FETCH_COLLECTIONS_START'
})

const mapStateToProps = state => ({

})

const mapDispatchToProps = ({
  action
})

const _App = ({action}) => {
  useEffect(() => {
    action();
  }, [])

  return <div>
  </div>
}

const App = connect(mapStateToProps, mapDispatchToProps)(_App)

ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById('root')
  );

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/7.10.1/polyfill.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/redux@4.0.5/dist/redux.js"></script>
<script src="https://unpkg.com/react-redux@latest/dist/react-redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-saga/1.1.3/redux-saga.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-saga/1.1.3/redux-saga-effects.umd.js"></script>
<div id="root"></div>


问:
cURL error 60: SSL certificate problem: certificate has expired
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

```<code>cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
</code>```

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1
</code>```

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.
</code>```

My curl code -

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
</code>```

答:
We have the same error. For solving your issue update your "SSLCertificateChainFile" with the newest version of your trusted SSL site. In our case is comodo.

You need to go to your trusted site and find under your certificates the "CA-CRT". Copy the content.

Go to your /etc/apache2/sites-available

Find the line wih "SSLCertificateChainFile".

Next edit the file and replace the content with your new CA-CRT values.

Then restart your web server, in our case is apache:
  service apache2 restart
   or
  systemctl restart apache2

If you can't restart apache the easy way is reboot your instance.

Body:
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.

My curl code -

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);


问:
How to print the values of slices
I want to see the values which are in the slice. How can I print them?</p>

```<code>projects []Project
</code>```

答:
I wrote a package named Pretty Slice. You can use it to visualize slices, and their backing arrays, etc.

package main

import pretty "github.com/inancgumus/prettyslice"

func main() {
    nums := []int{1, 9, 5, 6, 4, 8}
    odds := nums[:3]
    evens := nums[3:]

    nums[1], nums[3] = 9, 6
    pretty.Show("nums", nums)
    pretty.Show("odds : nums[:3]", odds)
    pretty.Show("evens: nums[3:]", evens)
}
```

This code is going produce and output like this one:

For more details, please read: https://github.com/inancgumus/prettyslice

Title: How to print the values of slices

Body:
I want to see the values which are in the slice. How can I print them?

projects []Project

Body:
I wrote a package named Pretty Slice. You can use it to visualize slices, and their backing arrays, etc.

package main

import pretty "github.com/inancgumus/prettyslice"

func main() {
    nums := []int{1, 9, 5, 6, 4, 8}
    odds := nums[:3]
    evens := nums[3:]

    nums[1], nums[3] = 9, 6
    pretty.Show("nums", nums)
    pretty.Show("odds : nums[:3]", odds)
    pretty.Show("evens: nums[3:]", evens)
}

This code is going produce and output like this one:

For more details, please read: https://github.com/inancgumus/prettyslice


问:
How can I plot random pixels in real time in Python?
I'm almost a beginner in Python even though I did Computer Sciences.

I'd like to do several projects with real-time Python plotting.

My start is to display an image with random pixels constantly changing.
I tried Python interactive mode, and loops, but I can't figure it out.

Here is the code to show random pixels :

```<code>import matplotlib
from numpy import random

Z = random.random((50,50))   # Test data
imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
fig.show()
</code>```

What would be an easy way to replace all pixels with new random ones each frame ? (Like a TV noise)
Thanks for help !

答:
If you want to show a plot between making changes you can use plt.pause(time_in_s):

```<code>import matplotlib.pyplot as plt
import matplotlib.cm as cm
from numpy import random

for i in range(20):
    Z = random.random((50,50))   # Test data
    plt.imshow(Z, cm.get_cmap("Spectral"), interpolation='nearest')
    plt.show()
    plt.pause(0.01)
</code>```

For more complex animations, see https://matplotlib.org/api/animation_api.html#module-matplotlib.animation
or
https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

Body:
I'm almost a beginner in Python even though I did Computer Sciences.

I'd like to do several projects with real-time Python plotting.

My start is to display an image with random pixels constantly changing.
I tried Python interactive mode, and loops, but I can't figure it out.

Here is the code to show random pixels :

import matplotlib
from numpy import random

Z = random.random((50,50))   # Test data
imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
fig.show()

What would be an easy way to replace all pixels with new random ones each frame ? (Like a TV noise)
Thanks for help !

Body:
If you want to show a plot between making changes you can use plt.pause(time_in_s):

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from numpy import random

for i in range(20):
    Z = random.random((50,50))   # Test data
    plt.imshow(Z, cm.get_cmap("Spectral"), interpolation='nearest')
    plt.show()
    plt.pause(0.01)

For more complex animations, see https://matplotlib.org/api/animation_api.html#module-matplotlib.animation
or
https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/


问:
Changing interpreter bash script
Is there any way for changing the interpreter in the middle of a bash script

For instance start with:

```<code>#!/bin/bash
</code>```

Later change to:

```<code>#!$drush_location
</code>```

The reason is because I want to use bash to resolve the location of drush using bash and then pass that var in as an interpreter

答:
You will need to write two scripts and use the first (bash) one to launch the second (drush).

There are other ways to accomplish this, but they are all basically fancy ways of doing the above. For example you could use a here-doc to cram a script contained as a string in your first script into stdin on drush and have it execute that, or even write a temporary file and execute that as a script, but you have to run two processes somehow, you can't change the interpreter on the fly.

Really the thing to do would be to fix your environment so that it can find drush. Then you can use:

```<code>#!/usr/bin/env drush
</code>```

As the hashbang for your drush script. If your system evn can't find it, then fix your search paths until it can!

Title: Changing interpreter bash script

Body:
Is there any way for changing the interpreter in the middle of a bash script

For instance start with:

#!/bin/bash

Later change to:

#!$drush_location

The reason is because I want to use bash to resolve the location of drush using bash and then pass that var in as an interpreter

Body:
You will need to write two scripts and use the first (bash) one to launch the second (drush).

There are other ways to accomplish this, but they are all basically fancy ways of doing the above. For example you could use a here-doc to cram a script contained as a string in your first script into stdin on drush and have it execute that, or even write a temporary file and execute that as a script, but you have to run two processes somehow, you can't change the interpreter on the fly.

Really the thing to do would be to fix your environment so that it can find drush. Then you can use:

#!/usr/bin/env drush

As the hashbang for your drush script. If your system evn can't find it, then fix your search paths until it can!


问:
Java - How to run function synchronously for multiple threads
I must use three instances of the Runnable class named changeCase and only one single instance of the Server class for all three changeCase instances. The process execution needs to run continously, that is why I have used while (true) inside the overridden run method. The process method execution for each Thread is overlapping. How can I solve this issue?

My code:

```<code>package uppercase;

import java.util.Scanner;

class Server {

    void process(String threadName) {

        System.out.println("You are inside the Server " +threadName);

        System.out.println("Enter your sentence");
        Scanner sc1 = new Scanner(System.in);
        String input = sc1.nextLine();

        System.out.println("Press 1 to convert to Uppercase or Press 2 to convert to Lowercase");
        Scanner sc2 = new Scanner(System.in);
        int num = sc2.nextInt();

        switch (num) {
            case 1:
                changetoUpperCase(input);
                break;
            case 2:
                changetoLowerCase(input);
                break;
            default:
                System.out.println("Invalid number given\n\n");
                break;
        }
    }

    void changetoUpperCase(String msg) {

        printMessage(msg.toUpperCase());
    }

    void changetoLowerCase(String msg) {

        printMessage(msg.toLowerCase());
    }

    void printMessage(String msg) {

        System.out.println("[ " +msg+ " ]\n\n");

        try {
            Thread.sleep(1000);
        }catch (Exception e) {
           System.out.println(e.getMessage());
        }
    }
}

class changeCase implements Runnable {

    String threadName;
    Server target;
    Thread t;

    public changeCase(Server c, String s) {

        this.threadName = s;
        this.target = c;
    }

    @Override
    synchronized public void run() {

        while(true) {

            target.process(threadName);
        }

        //target.process(threadName);
    }

}

public class UpperCase {

    public static void main(String[] args) {

        Server s1 = new Server();

        Thread t1 = new Thread(new changeCase(s1, "Thread1"));
        Thread t2 = new Thread(new changeCase(s1, "Thread2"));
        Thread t3 = new Thread(new changeCase(s1, "Thread3"));

        t1.start();
        t2.start();
        t3.start();
    }

}
</code>```

The output I need:

```<code>run:
You are inside the Server Thread1
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
1
[ HELLO WORLD ]

You are inside the Server Thread3
Enter your sentence
HELLO WORLD
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
2
[ hello world ]

You are inside the Server Thread2
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
4
Invalid number given

You are inside the Server Thread3
Enter your sentence
</code>```

The output I am getting:

```<code>run:
You are inside the Server Thread1
Enter your sentence
You are inside the Server Thread2
Enter your sentence
You are inside the Server Thread3
Enter your sentence
</code>```

答:
You can use a counter to make thread execute one by one.  </p>

```<code>class Server {
int threadCount = 3;
volatile int i = 1;

synchronized void process(String threadName) {
    int thread = Integer.parseInt(threadName.substring(threadName.length() - 1));
    if (thread % threadCount != i) {
        return;
    }
    i = i == threadCount - 1 ? 0 : i + 1;

    System.out.println("You are inside the Server " + threadName);

    System.out.println("Enter your sentence");
    Scanner sc1 = new Scanner(System.in);
    String input = sc1.nextLine();
...
</code>```

Body:
I must use three instances of the Runnable class named changeCase and only one single instance of the Server class for all three changeCase instances. The process execution needs to run continously, that is why I have used while (true) inside the overridden run method. The process method execution for each Thread is overlapping. How can I solve this issue?

My code:

package uppercase;

import java.util.Scanner;

class Server {

    void process(String threadName) {

        System.out.println("You are inside the Server " +threadName);

        System.out.println("Enter your sentence");
        Scanner sc1 = new Scanner(System.in);
        String input = sc1.nextLine();

        System.out.println("Press 1 to convert to Uppercase or Press 2 to convert to Lowercase");
        Scanner sc2 = new Scanner(System.in);
        int num = sc2.nextInt();

        switch (num) {
            case 1:
                changetoUpperCase(input);
                break;
            case 2:
                changetoLowerCase(input);
                break;
            default:
                System.out.println("Invalid number given\n\n");
                break;
        }
    }

    void changetoUpperCase(String msg) {

        printMessage(msg.toUpperCase());
    }

    void changetoLowerCase(String msg) {

        printMessage(msg.toLowerCase());
    }

    void printMessage(String msg) {

        System.out.println("[ " +msg+ " ]\n\n");

        try {
            Thread.sleep(1000);
        }catch (Exception e) {
           System.out.println(e.getMessage());
        }
    }
}

class changeCase implements Runnable {

    String threadName;
    Server target;
    Thread t;

    public changeCase(Server c, String s) {

        this.threadName = s;
        this.target = c;
    }

    @Override
    synchronized public void run() {

        while(true) {

            target.process(threadName);
        }

        //target.process(threadName);
    }

}

public class UpperCase {

    public static void main(String[] args) {

        Server s1 = new Server();

        Thread t1 = new Thread(new changeCase(s1, "Thread1"));
        Thread t2 = new Thread(new changeCase(s1, "Thread2"));
        Thread t3 = new Thread(new changeCase(s1, "Thread3"));

        t1.start();
        t2.start();
        t3.start();
    }

}

The output I need:

run:
You are inside the Server Thread1
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
1
[ HELLO WORLD ]

You are inside the Server Thread3
Enter your sentence
HELLO WORLD
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
2
[ hello world ]

You are inside the Server Thread2
Enter your sentence
hello world
Press 1 to convert to Uppercase or Press 2 to convert to Lowercase
4
Invalid number given

You are inside the Server Thread3
Enter your sentence

The output I am getting:

run:
You are inside the Server Thread1
Enter your sentence
You are inside the Server Thread2
Enter your sentence
You are inside the Server Thread3
Enter your sentence

Body:
You can use a counter to make thread execute one by one.

class Server {
int threadCount = 3;
volatile int i = 1;

synchronized void process(String threadName) {
    int thread = Integer.parseInt(threadName.substring(threadName.length() - 1));
    if (thread % threadCount != i) {
        return;
    }
    i = i == threadCount - 1 ? 0 : i + 1;

    System.out.println("You are inside the Server " + threadName);

    System.out.println("Enter your sentence");
    Scanner sc1 = new Scanner(System.in);
    String input = sc1.nextLine();
...


问:
regex - remove partial text from duplicate strings
with some hassle i've come up with the following reg ex: (?m)(XXX).*\R(?s).*?\K\1 where XXX is the text i am selecting in the duplicate string (in this case (?m)(#  .*).*\R(?s).*?\K\1).

When I go for finds everything is ok but somehow Notepad++ gets stuck when I am trying to apply it and failing replaces. Sometimes find also fails too. any help about?

E.g.:

```<code>#Tfr.msg.FoldCleanup#   Folder Cleanup
#Tfr.msg.FoldCleanup#   Folder Cleanup
</code>```

I need to select and change everything after '# ' of every second duplicate string.

update: i've tried it here (https://regex101.com/r/WQXFy6/42) and it works correctly. but it goes completely nothing with N++...

答:
I've found out the correct regex to my second question and works flawlessly.

Find:

```<code>^(.*?)$\s+?^(?=.*^\1$)
</code>```

replace with:

```<code>!$0
</code>```

Body:
with some hassle i've come up with the following reg ex: (?m)(XXX).*\R(?s).*?\K\1 where XXX is the text i am selecting in the duplicate string (in this case (?m)(#  .*).*\R(?s).*?\K\1).

When I go for finds everything is ok but somehow Notepad++ gets stuck when I am trying to apply it and failing replaces. Sometimes find also fails too. any help about?

E.g.:

#Tfr.msg.FoldCleanup#   Folder Cleanup
#Tfr.msg.FoldCleanup#   Folder Cleanup

I need to select and change everything after '# ' of every second duplicate string.

update: i've tried it here (https://regex101.com/r/WQXFy6/42) and it works correctly. but it goes completely nothing with N++...

Body:
I've found out the correct regex to my second question and works flawlessly.

Find:

^(.*?)$\s+?^(?=.*^\1$)

replace with:

!$0


问:
Pandas Week of the Month Business Day Stock Price Data
My question is different than the following:

Question1: Week of a month pandas
Quesiton2: Week number of the month

The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.

My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.

My attempts has been the look ahead which isn't optimal:

```<code>def is_third_friday(s):
    d = datetime.datetime.strptime(s, '%Y-%m-%d')
    return d.weekday() == 5 and 15 <= d.day <= 21

dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True
</code>```

I don't know how to provide some sample data but if  you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.

The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.

Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.

答:
Though the title of the question is "Pandas Week of the Month", based on your comments to other answers, it seems you are primarily interested in identifying "OpEx week",  which is the trading week (i.e. Monday through Friday) that contains third Friday.

If above assumption and definition is correct, then this function will do the job:

```<code>def isOpexWeek(d):
    first_week_day = datetime.date(d.year, d.month, 1).weekday()
    first_friday = 1 + ((4 - first_week_day + 7) % 7)
    third_friday = first_friday + 14
    return d.day in range(third_friday-4, third_friday+1)

dow = pd.DataFrame(index=pd.date_range('2020-01-01', '2020-02-01'), columns=['OpexWeek'])
dow['OpexWeek'] = dow.index.to_series().apply(isOpexWeek)
print(dow)

dow = pd.DataFrame(index=pd.date_range('2020-01-01', '2021-01-01'), columns=['OpexWeek'])
dow['OpexWeek'] = dow.index.to_series().apply(isOpexWeek)
print(dow[dow.OpexWeek])
</code>```

Body:
My question is different than the following:

Question1: Week of a month pandas
Quesiton2: Week number of the month

The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.

My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.

My attempts has been the look ahead which isn't optimal:

def is_third_friday(s):
    d = datetime.datetime.strptime(s, '%Y-%m-%d')
    return d.weekday() == 5 and 15 <= d.day <= 21

dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True

I don't know how to provide some sample data but if  you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.

The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.

Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.

Body:
Though the title of the question is "Pandas Week of the Month", based on your comments to other answers, it seems you are primarily interested in identifying "OpEx week",  which is the trading week (i.e. Monday through Friday) that contains third Friday.

If above assumption and definition is correct, then this function will do the job:

def isOpexWeek(d):
    first_week_day = datetime.date(d.year, d.month, 1).weekday()
    first_friday = 1 + ((4 - first_week_day + 7) % 7)
    third_friday = first_friday + 14
    return d.day in range(third_friday-4, third_friday+1)

dow = pd.DataFrame(index=pd.date_range('2020-01-01', '2020-02-01'), columns=['OpexWeek'])
dow['OpexWeek'] = dow.index.to_series().apply(isOpexWeek)
print(dow)

dow = pd.DataFrame(index=pd.date_range('2020-01-01', '2021-01-01'), columns=['OpexWeek'])
dow['OpexWeek'] = dow.index.to_series().apply(isOpexWeek)
print(dow[dow.OpexWeek])


问:
Java float to a double and create the correct the format
Ths may well be a simple question.

I am having an issue with a timestamp which is represented as:

long timestamp: 351802384172493

I need to pass my timeStamp as a double, when i create the double it is represented as:

double timestamp: 3.15802384172493E14

I actually need to pass the double in this format:

double timestamp: 315802.384172493

Is there a best way to achieve this?

答:
Convert your long to double by dividing it by the correct factor

```<code>long timestamp = 351802384172493L;
double ts = timestamp / 1_000_000_000.0;

System.out.printf("%.9f\n", ts);
</code>```

yields

351802.384172493

Body:
Convert your long to double by dividing it by the correct factor

long timestamp = 351802384172493L;
double ts = timestamp / 1_000_000_000.0;

System.out.printf("%.9f\n", ts);

yields

351802.384172493


问:
Controlling output to a TV display while control panel is on laptop screen?
I have a program written in VB.Net with Visual Studio 2008.  I have one window form to display on a laptop that controls the information seen/sent on another form that is to be continually displayed on an output from the laptop to a TV, Projector or Monitor.

Or I would like to accomplish this:

Computer/laptop - Has window form 1 that controls the program
TV/Ouput - Has window form 2 that shows updated data on the screen for people to see

I do not want people to see the control form that is on the laptop.

Is their a way to assign a form to use an output to other screen only?

答: You can create two forms, one is the control panel with startup on the primary screen (default). For the other form, set the location to that of the secondary screen (i.e. TV or projector). To do this, iterate through i.e. Screen.AllScreens.Where(x=>!x.Primary).First(). The WorkingArea property gives the rectangle in which to place the second form.</p>


问:
PHP Split and sort data in new array
Restructuring PHP array data.
Testing the "data block 1" works fine and the data is correctly exploded in $newArray_1 and finally sorted in $newArray_2. I do not really use the explode but choosed to kept it in the code since it will be used later to extract the needed name of key within new arrays.

Question: Is it possible to use the same code base in order to solve with the same handling of "data block 2" ?

My code:

```<code>// Unsorted array -------------------------------------

$frontendData = [
  'datasheet' => [
    'Name_1_balance0'    => 1, // Data block 1
    'Name_1_balance2'    => 3, // Data block 1
    'Name_1_balance3'    => 4, // Data block 1
    'Name_1_balance1'    => 2, // Data block 1
    // 'Name_2_balance0'    => 5, // Data block 2
    // 'Name_2_balance2'    => 7, // Data block 2
    // 'Name_2_balance3'    => 8, // Data block 2
    // 'Name_2_balance1'    => 6, // Data block 2
  ]
];

ksort($frontendData['datasheet']);
print_r($frontendData);

// Explode array -------------------------------------

$newArray_1 = [];

foreach ( $frontendData as $mainKey => $elements )  {
    foreach ( $elements as $subKey => $value ){
        $newData = explode("_", $subKey);
        $newData[] = $value;
        $newArray_1[$mainKey][] = $newData;
    }
}

print_r($newArray_1);

// Restructure array -------------------------------------

$newArray_2['datasheet'] = ['Name_1'];

for ($i=0; $i <=3 ; $i++) {

  $newArray_2['datasheet'][1]['balance'][$i] =
    $newArray_1['datasheet'][$i][3];

}

print_r($newArray_2);
</code>```

Result (Processing "Data block 1"):

```<code>Array
(
    [datasheet] => Array
        (
            [0] => Name_1
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                            [3] => 4
                        )

                )

        )

)
</code>```

Wanted result (Processing "Data block 1" & "Data block 2"):

```<code>Array
(
    [datasheet] =>
        Array
        (
            [0] => Name_1
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                            [3] => 4
                        )

                )

        ),
        Array
        (
            [0] => Name_2
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 5
                            [1] => 6
                            [2] => 7
                            [3] => 8
                        )

                )

        )

)
</code>```

答:
try this</p>

```<code><?php
// Unsorted array -------------------------------------

$frontendData = [
  'datasheet' => [
    'Name_2_balance0'    => 5, // Data block 2
    'Name_1_balance0'    => 1, // Data block 1
    'Name_1_balance2'    => 3, // Data block 1
    'Name_1_balance3'    => 4, // Data block 1
    'Name_1_balance1'    => 2, // Data block 1
    'Name_2_balance2'    => 7, // Data block 2
    'Name_2_balance3'    => 8, // Data block 2
    'Name_2_balance1'    => 6, // Data block 2
  ]
];

ksort($frontendData['datasheet']);
// print_r($frontendData);

// Explode array -------------------------------------

$newArray_1 = array('datasheet'=>array());
$key='';
$i = 0;
foreach ( $frontendData['datasheet'] as $mainKey => $elements )  {
    $newData = explode("_", $mainKey);
    if(sizeof($newData)>=3){
        $newkey=$newData[0].'_'.$newData[1];
        if($newkey!=$key){
            $key=$newkey;
            array_push($newArray_1['datasheet'],array());
            array_push($newArray_1['datasheet'][$i], $newkey);
            array_push($newArray_1['datasheet'][$i], array());
            $k=array();
            array_push($k, $elements);
            $newArray_1['datasheet'][$i][1]=array('balance' => $k);
            $i++;

        }else{
            array_push($newArray_1['datasheet'][$i-1][1]['balance'], $elements);
        }

    }

}
echo "```";
print_r($newArray_1);
echo "```";
// Restructure array -------------------------------------

//$newArray_2['datasheet'] = ['Name_1'];

?>
</code>```

Title: PHP Split and sort data in new array

Body:
Restructuring PHP array data.
Testing the "data block 1" works fine and the data is correctly exploded in $newArray_1 and finally sorted in $newArray_2. I do not really use the explode but choosed to kept it in the code since it will be used later to extract the needed name of key within new arrays.

Question: Is it possible to use the same code base in order to solve with the same handling of "data block 2" ?

My code:

// Unsorted array -------------------------------------

$frontendData = [
  'datasheet' => [
    'Name_1_balance0'    => 1, // Data block 1
    'Name_1_balance2'    => 3, // Data block 1
    'Name_1_balance3'    => 4, // Data block 1
    'Name_1_balance1'    => 2, // Data block 1
    // 'Name_2_balance0'    => 5, // Data block 2
    // 'Name_2_balance2'    => 7, // Data block 2
    // 'Name_2_balance3'    => 8, // Data block 2
    // 'Name_2_balance1'    => 6, // Data block 2
  ]
];

ksort($frontendData['datasheet']);
print_r($frontendData);

// Explode array -------------------------------------

$newArray_1 = [];

foreach ( $frontendData as $mainKey => $elements )  {
    foreach ( $elements as $subKey => $value ){
        $newData = explode("_", $subKey);
        $newData[] = $value;
        $newArray_1[$mainKey][] = $newData;
    }
}

print_r($newArray_1);

// Restructure array -------------------------------------

$newArray_2['datasheet'] = ['Name_1'];

for ($i=0; $i <=3 ; $i++) {

  $newArray_2['datasheet'][1]['balance'][$i] =
    $newArray_1['datasheet'][$i][3];

}

print_r($newArray_2);

Result (Processing "Data block 1"):

Array
(
    [datasheet] => Array
        (
            [0] => Name_1
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                            [3] => 4
                        )

                )

        )

)

Wanted result (Processing "Data block 1" & "Data block 2"):

Array
(
    [datasheet] =>
        Array
        (
            [0] => Name_1
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                            [3] => 4
                        )

                )

        ),
        Array
        (
            [0] => Name_2
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 5
                            [1] => 6
                            [2] => 7
                            [3] => 8
                        )

                )

        )

)

Body:
try this

<?php
// Unsorted array -------------------------------------

$frontendData = [
  'datasheet' => [
    'Name_2_balance0'    => 5, // Data block 2
    'Name_1_balance0'    => 1, // Data block 1
    'Name_1_balance2'    => 3, // Data block 1
    'Name_1_balance3'    => 4, // Data block 1
    'Name_1_balance1'    => 2, // Data block 1
    'Name_2_balance2'    => 7, // Data block 2
    'Name_2_balance3'    => 8, // Data block 2
    'Name_2_balance1'    => 6, // Data block 2
  ]
];

ksort($frontendData['datasheet']);
// print_r($frontendData);

// Explode array -------------------------------------

$newArray_1 = array('datasheet'=>array());
$key='';
$i = 0;
foreach ( $frontendData['datasheet'] as $mainKey => $elements )  {
    $newData = explode("_", $mainKey);
    if(sizeof($newData)>=3){
        $newkey=$newData[0].'_'.$newData[1];
        if($newkey!=$key){
            $key=$newkey;
            array_push($newArray_1['datasheet'],array());
            array_push($newArray_1['datasheet'][$i], $newkey);
            array_push($newArray_1['datasheet'][$i], array());
            $k=array();
            array_push($k, $elements);
            $newArray_1['datasheet'][$i][1]=array('balance' => $k);
            $i++;

        }else{
            array_push($newArray_1['datasheet'][$i-1][1]['balance'], $elements);
        }

    }

}
echo "<pre>";
print_r($newArray_1);
echo "</pre>";
// Restructure array -------------------------------------

//$newArray_2['datasheet'] = ['Name_1'];

?>


问:
Change value in textbox from combobox
I'm trying to make the textbox value change based on the value of the combobox. It's should be fairly straight forward, but I'm struggling with this.

```<code>Private Sub Combobox1_Change()
 x = Combobox1.Value
 textbox1.Value = Worksheets("Sheet1").Range("B") & x
End Sub
</code>```

P.S. For clarity, I've never been a professional programmer or code writer.

答:
I think your problem is that the bracket in the wrong place.

```<code>Range("B" & x).value
</code>```

I also would prefer this version:

```<code>Range("B1").Offset(x - 1).Value
</code>```

Title: Change value in textbox from combobox

Body:
I'm trying to make the textbox value change based on the value of the combobox. It's should be fairly straight forward, but I'm struggling with this.

Private Sub Combobox1_Change()
 x = Combobox1.Value
 textbox1.Value = Worksheets("Sheet1").Range("B") & x
End Sub

P.S. For clarity, I've never been a professional programmer or code writer.

Body:
I think your problem is that the bracket in the wrong place.

Range("B" & x).value

I also would prefer this version:

Range("B1").Offset(x - 1).Value


问:
Need help retrieving Deep values from Hashtable in Powershell
I kinda need help retrieving deep values from HashTable.

My Situation: I wrote a C# executable which gives me data in JSON format that I stored in a variable $Result.
I'm able to fetch and process all fields of $Result except nested HashTable called Properties and its keys (Locations). I just need to list the cities which are mentioned in the HashTable called Properties

At the minute I'm able to get the Locations Key as shown below

PS C:\WINDOWS\system32> $Result.Properties.Locations
City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009

PS C:\WINDOWS\system32> ```
</div>
</div>
</p>

<p><strong>Expected Output</strong>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>NewYork
Seattle
Miami
SanJose</code>```

Properties Hashtable

[Properties]@
{
    accountExpires=Never;
    AccountLockedOut=False;
    mail=JamesBond@internationalspy.com;
    cn=Tom Cruise;
    codePage=0;
    countryCode=0;
    displayName=Tom Cruise;
    employeeID=743355;
    Enabled=True;
    givenName=Tom;
    instanceType=4;
    lastLogoff=12/31/1600 4:00:00 PM;
    lastLogon=3/27/2020 7:52:36 AM;
    lastLogonTimestamp=5/25/2020 12:47:07 PM;
    lockoutTime=12/31/1600 4:00:00 PM;
    logonCount=4;
    mail=jamesbond@InternalActor.com;
    Locations=City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009
}```

I need to get the fetch the list of cities which are nested with the above Hashtable.
I just want the list of cities so that I can further apply my business logic and proceed further.

答:
Here's some more alternatives for you:

split and replace:

```<code>($Result.Properties.Locations -split '[;,]' | Where-Object { $_ -match '^City=' }) -replace '^City='
</code>```

split and ConvertFrom-StringData

```<code>($Result.Properties.Locations -split '[;,]' | ConvertFrom-StringData).City
</code>```

iterate over matches

```<code>$match = ([regex]'(?i)City=([^,]+)').Match($Result.Properties.Locations)
while ($match.Success) {
    $match.Groups[1].Value
    $match = $match.NextMatch()
}
</code>```

All result in

```
NewYork
Seattle
Miami
SanJose
```

Body:
I kinda need help retrieving deep values from HashTable.

My Situation: I wrote a C# executable which gives me data in JSON format that I stored in a variable $Result.
I'm able to fetch and process all fields of $Result except nested HashTable called Properties and its keys (Locations). I just need to list the cities which are mentioned in the HashTable called Properties

At the minute I'm able to get the Locations Key as shown below

PS C:\WINDOWS\system32> $Result.Properties.Locations
City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009

PS C:\WINDOWS\system32>

Expected Output:

NewYork
Seattle
Miami
SanJose

Properties Hashtable

[Properties]@
{
    accountExpires=Never;
    AccountLockedOut=False;
    mail=JamesBond@internationalspy.com;
    cn=Tom Cruise;
    codePage=0;
    countryCode=0;
    displayName=Tom Cruise;
    employeeID=743355;
    Enabled=True;
    givenName=Tom;
    instanceType=4;
    lastLogoff=12/31/1600 4:00:00 PM;
    lastLogon=3/27/2020 7:52:36 AM;
    lastLogonTimestamp=5/25/2020 12:47:07 PM;
    lockoutTime=12/31/1600 4:00:00 PM;
    logonCount=4;
    mail=jamesbond@InternalActor.com;
    Locations=City=NewYork,Country=USA,Year=2001;City=Seattle,Country=USA,Year=2002;City=Miami,Country=USA,Year=2010;City=SanJose,Country=USA,Year=2009
}

I need to get the fetch the list of cities which are nested with the above Hashtable.
I just want the list of cities so that I can further apply my business logic and proceed further.

Body:
Here's some more alternatives for you:

split and replace:

($Result.Properties.Locations -split '[;,]' | Where-Object { $_ -match '^City=' }) -replace '^City='

split and ConvertFrom-StringData

($Result.Properties.Locations -split '[;,]' | ConvertFrom-StringData).City

iterate over matches

$match = ([regex]'(?i)City=([^,]+)').Match($Result.Properties.Locations)
while ($match.Success) {
    $match.Groups[1].Value
    $match = $match.NextMatch()
}

All result in

NewYork
Seattle
Miami
SanJose


问:
server that supports Unix and TCP clients
I'm making a server/client program in C (LINUX). I have 4 programs in a folder. A clientUNIX, a clientTCP, a serverUNIX and a serverTCP. They all work flawlessly. Now, my goal is to make a server that supports both clients.

The easiest way of doing this, for me, was to start a new program (serverTCPUNIX) that does the following:

In main(), create a thread to handle TCP clients and another thread to handle UNIX clients.

Is there a better way of achieving this? Because this way, I'd have 2 threads looping through clients. I want to know if I can have only 1 thread and 1 loop that supports both types of clients.

Thanks.

答: Maybe you could switch the sockets on the server to non-blocking mode and then use select() to wait for either of them to receive a connection and handle it as needed, for example by creating a thread handling the client's request, and then going back to same select() to wait for the next incoming connection.