问:
Javadoc generation failed. Unmappable character for encoding ASCII
When I want to build the project using IntelliJ and Gradle
I get two errors:

```<code>Execution failed for task ':javadoc'.
Javadoc generation failed.
</code>```

and

```<code>error: unmappable character for encoding ASCII
W??hrung
</code>```

Here I use the German Umlaut 'ä' on one of the file in the project.

Three of my work colleagues have exactly the same project using also IntelliJ and have the same setting in Preferences>Editor>File Encoding like i do. But the project is build successfully by my work colleagues.

I found a temporary solution to put the following lines in the build.gradle:

```<code>javadoc {
    options.encoding = 'UTF-8'
}
</code>```

Why I get the errors when I build the project?

答:
If you generate your Javadocs with a Gradle Task your IntelliJ Configuration does not matter since Gradle only reads the Gradle Configuration (build.gradle). Therefore you have to set the file encoding in Gradle.

You may configure Gradle to always use UTF-8 -> Stackoverflow issue on how to set encoding to UTF-8

Body:
When I want to build the project using IntelliJ and Gradle
I get two errors:

Execution failed for task ':javadoc'.
Javadoc generation failed.

and

error: unmappable character for encoding ASCII
W??hrung

Here I use the German Umlaut 'ä' on one of the file in the project.

Three of my work colleagues have exactly the same project using also IntelliJ and have the same setting in Preferences>Editor>File Encoding like i do. But the project is build successfully by my work colleagues.

I found a temporary solution to put the following lines in the build.gradle:

javadoc {
    options.encoding = 'UTF-8'
}

Why I get the errors when I build the project?


来源: stackexchange

问:
Xamarin Forms Best way to run a background thread
I have a question. I am building an app that collects stock market prices, but now the most important part is where I do a call every x seconds to get the new price. The variable of the price is located in the App.xaml.cs, so it is global for every page, but now I need to update it with the following line every 3 seconds: CoinList = await RestService.GetCoins();

The function must be async because the whole RestService is async!

I already found something like this:

```<code>var minutes = TimeSpan.FromMinutes (3);

Device.StartTimer (minutes, () => {

    // call your method to check for notifications here

    // Returning true means you want to repeat this timer
    return true;
});
</code>```

But I don't know if this is the best way to do it and where I should put it, because it is the most essential part of my app!

Any suggestions?

答:
Just wrap the async method into a Task.Run, check the code below .

```<code>Device.StartTimer(TimeSpan.FromSeconds(3), () =>
{
  Task.Run(async () =>
  {
    CoinList = await RestService.GetCoins();
  });
  return true;
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a question. I am building an app that collects stock market prices, but now the most important part is where I do a call every x seconds to get the new price. The variable of the price is located in the App.xaml.cs, so it is global for every page, but now I need to update it with the following line every 3 seconds: CoinList = await RestService.GetCoins();

The function must be async because the whole RestService is async!

I already found something like this:

var minutes = TimeSpan.FromMinutes (3);

Device.StartTimer (minutes, () => {

    // call your method to check for notifications here

    // Returning true means you want to repeat this timer
    return true;
});

But I don't know if this is the best way to do it and where I should put it, because it is the most essential part of my app!

Any suggestions?

Body:
Just wrap the async method into a Task.Run, check the code below .

Device.StartTimer(TimeSpan.FromSeconds(3), () =>
{
  Task.Run(async () =>
  {
    CoinList = await RestService.GetCoins();
  });
  return true;
});


问:
How to connect to Oracle Database with php?
I am currently working on a website that connects to an Oracle Database. I have two php files, one for connection with the database and the other is the html structure itself.

Connect.php:

```<code><?php

$servername = "//////";
$username = "/////";
$password = "/////";

$conn = oci_connect($servername, $username, $password);

 if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
 }
 echo "Connected!";

?>
</code>```

I have been having a very hard time connecting to the database. I followed the Oracle tutorial and edited the oci8.connection_class = MYPHPAPP in php.ini, but everytime I run the Connect.php, I get the HTTP Error 500. Did I miss anything? What should I do?

Edit 1: I used display_errors and the error I am getting is Call to undefined function oci_connect()

Edit 2: I tried everything at this point to make the oci_connect work. I downloaded the oracle client and made it an environmental variable but oci_connect is still not working. I would really appreciate if any mac users could help me with this.

答:
Download the appropriate oracle client to your machine, extract it and copy and paste in your system drive.

Add the path of your oracle client to environment variables.

Then you need to enable php_oci8_12c extension using php.ini or GUI if available.
Open php file and write the following code:

```<code>function connect(){
     $dburl = "(DESCRIPTION =
     (ADDRESS = (PROTOCOL = TCP)(HOST = your_host)(PORT = 1521))
     (CONNECT_DATA =
       (SERVER = DEDICATED)
       (SERVICE_NAME = your_db_sid)
     )
     )";
     //db charset is optional
     $db_charset = 'WE8MSWIN1252'; //your db charset goes here
     try {
         return oci_connect("username", "password",$dburl,$db_charset);
       }
       catch (Exception $e) {
         die($e);
       }
   }
</code>```

This code is work fine on my windows 10 machine, php 7.1.9 and oracle 12c.

Body:
I am currently working on a website that connects to an Oracle Database. I have two php files, one for connection with the database and the other is the html structure itself.

Connect.php:

<?php

$servername = "//////";
$username = "/////";
$password = "/////";

$conn = oci_connect($servername, $username, $password);

 if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
 }
 echo "Connected!";

?>

I have been having a very hard time connecting to the database. I followed the Oracle tutorial and edited the oci8.connection_class = MYPHPAPP in php.ini, but everytime I run the Connect.php, I get the HTTP Error 500. Did I miss anything? What should I do?

Edit 1: I used display_errors and the error I am getting is Call to undefined function oci_connect()

Edit 2: I tried everything at this point to make the oci_connect work. I downloaded the oracle client and made it an environmental variable but oci_connect is still not working. I would really appreciate if any mac users could help me with this.

Body:
Download the appropriate oracle client to your machine, extract it and copy and paste in your system drive.

Add the path of your oracle client to environment variables.

Then you need to enable php_oci8_12c extension using php.ini or GUI if available.
Open php file and write the following code:

function connect(){
     $dburl = "(DESCRIPTION =
     (ADDRESS = (PROTOCOL = TCP)(HOST = your_host)(PORT = 1521))
     (CONNECT_DATA =
       (SERVER = DEDICATED)
       (SERVICE_NAME = your_db_sid)
     )
     )";
     //db charset is optional
     $db_charset = 'WE8MSWIN1252'; //your db charset goes here
     try {
         return oci_connect("username", "password",$dburl,$db_charset);
       }
       catch (Exception $e) {
         die($e);
       }
   }

This code is work fine on my windows 10 machine, php 7.1.9 and oracle 12c.


问:
How do I escape a special Regex character?
I've encountered a problem in Java, specific to the String.split function.
I'm porting my C# code to Java, and something bothers Java. My C# code is as follows :

```<code>foreach (char sep in separators)
    if (text.Contains(sep.ToString()))
        array = text.Reverse().Split(sep);
</code>```

Reverse() is an extension I've made myself which just reverses a string.
separators is a char array that contains a few separators :

```<code>char[] separators = { '&', '!', '#', '?', '%' };
</code>```

Now, in Java, my code is as follows :

```<code>for (char sep : separators) {
    String sepp = String.valueOf(sep);
    if (text.contains(sepp))
        array = new StringBuilder(text).reverse().toString().split(sepp);
}
</code>```

The problem with this code is that, when I have the specific separator ? (it's randomly choosed), then it throws me this error (Java only) :

```<code>Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
at java.base/java.util.regex.Pattern.error(Pattern.java:2027)
at java.base/java.util.regex.Pattern.sequence(Pattern.java:2202)
at java.base/java.util.regex.Pattern.expr(Pattern.java:2068)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1782)
at java.base/java.util.regex.Pattern.<init>(Pattern.java:1428)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.split(String.java:2317)
at java.base/java.lang.String.split(String.java:2364)
at com.anerruption.encryption.Main.decrypt(Main.java:58)
at com.anerruption.encryption.Main.main(Main.java:43)
</code>```

My guess is that the function string.Split in C# doesn't use Regex, but the one in Java does. From what I've heard, I need to escape the character. Doing \\? did not work. How could I do this?

Any help is greatly appreciated!

答:
you can use this way, by concatenating "\\" to each separator only for split() method

```<code>char[] separators = { '&', '!', '#', '?', '%' };

for (char sep : separators) {
    if (text.contains(sep+""))
       array = new StringBuilder(text).reverse().toString().split("\\"+sep);
}
</code>```

Body:
I've encountered a problem in Java, specific to the String.split function.
I'm porting my C# code to Java, and something bothers Java. My C# code is as follows :

foreach (char sep in separators)
    if (text.Contains(sep.ToString()))
        array = text.Reverse().Split(sep);

Reverse() is an extension I've made myself which just reverses a string.
separators is a char array that contains a few separators :

char[] separators = { '&', '!', '#', '?', '%' };

Now, in Java, my code is as follows :

for (char sep : separators) {
    String sepp = String.valueOf(sep);
    if (text.contains(sepp))
        array = new StringBuilder(text).reverse().toString().split(sepp);
}

The problem with this code is that, when I have the specific separator ? (it's randomly choosed), then it throws me this error (Java only) :

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
at java.base/java.util.regex.Pattern.error(Pattern.java:2027)
at java.base/java.util.regex.Pattern.sequence(Pattern.java:2202)
at java.base/java.util.regex.Pattern.expr(Pattern.java:2068)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1782)
at java.base/java.util.regex.Pattern.<init>(Pattern.java:1428)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.split(String.java:2317)
at java.base/java.lang.String.split(String.java:2364)
at com.anerruption.encryption.Main.decrypt(Main.java:58)
at com.anerruption.encryption.Main.main(Main.java:43)

My guess is that the function string.Split in C# doesn't use Regex, but the one in Java does. From what I've heard, I need to escape the character. Doing \\? did not work. How could I do this?

Any help is greatly appreciated!

Body:
you can use this way, by concatenating "\\" to each separator only for split() method

char[] separators = { '&', '!', '#', '?', '%' };

for (char sep : separators) {
    if (text.contains(sep+""))
       array = new StringBuilder(text).reverse().toString().split("\\"+sep);
}


问:
Process 350k requests per seconds and save data to Google Cloud Storage
I need to implement microservice which is fairly simple in terms of logic and architecture, but needs to handle around 305k requests per second.

All it's going to do is to ingest JSON data, validate it according to simple rules and record to Google Cloud Storage as JSON files. There are lots of Google Cloud services and APIs available, but it's hard for me to pick proper stack and pipeline because I have not had much experience with them as well as with highload.

There is an example I'm looking at
https://cloud.google.com/pubsub/docs/pubsub-dataflow

The flow is the following:

```<code>PubSub > Dataflow > Cloud Storage
</code>```

It does exactly what I need (except date validation) but looks like Dataflow is limited to Java and Python, and I'd rather use PHP.

Another relevant example is
https://medium.com/google-cloud/cloud-run-using-pubsub-triggers-2db74fc4ac6d

It uses Cloud Run, with supports PHP, and PubSub to trigger Cloud Run workload. So it goes like:

```<code>PubSub > Cloud Run
</code>```

and working with Cloud Storage in Run looks pretty simple.

Am I on a right way? Can something like mentioned above work for me or do I need something different?

答:
My first intuition when I saw 350k request per seconds and PubSub, is this pattern:

```<code>Pubsub > Dataflow > BigTable
</code>```

My question validate the choice of BigTable because you can query BigTable table from BigQuery for later analysis.

Of course, it's expensive but you have here a very scalable system.

An alternative, if your process fits the BigQuery streaming quotas, is to stream directly into BigQuery instead of BigTable.

```<code>Pubsub > Dataflow > BigQuery
</code>```

The problem with a solution of Cloud Run or App Engine, is that you will need to run a process externally (for example with Cloud Scheduler), and in this process, you will perform a loop to pull message from PubSub subscription. You will cope with several difficulties

PubSub perform at least 1 delivery and double messages can be a concern. Dataflow manage this automatically

The memory limitation of App Engine and Cloud Run can be an issue, especially if your language is not memory efficient.

Pulling velocity can be a concern, and parallelism can be a challenge.

Pulling duration is limited to some minutes (because of max request duration on Cloud Run and App Engine) and you have to exit gracefully and to wait the next Cloud Scheduler trigger to start again the PubSub pulling.

EDIT

I forgot that you didn't want to code in Java or Python. I can propose you 2 alternative if your process is really simple:

Use Google provided Dataflow template, especially in streaming where you can stream directly into BigQuery, without transformation. And if you want to perform transform, you can use the source code as base and just add your transform step in it.

You can process your PubSub messages as a simple SQL query. Quite boring to set up, but you simply have to define your transform in SQL language and the Dataflow is built for you.

Personal opinion: coding language doesn't matter, use the right tool for the right job. Using Cloud Run or App Engine for this will create a much more unstable and hard to maintain system than learning how to write 10 lines of Java code

Body:
I need to implement microservice which is fairly simple in terms of logic and architecture, but needs to handle around 305k requests per second.

All it's going to do is to ingest JSON data, validate it according to simple rules and record to Google Cloud Storage as JSON files. There are lots of Google Cloud services and APIs available, but it's hard for me to pick proper stack and pipeline because I have not had much experience with them as well as with highload.

There is an example I'm looking at
https://cloud.google.com/pubsub/docs/pubsub-dataflow

The flow is the following:

PubSub > Dataflow > Cloud Storage

It does exactly what I need (except date validation) but looks like Dataflow is limited to Java and Python, and I'd rather use PHP.

Another relevant example is
https://medium.com/google-cloud/cloud-run-using-pubsub-triggers-2db74fc4ac6d

It uses Cloud Run, with supports PHP, and PubSub to trigger Cloud Run workload. So it goes like:

PubSub > Cloud Run

and working with Cloud Storage in Run looks pretty simple.

Am I on a right way? Can something like mentioned above work for me or do I need something different?

Body:
My first intuition when I saw 350k request per seconds and PubSub, is this pattern:

Pubsub > Dataflow > BigTable

My question validate the choice of BigTable because you can query BigTable table from BigQuery for later analysis.

Of course, it's expensive but you have here a very scalable system.

An alternative, if your process fits the BigQuery streaming quotas, is to stream directly into BigQuery instead of BigTable.

Pubsub > Dataflow > BigQuery

The problem with a solution of Cloud Run or App Engine, is that you will need to run a process externally (for example with Cloud Scheduler), and in this process, you will perform a loop to pull message from PubSub subscription. You will cope with several difficulties

PubSub perform at least 1 delivery and double messages can be a concern. Dataflow manage this automatically

The memory limitation of App Engine and Cloud Run can be an issue, especially if your language is not memory efficient.

Pulling velocity can be a concern, and parallelism can be a challenge.

Pulling duration is limited to some minutes (because of max request duration on Cloud Run and App Engine) and you have to exit gracefully and to wait the next Cloud Scheduler trigger to start again the PubSub pulling.

EDIT

I forgot that you didn't want to code in Java or Python. I can propose you 2 alternative if your process is really simple:

Use Google provided Dataflow template, especially in streaming where you can stream directly into BigQuery, without transformation. And if you want to perform transform, you can use the source code as base and just add your transform step in it.

You can process your PubSub messages as a simple SQL query. Quite boring to set up, but you simply have to define your transform in SQL language and the Dataflow is built for you.

Personal opinion: coding language doesn't matter, use the right tool for the right job. Using Cloud Run or App Engine for this will create a much more unstable and hard to maintain system than learning how to write 10 lines of Java code


问:
Can I make component parameter required when building a custom Blazor component?
When I try to build a Blazor component I can define parameters for it like this:

```<code>@code {

   [Parameter]
   public string MyString { get; set; }

}
</code>```

My question is can I make this parameter required so that, when component is used, the project will not build unless I provide the specified parameter? Is this something I should even be worried about? I suppose I could handle any invalid values in component initialization by maybe throwing an exception if the value is not provided like this:

```<code>protected override void OnInitialized()
{
    base.OnInitialized();
    if (string.IsNullOrWhiteSpace(MyString)) {
       // throw an exception here...
    }
}
</code>```

but is that the right way to handle this?

答:
Not yet, no. The best you can do at the moment is to throw an exception in SetParametersAsync.

There's a section on optional route parameters on Blazor University that will show how to check if a parameter was passed or not. You simply make it nullable and check it isn't null.
https://blazor-university.com/routing/optional-route-parameters/

Alternatively, if override SetParametersAsync you are passed a ParameterView parameters parameter, you can use parameters.TryGetValue to determine if a parameter was passed, and throw an exception if it wasn't.

But there is currently no way to cause compile-time errors.

Body:
When I try to build a Blazor component I can define parameters for it like this:

@code {

   [Parameter]
   public string MyString { get; set; }

}

My question is can I make this parameter required so that, when component is used, the project will not build unless I provide the specified parameter? Is this something I should even be worried about? I suppose I could handle any invalid values in component initialization by maybe throwing an exception if the value is not provided like this:

protected override void OnInitialized()
{
    base.OnInitialized();
    if (string.IsNullOrWhiteSpace(MyString)) {
       // throw an exception here...
    }
}

but is that the right way to handle this?


问:
Using Variables and/or Properties with Simple Data Writer in JMeter
Using JMeter v5.1.1, I am setting a dynamic file path and name to be used with Simple Data Writer.  I've tried this every way I can think of to no avail.  Things I've tried:

JSR223 PreProcessor (scoped to same thread group) which stores dynamic path/name in variables, and use variable in Simple Data Writer

Execute thread groups consecutively.  Use StartUp Thread with JSR223 Sampler which stores dynamic path/name in properties, and use __P function in Simple Data Writer to retrieve path/name.  This method will pull the property values from the previous run if I do not remove the properties at the end of the test.

Execute thread groups consecutively.  Use StartUp Thread with JSR223 Sampler which stores dynamic path/name in properties.  Run JSR223 PreProcessor which stores global properties as variables in thread group, and use variables in Simple Data Writer to retrieve path/name.  I've also tried the __V function with this approach.  This method will pull the property values from the previous run if I do not remove the properties at the end of the test.

I can see in the JSR223 scripts that the path/name are being set correctly using log.info.  I can also see them set when using a debug sampler, but for some reason the Simple Data Writer does not seem to be picking them up.  If I set the variables before running, it works fine.  This seems like an order of operations problem, or asynchronous/multi-thread issue, but am not sure how to proceed.  Any guidance would be much appreciated.

Here's a sample to reproduce the behavior:

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.1.1 r1855137">
  <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Data Writer Issue" enabled="true">
      <stringProp name="TestPlan.comments"></stringProp>
      <boolProp name="TestPlan.functional_mode">false</boolProp>
      <boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp>
      <boolProp name="TestPlan.serialize_threadgroups">true</boolProp>
      <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments"/>
      </elementProp>
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
      <SetupThreadGroup guiclass="SetupThreadGroupGui" testclass="SetupThreadGroup" testname="setUp Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </SetupThreadGroup>
      <hashTree>
        <JSR223Sampler guiclass="TestBeanGUI" testclass="JSR223Sampler" testname="Set Path to Store Results" enabled="true">
          <stringProp name="scriptLanguage">groovy</stringProp>
          <stringProp name="parameters"></stringProp>
          <stringProp name="filename"></stringProp>
          <stringProp name="cacheKey">true</stringProp>
          <stringProp name="script">import org.apache.jmeter.services.FileServer;

// Get the separator for current OS
String separator = File.separator;

// Use {{current directory}}/csv for path
String path = FileServer.getFileServer().getBaseDir() + separator + "csv" + separator;

// Create directory if doesn't already exist
(new File(path)).mkdirs();

log.info(path);

// Save path to property
props.put("data-file-path", path);</stringProp>
        </JSR223Sampler>
        <hashTree/>
        <JSR223Sampler guiclass="TestBeanGUI" testclass="JSR223Sampler" testname="Set FileName to Store Results" enabled="true">
          <stringProp name="scriptLanguage">groovy</stringProp>
          <stringProp name="parameters"></stringProp>
          <stringProp name="filename"></stringProp>
          <stringProp name="cacheKey">true</stringProp>
          <stringProp name="script">import org.apache.jmeter.services.FileServer;
import java.time.*;
import java.time.format.*;

// Get current date/time formatted as yyyyMMddHHmm
String formattedDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yMMddHHmm"));

// Get name of currently-running script
String scriptName = FileServer.getFileServer().getScriptName();

// Save fileName as scriptName (minus file extension) with timestamp at end
String fileName = scriptName.take(scriptName.lastIndexOf('.'))  + "_" + formattedDateTime + ".csv";

log.info(fileName);

// Set filename as property
props.put("data-file-name", fileName);</stringProp>
        </JSR223Sampler>
        <hashTree/>
      </hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Sample GET Requests" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">2</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
        <boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
        <boolProp name="ThreadGroup.delayedStart">true</boolProp>
      </ThreadGroup>
      <hashTree>
        <DebugSampler guiclass="TestBeanGUI" testclass="DebugSampler" testname="Debug Sampler" enabled="true">
          <boolProp name="displayJMeterProperties">true</boolProp>
          <boolProp name="displayJMeterVariables">true</boolProp>
          <boolProp name="displaySystemProperties">false</boolProp>
        </DebugSampler>
        <hashTree/>
        <ResultCollector guiclass="SimpleDataWriter" testclass="ResultCollector" testname="Save Results to CSV File" enabled="true">
          <boolProp name="ResultCollector.error_logging">false</boolProp>
          <objProp>
            <name>saveConfig</name>
            <value class="SampleSaveConfiguration">
              <time>true</time>
              <latency>true</latency>
              <timestamp>true</timestamp>
              <success>true</success>
              true
              true
              <message>true</message>
              <threadName>true</threadName>
              <dataType>true</dataType>
              <encoding>false</encoding>
              <assertions>false</assertions>
              <subresults>true</subresults>
              <responseData>false</responseData>
              <samplerData>false</samplerData>
              <xml>false</xml>
              <fieldNames>true</fieldNames>
              <responseHeaders>false</responseHeaders>
              <requestHeaders>false</requestHeaders>
              <responseDataOnError>false</responseDataOnError>
              <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
              <assertionsResultsToSave>0</assertionsResultsToSave>
              <bytes>true</bytes>
              <sentBytes>true</sentBytes>
              <url>true</url>
              <threadCounts>true</threadCounts>
              <idleTime>true</idleTime>
              <connectTime>true</connectTime>
            </value>
          </objProp>
          <stringProp name="filename">${__P(data-file-path)}${__P(data-file-name)}</stringProp>
        </ResultCollector>
        <hashTree/>
        <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Get ToDo" enabled="true">
          <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
            <collectionProp name="Arguments.arguments"/>
          </elementProp>
          <stringProp name="HTTPSampler.domain">jsonplaceholder.typicode.com</stringProp>
          <stringProp name="HTTPSampler.port"></stringProp>
          <stringProp name="HTTPSampler.protocol">https</stringProp>
          <stringProp name="HTTPSampler.contentEncoding"></stringProp>
          <stringProp name="HTTPSampler.path">/todos/1</stringProp>
          <stringProp name="HTTPSampler.method">GET</stringProp>
          <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
          <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
          <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
          <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
          <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
          <stringProp name="HTTPSampler.connect_timeout"></stringProp>
          <stringProp name="HTTPSampler.response_timeout"></stringProp>
          <stringProp name="TestPlan.comments">"groupNames": ["${__P(GroupNames_${__Random(1,${__property(GroupNames_matchNr)})})}"]</stringProp>
        </HTTPSamplerProxy>
        <hashTree/>
      </hashTree>
      <PostThreadGroup guiclass="PostThreadGroupGui" testclass="PostThreadGroup" testname="tearDown Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </PostThreadGroup>
      <hashTree>
        <JSR223Sampler guiclass="TestBeanGUI" testclass="JSR223Sampler" testname="Clear Dynamic Properties" enabled="true">
          <stringProp name="scriptLanguage">groovy</stringProp>
          <stringProp name="parameters"></stringProp>
          <stringProp name="filename"></stringProp>
          <stringProp name="cacheKey">true</stringProp>
          <stringProp name="script">props.remove("data-file-path");
props.remove("data-file-name");</stringProp>
        </JSR223Sampler>
        <hashTree/>
      </hashTree>
      <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
          <name>saveConfig</name>
          <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            true
            true
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>true</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
            <sentBytes>true</sentBytes>
            <url>true</url>
            <threadCounts>true</threadCounts>
            <idleTime>true</idleTime>
            <connectTime>true</connectTime>
          </value>
        </objProp>
        <stringProp name="filename"></stringProp>
      </ResultCollector>
      <hashTree/>
    </hashTree>
  </hashTree>
</jmeterTestPlan>

```

答: You can debug this issue using step-by-step Debugger. Also you can use inbuilt JMeter function to complete your requirement if you can. Because inbuilt JMeter function works well in listener's path.</p>


问:
What is side effect in C?
Wikipedia says that:

In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides returning a value (the main effect) to the invoker of the operation.

But how can we access a variable outside its local environment, can anyone explain this situation, side effect, main effect and sequence point comprehensibly?

答:
A function is (should be) a black box, in which the return value, or the value of a variable passed by reference, should be the only thing that may change depending upon the input parameters.

Any other observable change that the function produces outside these cases, is a side-effect. The most well-known example may be the printf() function which, besides returning the number of written characters, changes the contents of the standard output, which means altering some memory buffer associated with a pipe, a file, or the screen, for instance, and which doesn't belong to the local environment of the function.

Title: What is side effect in C?


问:
Swipe in vuetify list items
I am trying to make a swipeable version of the vuetify list elements. I found the swiperjs.com library which does an awesome job in adding swiping capabilities for an html element. I also found this project https://github.com/davidgaroro/vuetify-swipeout which integrates the vuetify library and the swipeable library. Having read the content of the vuetify-swipeout project it looks like the trick is only in setting the right classes on the v-list-tile component, namely

```<code> <v-list-tile class="swiper-slide">
</code>```

while surrounding the element with

```<code><div :id="id" class="swiper-container">
    <div class="swiper-wrapper">
      ...
    </div>
</div>
</code>```

The demo works pretty well on the github site.

However, here comes the trick, as v-list-tile is not supported anymore by the current version of vuetify, I replaced all the v-list-tile with v-list-item - which I expected to be equivalent - but it is not and all the v-list-items are translated to the left until you can't see them on the screen without swiping.

So instead of hiding the swappable content and showing the main content, the whole content it translated to the left making the tile unvisible to the screen.

I would greatly appreciate if you could lend me a hand to understand what I am doing wrong.

Thanks and regards,

Pat

答:
I got it to work more or less, with the following component:

```<code><!-- components/VSwipable.vue -->

<template>
    <div ref="container" class="swiper-container">
        <div class="swiper-wrapper">
            <div v-if="swipeRight" class="swiper-slide">
                <slot name="right-content"/>
            </div>
            <div class="swiper-slide">
                <slot/>
            </div>
            <div v-if="swipeLeft" class="swiper-slide">
                <slot name="left-content"/>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
    import Swiper, { SelectableElement } from 'swiper';
    import 'swiper/css/swiper.css';
    import Vue from 'vue';

    export default Vue.extend({
        mounted() {
            const swiper = new Swiper(this.$refs.container as SelectableElement, {
                initialSlide: this.swipeRight ? 1 : 0,
                resistanceRatio: 0,
                speed: 150,
            });

            swiper.on('transitionEnd', () => {
                // slide index  swipe mode
                //   0   1       R
                //   0   1   2   R   L
                //       0   1   L
                switch (true) {
                    case this.swipeRight && swiper.activeIndex === 0:
                        this.$emit('swipedRight');
                        break;
                    case this.swipeRight && swiper.activeIndex === 2:
                        this.$emit('swipedLeft');
                        break;
                    case !this.swipeRight && swiper.activeIndex === 1:
                        this.$emit('swipedLeft');
                        break;
                    default:
                }

                switch (swiper.activeIndex) {
                    case 0:
                        this.$emit('swipedRight');
                        break;
                    case 2:
                        this.$emit('swipedLeft');
                        break;
                    default:
                }
            });
        },
        props: {
            swipeLeft: Boolean,
            swipeRight: Boolean,
        },
    });
</script>
</code>```

And example usage:

```<code><template>
    <v-container>
        <v-list>
            <template v-for="item in items">

                <!-- swipe-left enablesleft swiping (you can also use swipe-right), it supports two events: swipedLeft and swipedRight -->
                <v-swipable :key="item" swipe-left>

                    <!-- inject a red list item in the left slide -
                         you can also inject buttons and stuff,
                         use right-content for the right one -->
                    <v-list-item class="error" slot="left-content"/>

                    <v-list-item :value="item">
                        <v-list-item-content>
                            <v-list-item-title v-text="item"/>
                            <v-list-item-subtitle v-text="`Some details about ${item}`"/>
                        </v-list-item-content>
                    </v-list-item>

                </v-swipable>

            </template>
        </v-list>
    </v-container>
</template>

<script lang="ts">
    import VSwipable from '@/components/VSwipable.vue';

    export default Vue.extend({
        data: () => ({
            items: ['Item 1', 'Item 2', 'Item 3']
        }),
        components: {
            VSwipable,
        },
    });
</script>
</code>```

Title: Swipe in vuetify list items

Body:
I am trying to make a swipeable version of the vuetify list elements. I found the swiperjs.com library which does an awesome job in adding swiping capabilities for an html element. I also found this project https://github.com/davidgaroro/vuetify-swipeout which integrates the vuetify library and the swipeable library. Having read the content of the vuetify-swipeout project it looks like the trick is only in setting the right classes on the v-list-tile component, namely

 <v-list-tile class="swiper-slide">

while surrounding the element with

      ...

The demo works pretty well on the github site.

However, here comes the trick, as v-list-tile is not supported anymore by the current version of vuetify, I replaced all the v-list-tile with v-list-item - which I expected to be equivalent - but it is not and all the v-list-items are translated to the left until you can't see them on the screen without swiping.

So instead of hiding the swappable content and showing the main content, the whole content it translated to the left making the tile unvisible to the screen.

I would greatly appreciate if you could lend me a hand to understand what I am doing wrong.

Thanks and regards,

Pat

Body:
I got it to work more or less, with the following component:

<!-- components/VSwipable.vue -->

<template>
    <div ref="container" class="swiper-container">
        <div class="swiper-wrapper">
            <div v-if="swipeRight" class="swiper-slide">
                <slot name="right-content"/>
            </div>
            <div class="swiper-slide">
                <slot/>
            </div>
            <div v-if="swipeLeft" class="swiper-slide">
                <slot name="left-content"/>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
    import Swiper, { SelectableElement } from 'swiper';
    import 'swiper/css/swiper.css';
    import Vue from 'vue';

    export default Vue.extend({
        mounted() {
            const swiper = new Swiper(this.$refs.container as SelectableElement, {
                initialSlide: this.swipeRight ? 1 : 0,
                resistanceRatio: 0,
                speed: 150,
            });

            swiper.on('transitionEnd', () => {
                // slide index  swipe mode
                //   0   1       R
                //   0   1   2   R   L
                //       0   1   L
                switch (true) {
                    case this.swipeRight && swiper.activeIndex === 0:
                        this.$emit('swipedRight');
                        break;
                    case this.swipeRight && swiper.activeIndex === 2:
                        this.$emit('swipedLeft');
                        break;
                    case !this.swipeRight && swiper.activeIndex === 1:
                        this.$emit('swipedLeft');
                        break;
                    default:
                }

                switch (swiper.activeIndex) {
                    case 0:
                        this.$emit('swipedRight');
                        break;
                    case 2:
                        this.$emit('swipedLeft');
                        break;
                    default:
                }
            });
        },
        props: {
            swipeLeft: Boolean,
            swipeRight: Boolean,
        },
    });
</script>

And example usage:

<template>
    <v-container>
        <v-list>
            <template v-for="item in items">

                <!-- swipe-left enablesleft swiping (you can also use swipe-right), it supports two events: swipedLeft and swipedRight -->
                <v-swipable :key="item" swipe-left>

                    <!-- inject a red list item in the left slide -
                         you can also inject buttons and stuff,
                         use right-content for the right one -->
                    <v-list-item class="error" slot="left-content"/>

                    <v-list-item :value="item">
                        <v-list-item-content>
                            <v-list-item-title v-text="item"/>
                            <v-list-item-subtitle v-text="`Some details about ${item}`"/>
                        </v-list-item-content>
                    </v-list-item>

                </v-swipable>

            </template>
        </v-list>
    </v-container>
</template>

<script lang="ts">
    import VSwipable from '@/components/VSwipable.vue';

    export default Vue.extend({
        data: () => ({
            items: ['Item 1', 'Item 2', 'Item 3']
        }),
        components: {
            VSwipable,
        },
    });
</script>


问:
Using haarcascade to detect licence plates with OpenCV and Python
Im writing a code that will recognize licence plates on cars with a help of opencv and Python. For that Im using haarcascades. I downloaded haarcascades from here (if you have better source, please let me know):

https://github.com/opencv/opencv/tree/master/data/haarcascades

This is the image:

When I work with first haarcascade, it only detects licence plate on right car *(two times), but It does not recognize plates on white car.

When I work second haarcascade, it gives me error that I do not know what it means and how to fix it, this is the error:

```<code>cascadedetect.cpp:567: error: (-2:Unspecified error) in function 'bool __thiscall cv::HaarEvaluator::Feature::read(const class cv::FileNode &,const class cv::Size_<int> &)'
> Invalid HAAR feature (expected: 'rw.r.x < W'), where
>     'rw.r.x' is 32
> must be less than
>     'W' is 16

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\nenad\OneDrive\Desktop\open cv slika\Tablice\tablica.py", line 14, in <module>
    plates_cascade = cv2.CascadeClassifier('haarcascade_licence_plate_rus_16stages.xml')
SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set
</code>```

I do not think that the problem is because these haar cascades have russian licence plates, I have watched all over the web and russian licence plates look similar to other.
This is the code that I wrote:

```<code># Standard imports

import cv2
import numpy as np

# Read image
img = cv2.imread("slika2.jpg", 1)
gray = cv2.cvtColor(img, 0)
cv2.imshow('img', gray)
cv2.waitKey(0)

#read haarcascade
#plates_cascade = cv2.CascadeClassifier('haarcascade_russian_plate_number.xml') #does not give me error, but result is not correct
plates_cascade = cv2.CascadeClassifier('haarcascade_licence_plate_rus_16stages.xml') #gives me error

plates = plates_cascade.detectMultiScale(gray, 1.2, 4)

for (x,y,w,h) in plates:

    #detect plate with rectangle
    #rec. start point (x,y), rec. end point (x+w, y+h), blue color(255,0,0), line width 1

    plates_rec = cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 1)
    #cv2.putText(plates_rec, 'Text', (x, y-3), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)

    gray_plates = gray[y:y+h, x:x+w]
    color_plates = img[y:y+h, x:x+w]

    #cv2.imshow('img', gray_plates)
    #cv2.waitKey(0)

    height, width, chanel = gray_plates.shape
    print(height, width)

cv2.imshow('img', img)
cv2.waitKey(0)
print('Number of detected licence plates:', len(plates))
</code>```

Any suggestion how can I improve my code, and fix this?
Also, If you can tell me how to create my own haar cascade, I have looked all over the web but I couldnt find any solution that works.

答:
go to the haar casecade .xml file and change the value for the size.</p>

```<code><size> H W </size>
</code>```

Body:
Im writing a code that will recognize licence plates on cars with a help of opencv and Python. For that Im using haarcascades. I downloaded haarcascades from here (if you have better source, please let me know):

https://github.com/opencv/opencv/tree/master/data/haarcascades

This is the image:

When I work with first haarcascade, it only detects licence plate on right car *(two times), but It does not recognize plates on white car.

When I work second haarcascade, it gives me error that I do not know what it means and how to fix it, this is the error:

cascadedetect.cpp:567: error: (-2:Unspecified error) in function 'bool __thiscall cv::HaarEvaluator::Feature::read(const class cv::FileNode &,const class cv::Size_<int> &)'
> Invalid HAAR feature (expected: 'rw.r.x < W'), where
>     'rw.r.x' is 32
> must be less than
>     'W' is 16

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\nenad\OneDrive\Desktop\open cv slika\Tablice\tablica.py", line 14, in <module>
    plates_cascade = cv2.CascadeClassifier('haarcascade_licence_plate_rus_16stages.xml')
SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set

I do not think that the problem is because these haar cascades have russian licence plates, I have watched all over the web and russian licence plates look similar to other.
This is the code that I wrote:

# Standard imports

import cv2
import numpy as np

# Read image
img = cv2.imread("slika2.jpg", 1)
gray = cv2.cvtColor(img, 0)
cv2.imshow('img', gray)
cv2.waitKey(0)

#read haarcascade
#plates_cascade = cv2.CascadeClassifier('haarcascade_russian_plate_number.xml') #does not give me error, but result is not correct
plates_cascade = cv2.CascadeClassifier('haarcascade_licence_plate_rus_16stages.xml') #gives me error

plates = plates_cascade.detectMultiScale(gray, 1.2, 4)

for (x,y,w,h) in plates:

    #detect plate with rectangle
    #rec. start point (x,y), rec. end point (x+w, y+h), blue color(255,0,0), line width 1

    plates_rec = cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 1)
    #cv2.putText(plates_rec, 'Text', (x, y-3), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1)

    gray_plates = gray[y:y+h, x:x+w]
    color_plates = img[y:y+h, x:x+w]

    #cv2.imshow('img', gray_plates)
    #cv2.waitKey(0)

    height, width, chanel = gray_plates.shape
    print(height, width)

cv2.imshow('img', img)
cv2.waitKey(0)
print('Number of detected licence plates:', len(plates))

Any suggestion how can I improve my code, and fix this?
Also, If you can tell me how to create my own haar cascade, I have looked all over the web but I couldnt find any solution that works.

Body:
go to the haar casecade .xml file and change the value for the size.

<size> H W </size>


答:
You should use the json library:

import json

def json_to_dict(api_response):
    # I assume the api response is a string
    api_response_dict = json.loads(api_response)
    return api_response_dict
```

<p>This will create one dictionary with all of the contents. Then you can parse this dictionary and take only the key-value pairs that you care about:</p>

<pre class="lang-py prettyprint-override"><code>list_of_products = []
for product_group in api_response_dict['data']['styles']:
    for product in product_group['groups']:
        code = product['product'][0]['code']
        date = product['product'][0]['date']
        list_of_products.append((code, date))
</code>```

This was just an example.

Title: Parse JSON using Python

Body:
I am calling an API and I am getting a JSON response like the one above:

{
  "data": {
    "styles": [
      {
        "groups": [
          {
            "product": [
              {
                "code": "0000001",
                "date": null
              }
            ]
          },
          {
            "product": [
              {
                "code": "0000002",
                "date": "2020-05-02T00:00:00.000Z"
              }
            ]
          },
          {
            "product": [
              {
                "code": "0000003",
                "date": "2020-04-22T00:00:00.000Z"
              }
            ]
          }
        ]
      },
      {
        "groups": [
          {
            "product": [
              {
                "code": "0000011",
                "date": "2020-05-12T00:00:00.000Z"
              }
            ]
          },
          {
            "product": [
              {
                "code": "0000012",
                "date": "2020-05-12T00:00:00.000Z"
              }
            ]
          }
        ]
      }
    ]
  }
}

I am not familiar with handling JSON and this one is super nested. All I want to do is to create a tuple (or a dict) which would look like:

(0000001, null)
(0000002, 2020-05-02T00:00:00.000Z)
(0000003, 2020-04-22T00:00:00.000Z)
(0000011, 2020-05-12T00:00:00.000Z)
(0000012, 2020-05-12T00:00:00.000Z)

Could you please advice me one how to do that?

Body:
You should use the json library:

import json

def json_to_dict(api_response):
    # I assume the api response is a string
    api_response_dict = json.loads(api_response)
    return api_response_dict

This will create one dictionary with all of the contents. Then you can parse this dictionary and take only the key-value pairs that you care about:

list_of_products = []
for product_group in api_response_dict['data']['styles']:
    for product in product_group['groups']:
        code = product['product'][0]['code']
        date = product['product'][0]['date']
        list_of_products.append((code, date))

This was just an example.


问:
How to import entire folder to another?
This is what my folder looks like (both folders have empty __init__.py file:

```<code>.
├── Filter
│   ├── __init__.py
│   └── stp.py
└── Time
    ├── __init__.py
    └── event.py
</code>```

In event.py I currently have (which works):

```<code>from Filter.stp import *
</code>```

But I want to change it to (import entire folder since I have many more files in reality):

```<code>import Filter
</code>```

How can I do that?

答:
Does from Filter.stp import * work? I believe you'll be getting a module not found error. This is because you have to have the Filter folder inside Time folder. After that you can either use import or from import.

However if you can't move the folders  across then you've to add the path (Eg. C:/.../Filter) to your Filter folder

```<code>import sys
sys.path.append('C:/.../Filter') # include the full path

import stp # now you can import all the modules inside Filter
</code>```

Title: How to import entire folder to another?

Body:
This is what my folder looks like (both folders have empty __init__.py file:

.
├── Filter
│   ├── __init__.py
│   └── stp.py
└── Time
    ├── __init__.py
    └── event.py

In event.py I currently have (which works):

from Filter.stp import *

But I want to change it to (import entire folder since I have many more files in reality):

import Filter

How can I do that?

Body:
Does from Filter.stp import * work? I believe you'll be getting a module not found error. This is because you have to have the Filter folder inside Time folder. After that you can either use import or from import.

However if you can't move the folders  across then you've to add the path (Eg. C:/.../Filter) to your Filter folder

import sys
sys.path.append('C:/.../Filter') # include the full path

import stp # now you can import all the modules inside Filter


问:
Enable incoming connections from specified IP-address only
I have a server application with a listening socket opened on a specific IP port.
How can I allow the socket to enable incoming connections from just one specified IP address?</p>

答:
You'll have to either use some firewall software to restrict incoming requests to that port, or shut down accepted connections that you do not want to service (based on the socket address returned by accept).

There might be libraries out there that do that for you, but the socket API doesn't have anything to do it automatically.

ContentLicense: CC BY-SA 3.0


问:
How to use replaceAll when input contains spaces
I have a newbie question about replaceAll method on String. It works fine as long as the input does not contain any type of space (breaking/non-breaking etc).

How to sanitize the input so it covers all cases for special space characters and I can use something like this:

```<code>String replaced = replaced.replaceAll("my-test (2)", "test"); // not working
</code>```

I tried various types of regex with \\s, \u00A0 etc.

EDIT: I noticed that the braces are also causing some problems with replaceAll.

This is my case:

```<code>"my-value (2)".replaceAll("my-value (2)", "test);
</code>```

答:
First argument of replaceAll() method is regex. "my-test (2)" contains regex group "(2)".
so try to use something like replaced.replaceAll("my-test \\(2\\)", "test"));

Body:
I have a newbie question about replaceAll method on String. It works fine as long as the input does not contain any type of space (breaking/non-breaking etc).

How to sanitize the input so it covers all cases for special space characters and I can use something like this:

String replaced = replaced.replaceAll("my-test (2)", "test"); // not working

I tried various types of regex with \\s, \u00A0 etc.

EDIT: I noticed that the braces are also causing some problems with replaceAll.

This is my case:

"my-value (2)".replaceAll("my-value (2)", "test);


问:
How can i put an image as bg in Label widget so that the text is also visible
Actually the text THIS IS NOT VISIBLE is covered by the image.

```<code>image_caption = Label(canvas, text='THIS IS NOT VISIBLE', fg='brown', image=bg_image)
image_caption.grid(row=0, column=1, padx=20, pady=100)
</code>```

I want to keep text on an image so that image become bg of text instead of default white bg.

答:
Try using this compound = BOTTOM or compound = CENTER as an argument inside of Button()

```<code>image_caption = Label(canvas, text='THIS IS NOT VISIBLE', fg='brown',compound=CENTER, image=bg_image)
image_caption.grid(row=0, column=1, padx=20, pady=100)
</code>```

Body:
Actually the text THIS IS NOT VISIBLE is covered by the image.

image_caption = Label(canvas, text='THIS IS NOT VISIBLE', fg='brown', image=bg_image)
image_caption.grid(row=0, column=1, padx=20, pady=100)

I want to keep text on an image so that image become bg of text instead of default white bg.

Body:
Try using this compound = BOTTOM or compound = CENTER as an argument inside of Button()

image_caption = Label(canvas, text='THIS IS NOT VISIBLE', fg='brown',compound=CENTER, image=bg_image)
image_caption.grid(row=0, column=1, padx=20, pady=100)


答:
Your question is about parsing JSON with Python.

You can perform this using json.loads :

```<code>import json
my_string = '{"foo": "bar"}'
data = json.loads(my_string)
</code>```

However, it looks like you are using an API response. If your using requests (and you should), you can use

```<code>response = requests.get([...])
data = response.json()
</code>```

Title: Parse JSON using Python

Body:
Your question is about parsing JSON with Python.

You can perform this using json.loads :

import json
my_string = '{"foo": "bar"}'
data = json.loads(my_string)

However, it looks like you are using an API response. If your using requests (and you should), you can use

response = requests.get([...])
data = response.json()


问:
Ireports with jsp
I am new to Jasper reports(iReports).
Is there any tutorial to generate reports using iReport from JSP?

Thanks in advance!

答: JSF library exists for Jasper Reports. Look at here</p>

Title: Ireports with jsp


问:
Python - TensorFlow and Keras
I've been searching all about What is Tensorflow and Keras. They say that Tensorflow runs on top of Keras which means that Tensorflow is the "BACKEND" of KERAS.  (Although you can use others like Theano and CNTK)

Does the "BACKEND" term here mean it does the whole mathematical process thing behind a deep learning model ? What I mean is like Tensorflow is the one who does the complicated stuffs like processing the matrices (tensor) , doing all the math stuff?

On the other hand KERAS is the guy that is needed ONLY for us to create a MODEL, right?
and ONCE the model is created, its "BACKEND" is Tensorflow, right? cause for the MODEL TO WORK AS IT SHOULD BE (like process matrices and do all the math stuffs) it needs a "BACKEND" which is Tensorflow.

That is what I understand based on some open forums and the Keras documentation:

Keras is a model-level library, providing high-level building blocks for developing deep learning models. It does not handle itself low-level operations such as tensor products, convolutions and so on. Instead, it relies on a specialized, well-optimized tensor manipulation library to do so, serving as the “backend engine” of Keras.

Is my understanding correct? Please enlighten me if you have other answers.

答:
As of a greater version of TensorFlow (1.8) and all the later + latest versions of TensorFlow, Keras is integrated inside TensorFlow.

The recommended way to use Keras is to use it inside TensorFlow, practically if you import a layer you should do like from tensorflow.keras import X, Y.

Keras indeed is a high-level API which supports multiple back-end frameworks, such as Theano(which is obsolete by the way) or MXNET etc.

Since Keras was easier to use and a lot of people opted for Keras in spite of TensorFlow, whose learning curve was very poor in comparison with Keras, TensorFlow decided to integrate Keras inside their framework.

Practically, in the meantime, the creator of Keras became part of the Google development team, hence the integration of Keras inside TensorFlow.

If you are just staring with deep learning, ensure that you are using Keras inside TensorFlow. It is more robust, less prone to errors. In addition to this, Keras will enter maintenance mode (as of 2.3.X) no major version will be released anymore, only maintenance.

Title: Python - TensorFlow and Keras


问:
pivot rows certain values to columns
i have this table,

```<code>id activity type      start_date
1  a        type_o    01/01/20
1  b        type_o    05/01/20
1  c        type_o    07/01/20
1  d        type_o    23/01/20
1  e        type_o    24/01/20
2  a        type_k    08/01/20
2  b        type_k    10/01/20
2  c        type_k    11/01/20
2  d        type_k    12/01/20
3  a        type_h    12/01/20
3  c        type_h    13/01/20
3  e        type_h    14/01/20
</code>```

all activities are (a,b,c,d,e)
i want it to look like this,

```<code>id type     a         b         c         d         e
1  type_o   01/01/20  05/01/20  07/01/20  23/01/20  24/01/20
2  type_k   08/01/20  10/01/20  11/01/20  null      null
3  type_h   12/01/20  null      13/01/20  null      12/01/20
</code>```

where we compensate null in other activities not exists in some id's,
i don't understand the pivot keyword in sql, any help ?

答:
A more universal solution is to use CASE - WHEN statements.

The advantage is - the code is more portable across different SQL flavours and you can take care of duplicates in the records, if needed down the line.

```<code>select id,type
,case when activity = 'a' then  min(start_date) else null end as `a`
,case when activity = 'b' then  min(start_date) else null end as `b`
,case when activity = 'c' then  min(start_date) else null end as `c`
,case when activity = 'd' then  min(start_date) else null end as `d`
group by 1,2
</code>```

Title: pivot rows certain values to columns

Body:
i have this table,

id activity type      start_date
1  a        type_o    01/01/20
1  b        type_o    05/01/20
1  c        type_o    07/01/20
1  d        type_o    23/01/20
1  e        type_o    24/01/20
2  a        type_k    08/01/20
2  b        type_k    10/01/20
2  c        type_k    11/01/20
2  d        type_k    12/01/20
3  a        type_h    12/01/20
3  c        type_h    13/01/20
3  e        type_h    14/01/20

all activities are (a,b,c,d,e)
i want it to look like this,

id type     a         b         c         d         e
1  type_o   01/01/20  05/01/20  07/01/20  23/01/20  24/01/20
2  type_k   08/01/20  10/01/20  11/01/20  null      null
3  type_h   12/01/20  null      13/01/20  null      12/01/20

where we compensate null in other activities not exists in some id's,
i don't understand the pivot keyword in sql, any help ?

Body:
A more universal solution is to use CASE - WHEN statements.

The advantage is - the code is more portable across different SQL flavours and you can take care of duplicates in the records, if needed down the line.

select id,type
,case when activity = 'a' then  min(start_date) else null end as `a`
,case when activity = 'b' then  min(start_date) else null end as `b`
,case when activity = 'c' then  min(start_date) else null end as `c`
,case when activity = 'd' then  min(start_date) else null end as `d`
group by 1,2


问:
Recyclerview and OkHttp request synchronisation
I'm trying to fetch some data from LastFm API, process it, and display it in a recycler view. My problem is that because of the way my code is structured I think that I initialize my recycler view before data is fetched so nothing is being shown until I reopen my fragment and I don't know how to fix that.

Here is my fragment code:

```<code>public class TopArtistsFragment extends Fragment {

    private RecyclerView recyclerView;
    private ArtistRecyclerViewAdapter adapter;
    private TopArtistsViewModel mArtistsViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mArtistsViewModel = new ViewModelProvider(this).get(TopArtistsViewModel.class);

        mArtistsViewModel.init();

        mArtistsViewModel.getArtists().observe(this, new Observer<ArrayList<ArtistData>>() {
            @Override
            public void onChanged(ArrayList<ArtistData> artistData) {
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

       View view = inflater.inflate(R.layout.fragment_top_artists, container, false);
       recyclerView = view.findViewById(R.id.artistRecyclerView);

       return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initRecyclerView();
    }

    private void initRecyclerView() {
        adapter = new ArtistRecyclerViewAdapter(mArtistsViewModel.getArtists().getValue(), getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }
}
</code>```

This is my ViewModel:

```<code>public class TopArtistsViewModel extends ViewModel {

    private MutableLiveData<ArrayList<ArtistData>> mArtists;
    private ArtistDataRepository mRepo;

    public void init() {
        if(mArtists != null)
                return;
        mRepo = ArtistDataRepository.getInstance();
        mArtists = mRepo.getArtists();
    }

    public LiveData<ArrayList<ArtistData>> getArtists() {
        return mArtists;
    }
}
</code>```

And this is my repository where the work is being done:

```<code>public class ArtistDataRepository {
    private static ArtistDataRepository instance;
    private ArrayList<ArtistData> dataSet = new ArrayList<>();

    public static ArtistDataRepository getInstance() {
        if(instance == null)
            instance = new ArtistDataRepository();
        return instance;
    }

    public MutableLiveData<ArrayList<ArtistData>> getArtists() {
        setArtists();

        MutableLiveData<ArrayList<ArtistData>> data = new MutableLiveData<>();
        data.setValue(dataSet);
        return data;
    }

    private void setArtists () {
        fetchData();
    }

    private void fetchData () {
        final String requestUrl = "https://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=2124b8e156db20ac7a5035fad9c01b8e&format=json";

        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(requestUrl).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("NETWORK FAILURE", "Artist fetch");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                    parseData(response.body().string());
                else Log.d("OKHTTP", "Response not successful");
            }
        });
    }

    private void parseData (String queryResponse) {
        try {
            JSONArray artistResponse = new JSONObject(queryResponse).getJSONObject("artists").getJSONArray("artist");

            for(int i = 0; i < artistResponse.length(); i++) {
                JSONObject artist = artistResponse.getJSONObject(i);

                dataSet.add(new ArtistData(artist.getString("mbid"), artist.getString("playcount"), artist.getString("listeners"),
                        artist.getString("name"), artist.getJSONArray("image").getJSONObject(0).getString("#text")));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

I'm just a beginner so right now I'm basically trying to merge code from different tutorials into one. That's why some things you see here probably don't make sense, so please do tell me what I can fix.

答:
In order to tell the Recycleview that the data has come you need to get the Adapter and set its data then call adapter.notifyDataSetChanged();</p>

```<code> mArtistsViewModel.getArtists().observe(this, new Observer<ArrayList<ArtistData>>() {
            @Override
            public void onChanged(ArrayList<ArtistData> artistData) {
              -->  adapter.setData(artistData); // Something like that
                adapter.notifyDataSetChanged();
            }
        });
</code>```

Body:
I'm trying to fetch some data from LastFm API, process it, and display it in a recycler view. My problem is that because of the way my code is structured I think that I initialize my recycler view before data is fetched so nothing is being shown until I reopen my fragment and I don't know how to fix that.

Here is my fragment code:

public class TopArtistsFragment extends Fragment {

    private RecyclerView recyclerView;
    private ArtistRecyclerViewAdapter adapter;
    private TopArtistsViewModel mArtistsViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mArtistsViewModel = new ViewModelProvider(this).get(TopArtistsViewModel.class);

        mArtistsViewModel.init();

        mArtistsViewModel.getArtists().observe(this, new Observer<ArrayList<ArtistData>>() {
            @Override
            public void onChanged(ArrayList<ArtistData> artistData) {
                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

       View view = inflater.inflate(R.layout.fragment_top_artists, container, false);
       recyclerView = view.findViewById(R.id.artistRecyclerView);

       return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initRecyclerView();
    }

    private void initRecyclerView() {
        adapter = new ArtistRecyclerViewAdapter(mArtistsViewModel.getArtists().getValue(), getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }
}

This is my ViewModel:

public class TopArtistsViewModel extends ViewModel {

    private MutableLiveData<ArrayList<ArtistData>> mArtists;
    private ArtistDataRepository mRepo;

    public void init() {
        if(mArtists != null)
                return;
        mRepo = ArtistDataRepository.getInstance();
        mArtists = mRepo.getArtists();
    }

    public LiveData<ArrayList<ArtistData>> getArtists() {
        return mArtists;
    }
}

And this is my repository where the work is being done:

public class ArtistDataRepository {
    private static ArtistDataRepository instance;
    private ArrayList<ArtistData> dataSet = new ArrayList<>();

    public static ArtistDataRepository getInstance() {
        if(instance == null)
            instance = new ArtistDataRepository();
        return instance;
    }

    public MutableLiveData<ArrayList<ArtistData>> getArtists() {
        setArtists();

        MutableLiveData<ArrayList<ArtistData>> data = new MutableLiveData<>();
        data.setValue(dataSet);
        return data;
    }

    private void setArtists () {
        fetchData();
    }

    private void fetchData () {
        final String requestUrl = "https://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=2124b8e156db20ac7a5035fad9c01b8e&format=json";

        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(requestUrl).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("NETWORK FAILURE", "Artist fetch");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                    parseData(response.body().string());
                else Log.d("OKHTTP", "Response not successful");
            }
        });
    }

    private void parseData (String queryResponse) {
        try {
            JSONArray artistResponse = new JSONObject(queryResponse).getJSONObject("artists").getJSONArray("artist");

            for(int i = 0; i < artistResponse.length(); i++) {
                JSONObject artist = artistResponse.getJSONObject(i);

                dataSet.add(new ArtistData(artist.getString("mbid"), artist.getString("playcount"), artist.getString("listeners"),
                        artist.getString("name"), artist.getJSONArray("image").getJSONObject(0).getString("#text")));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

I'm just a beginner so right now I'm basically trying to merge code from different tutorials into one. That's why some things you see here probably don't make sense, so please do tell me what I can fix.

Body:
In order to tell the Recycleview that the data has come you need to get the Adapter and set its data then call adapter.notifyDataSetChanged();

 mArtistsViewModel.getArtists().observe(this, new Observer<ArrayList<ArtistData>>() {
            @Override
            public void onChanged(ArrayList<ArtistData> artistData) {
              -->  adapter.setData(artistData); // Something like that
                adapter.notifyDataSetChanged();
            }
        });


问:
Application Insights for WebAPI application
Is it possible to tell Application Insights to use a different InstrumentationKey depending on the request URL?

Our application works with different clients and we want to separate the logs for them in different instances of Application Insights.

Url format: https://webapi.com/v1/{client_name}/bla/bla

It would be great to setup configuration to select InstrumentationKey by client_name from request.

答:
Thanks to the answers from @cijothomas and @danpop (link) I was able to understand the whole picture.

Step 1: Create custom ITelemetryInitializer (Microsoft Documentation):

```<code>public class MyTelemetryInitializer : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        var appKey = CallContext.LogicalGetData("ApplicationKey")?.ToString();

        switch (appKey)
        {
            case "App1":
                telemetry.Context.InstrumentationKey = "d223527b-f34e-4c47-8aa8-1f21eb0fc349";
                return;
            default:
                telemetry.Context.InstrumentationKey = "f8ceb6cf-4357-4776-a2b6-5bbed8d2561c";
                return;
        }
    }
}
</code>```

Step 2: Register custom initializer:

```<code><ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
   <TelemetryInitializers>
     <Add Type="Application.WebAPI.MyTelemetryInitializer, Application.WebAPI"/>
   </TelemetryInitializers>
   <!--<InstrumentationKey>f8ceb6cf-4357-4776-a2b6-5bbed8d2561c</InstrumentationKey>-->
</ApplicationInsights>
</code>```

OR

```<code>protected void Application_Start()
{
    // ...
    TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
}
</code>```

Step 3: Make some adjustments to the logger (source code taken from @danpop answer Logger target configuration):

```<code>var config = new LoggingConfiguration();
ConfigurationItemFactory.Default.Targets.RegisterDefinition("ai", typeof());
ApplicationInsightsTarget aiTarget = new ApplicationInsightsTarget();
aiTarget.InstrumentationKey = "your_key";
aiTarget.Name = "ai";
config.AddTarget("ai", aiTarget);
LogManager.Configuration = config;
</code>```

ILogger configuration exmples: Log4Net, NLog, System.Diagnostics

Body:
Thanks to the answers from @cijothomas and @danpop (link) I was able to understand the whole picture.

Step 1: Create custom ITelemetryInitializer (Microsoft Documentation):

public class MyTelemetryInitializer : ITelemetryInitializer
{
    public void Initialize(ITelemetry telemetry)
    {
        var appKey = CallContext.LogicalGetData("ApplicationKey")?.ToString();

        switch (appKey)
        {
            case "App1":
                telemetry.Context.InstrumentationKey = "d223527b-f34e-4c47-8aa8-1f21eb0fc349";
                return;
            default:
                telemetry.Context.InstrumentationKey = "f8ceb6cf-4357-4776-a2b6-5bbed8d2561c";
                return;
        }
    }
}

Step 2: Register custom initializer:

<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
   <TelemetryInitializers>
     <Add Type="Application.WebAPI.MyTelemetryInitializer, Application.WebAPI"/>
   </TelemetryInitializers>
   <!--<InstrumentationKey>f8ceb6cf-4357-4776-a2b6-5bbed8d2561c</InstrumentationKey>-->
</ApplicationInsights>

OR

protected void Application_Start()
{
    // ...
    TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
}

Step 3: Make some adjustments to the logger (source code taken from @danpop answer Logger target configuration):

var config = new LoggingConfiguration();
ConfigurationItemFactory.Default.Targets.RegisterDefinition("ai", typeof());
ApplicationInsightsTarget aiTarget = new ApplicationInsightsTarget();
aiTarget.InstrumentationKey = "your_key";
aiTarget.Name = "ai";
config.AddTarget("ai", aiTarget);
LogManager.Configuration = config;

ILogger configuration exmples: Log4Net, NLog, System.Diagnostics


答: When you accept a connection you can examine the sockaddr after accepting to see if it came from the right address.  If not you immediately close the connect socket returned by accept.</p>

Title: Enable incoming connections from specified IP-address only

Body:
I have a server application with a listening socket opened on a specific IP port.
How can I allow the socket to enable incoming connections from just one specified IP address?


答:
I would use here:

```<code>String input = "my-value (2)";
String output = input.replaceAll("\\bmy-value\\s*\\(2\\)(?!\\S)", "test");
System.out.println(output);
</code>```

This prints: test

Here is an explanation of the regex pattern:

```<code>\b        word boundary
my-value  match "my-value"
\s*       zero or more whitespace characters
\(2\)     match "(2)"
(?!\S)    assert that what follows is either whitespace or the end of the input
</code>```

Title: How to use replaceAll when input contains spaces

Body:
I would use here:

String input = "my-value (2)";
String output = input.replaceAll("\\bmy-value\\s*\\(2\\)(?!\\S)", "test");
System.out.println(output);

This prints: test

Here is an explanation of the regex pattern:

\b        word boundary
my-value  match "my-value"
\s*       zero or more whitespace characters
\(2\)     match "(2)"
(?!\S)    assert that what follows is either whitespace or the end of the input


问:
Spark PySpark output JSON with one column value as key
If I have a simple table in dataframe with schema:

```<code>a string, b string, c string
</code>```

for example:

```<code>a     b      c
cat   3-3    78-b
cat   3-3    89-0
cat   4-4    78-n
dog   4-4    89-b
</code>```

And so on.
I would want to partition this table by column a and save each partition as separate JSON.

Further I would want the each partition as a JSON file with value in column b as key. For example:

```<code>File cat.json:
     {
       "3-3": {"b": "3-3", "c": "78-b"},
       "3-3": {"b": "3-3", "c": "89-0"},
       "4-4": {"b": "4-4", "c": "78-n"}
     }
File dog.json:
     {
       "4-4": {"b": 4-4, "c": "89-b"}
     }
</code>```

Is there a way to do this in pyspark? Thanks

Body:
If I have a simple table in dataframe with schema:

a string, b string, c string

for example:

a     b      c
cat   3-3    78-b
cat   3-3    89-0
cat   4-4    78-n
dog   4-4    89-b

And so on.
I would want to partition this table by column a and save each partition as separate JSON.

Further I would want the each partition as a JSON file with value in column b as key. For example:

File cat.json:
     {
       "3-3": {"b": "3-3", "c": "78-b"},
       "3-3": {"b": "3-3", "c": "89-0"},
       "4-4": {"b": "4-4", "c": "78-n"}
     }
File dog.json:
     {
       "4-4": {"b": 4-4, "c": "89-b"}
     }

Is there a way to do this in pyspark? Thanks

Body:
Try using below solution-

1. Load the data

 val data =
      """
        |a    | b   |   c
        |cat  | 3-3 |   78-b
        |cat  | 3-3 |   89-0
        |cat  | 4-4 |   78-n
        |dog  | 4-4 |   89-b
      """.stripMargin
    val stringDS = data.split(System.lineSeparator())
      .map(_.split("\\|").map(_.replaceAll("""^[ \t]+|[ \t]+$""", "")).mkString(","))
      .toSeq.toDS()
    val df = spark.read
      .option("sep", ",")
      .option("inferSchema", "true")
      .option("header", "true")
      .csv(stringDS)
    df.show(false)
    df.printSchema()
    /**
      * +---+---+----+
      * |a  |b  |c   |
      * +---+---+----+
      * |cat|3-3|78-b|
      * |cat|3-3|89-0|
      * |cat|4-4|78-n|
      * |dog|4-4|89-b|
      * +---+---+----+
      *
      * root
      * |-- a: string (nullable = true)
      * |-- b: string (nullable = true)
      * |-- c: string (nullable = true)
      */

2. Create Map as required

  val processedDF = df
        .groupBy("a")
        .agg(
          collect_list(struct(col("b"), col("c"))).as("value"),
          collect_list(col("b")).as("key")
        )
      .withColumn("map", map_from_arrays(col("key"), col("value")))

    processedDF.show(false)
    processedDF.printSchema()

    /**
      * +---+---------------------------------------+---------------+------------------------------------------------------------+
      * |a  |value                                  |key            |map                                                         |
      * +---+---------------------------------------+---------------+------------------------------------------------------------+
      * |cat|[[3-3, 78-b], [3-3, 89-0], [4-4, 78-n]]|[3-3, 3-3, 4-4]|[3-3 -> [3-3, 78-b], 3-3 -> [3-3, 89-0], 4-4 -> [4-4, 78-n]]|
      * |dog|[[4-4, 89-b]]                          |[4-4]          |[4-4 -> [4-4, 89-b]]                                        |
      * +---+---------------------------------------+---------------+------------------------------------------------------------+
      *
      * root
      * |-- a: string (nullable = true)
      * |-- value: array (nullable = true)
      * |    |-- element: struct (containsNull = true)
      * |    |    |-- b: string (nullable = true)
      * |    |    |-- c: string (nullable = true)
      * |-- key: array (nullable = true)
      * |    |-- element: string (containsNull = true)
      * |-- map: map (nullable = true)
      * |    |-- key: string
      * |    |-- value: struct (valueContainsNull = true)
      * |    |    |-- b: string (nullable = true)
      * |    |    |-- c: string (nullable = true)
      */

3. save the dataframe

 processedDF.select(col("a"), to_json(col("map"))).write
      .mode(SaveMode.Overwrite)
      .partitionBy("a")
      .text("/Users/sokale/models/run_2")

    /**
      * File directory and content of file
      * a=cat
      * |-  {"3-3":{"b":"3-3","c":"78-b"},"3-3":{"b":"3-3","c":"89-0"},"4-4":{"b":"4-4","c":"78-n"}}
      * a=dog
      * |-  {"4-4":{"b":"4-4","c":"89-b"}}
      */


问:
typeorm config with .env variables
i have this ormconfig.json:

```<code>{
  "type": "postgres",
  "host": "db-pg",
  "port": 5432,
  "username": "spirit",
  "password": "api",
  "database": "emasa_ci",
  "synchronize": true,
  "logging": false,
  "entities": ["dist/src/entity/**/*.js"],
  "migrations": ["dist/src/migration/**/*.js"],
  "subscribers": ["dist/src/subscriber/**/*.js"],
  "cli": {
    "entitiesDir": "dist/src/entity",
    "migrationsDir": "dist/src/migration",
    "subscribersDir": "dist/src/subscriber"
  }
}
</code>```

and have this env:

```<code>SERVER_PORT=4000
DB_HOST=db-pg
DB_PORT=5432
DB_USER=spirit
DB_PASS=api
DB_NAME=emasa_ci
</code>```

but .env doesn't work in .json and so I don't know how I'm going to use my enviroment variables in my config orm

答: You could hide ormconfig.json and put your secrets directly in there, or viceversa, load TypeORM's configuration from your .env file. Is there a precise reason why you need them to be separated? If yes, then we can work out a solution.

Title: typeorm config with .env variables

Body:
i have this ormconfig.json:

{
  "type": "postgres",
  "host": "db-pg",
  "port": 5432,
  "username": "spirit",
  "password": "api",
  "database": "emasa_ci",
  "synchronize": true,
  "logging": false,
  "entities": ["dist/src/entity/**/*.js"],
  "migrations": ["dist/src/migration/**/*.js"],
  "subscribers": ["dist/src/subscriber/**/*.js"],
  "cli": {
    "entitiesDir": "dist/src/entity",
    "migrationsDir": "dist/src/migration",
    "subscribersDir": "dist/src/subscriber"
  }
}

and have this env:

SERVER_PORT=4000
DB_HOST=db-pg
DB_PORT=5432
DB_USER=spirit
DB_PASS=api
DB_NAME=emasa_ci

but .env doesn't work in .json and so I don't know how I'm going to use my enviroment variables in my config orm


问:
onEdit / onForm submit - code initiated but no action
I have set up a function to send an email to my email when any change is made, so I can be notified when a maintenance request is added to the sheet. I want to set it up so my trigger only occurs when a certain column (in this case A) or row is changed - as I wasn't receiving notifications with on Form Submit for some reason.

Here is my code -

```<code>function onEdit(e){
var range = e.range; if (range.getColumn() === A && range.getRow() === observedCellRow) {

sendEmail(); MailApp.sendEmail('connor@singapm.com','Email Subject','Email Message' } }
</code>```

What else needs to be included in this code to get an email when 'A' Column is changed/added to? Please note I have no experience whatsoever in scripting. Thanks in advance.

答:
1. You cannot fire an onEdit trigger on FormSubmit

onEdit only detects edits that have been performed by a human, not form submissions .

If you want to fire your function when a new form submission takes place, please bind the installable trigger onFormSubmit to your function.

You can do so by going to Edit->Current Project triggers and selecting + Add Trigger.

If you want your function to fire both on (human-made) edit and on form submisison - you can have more than one trigger bound to the same function.

2.You cannot send an email triggered by a simple onEdit trigger

See Restrictions

They [simple triggers] cannot access services that require authorization. For example, a
  simple trigger cannot send an email because the Gmail service requires
  authorization.

So, to run your function onEdit please install the installable version of the onEdit instead of the simple one.

Please rename your function in order to deactivate the simple onEdit trigger (having both the simple and installable onEdit triggered active simultaneously can lead to not desired behavior).

Body:
I have set up a function to send an email to my email when any change is made, so I can be notified when a maintenance request is added to the sheet. I want to set it up so my trigger only occurs when a certain column (in this case A) or row is changed - as I wasn't receiving notifications with on Form Submit for some reason.

Here is my code -

function onEdit(e){
var range = e.range; if (range.getColumn() === A && range.getRow() === observedCellRow) {

sendEmail(); MailApp.sendEmail('connor@singapm.com','Email Subject','Email Message' } }

What else needs to be included in this code to get an email when 'A' Column is changed/added to? Please note I have no experience whatsoever in scripting. Thanks in advance.


问:
Check keys' expire times through the redis-cli
I have a question about Redis caching.
I wrote some code to cache some information and it works fine, but is there a way to check what's being stored inside of it through redis-cli? I just want to make sure that the value gets deleted after 10 minutes.

how I store stuff:

Cache::store('redis')->put('inventory_' . $this->user->steamid64, $items, 15);

答:
Enter the redis-cli and use:

keys * to see list of all keys

TTL my_key_name to see remaining expire time of the key

You can execute any of Redis commands inside of the redis-cli. It's good tool for development.


答:
This code is not going to compile. which IDE are you using? You are not even initialize the variable replaced and replaceAll() method uses regular expression. change replaceAll() to replace(). Try something like this.

```<code>String replaced = "my-test (2)";
replaced = replaced.replace("my-test (2)", "test");
System.out.println(replaced);
</code>```

Body:
This code is not going to compile. which IDE are you using? You are not even initialize the variable replaced and replaceAll() method uses regular expression. change replaceAll() to replace(). Try something like this.

String replaced = "my-test (2)";
replaced = replaced.replace("my-test (2)", "test");
System.out.println(replaced);


问:
Widget under a QTabBar with unwanted frame
I have a problem with QTabBar/QTabWidget. This is what my program looks like at the moment, using QTabBar:

As you can see, there is an unsightly line between the QTabBar and the QScrollArea underneath it. This line is part of the frame of the QScrollArea, which I can't simply get rid of, because it is required on the other three sides. I realise I could use QTabWidget, but then I would have to create a widget for each tab, which is not feasible here: the contents of the QScrollArea change according to the selected tab, but there is only one QScrollArea widget. (Duplicating it each time a new tab is created would cause its own problems.)

So does anybody know a way to either:

(i) tell the QScrollArea to draw a frame without the top line; or

(ii) use the same widget for each tab in a QTabWidget?

Update 3 For another approach, see my answer below.

Update 1 I have implemented zvezdi's suggestion, and the unsightly line has disappeared:

This is an improvement. But it's not right. Look at the gaps between the scroll bars and the border. On the right, it's two pixels instead of one; on the bottom, it's three pixels. And the gap on the right between the QScrollArea border and the mainWidget border is one pixel too big. This is due to QTabWidget's border style, which I am losing my sanity trying to change. If I say:

```<code>MyTabWidget -> setStyleSheet ("QTabWidget::pane { margin: 0px,0px,0px,0px }") ;
</code>```

then the margins seem to be right, but the borders disappear:

If I say:

```<code>MyTabWidget -> setStyleSheet ("QTabWidget::pane { "
  " margin: 0px,0px,0px,0px;"
  " border: 1px solid darkgray;"
  "}") ;
</code>```

then I'm almost back to where I started:

If I try to remedy this with:

```<code>ApplicationTabWidget -> setStyleSheet ("QTabWidget::pane { "
"   margin: 0px,0px,0px,0px;"
" border: 1px solid darkgray;"
" border-top: 0px;"
      "}") ;
</code>```

then again I am mocked for my pains:

Update 2 If I forget setStyleSheet and just turn documentMode on, this is what I get:

Please somebody, tell me I'm being stupid, and there's a perfectly simple solution to all this.

答:
You said "the contents of the QScrollArea change according to the selected tab" well if I assume that this is not true, and what you mean is that the content of the widget that is inside the scroll area changes, then you can try this:

Make as many QScrollArea objects as many tabs you need in your QTabWidget, but only one, for example QTextEdit, which you will show in every scroll area, and which content will change on tab change (takeWidget() from the old tab's QScrollArea & setWidget() on the new tab's QScrollArea)

I don't know how you've designed your code, but to try my suggestion your code should be designed around the widget inside QScrollArea, rather than the QScrollArea itself.

Body:
I have a problem with QTabBar/QTabWidget. This is what my program looks like at the moment, using QTabBar:

As you can see, there is an unsightly line between the QTabBar and the QScrollArea underneath it. This line is part of the frame of the QScrollArea, which I can't simply get rid of, because it is required on the other three sides. I realise I could use QTabWidget, but then I would have to create a widget for each tab, which is not feasible here: the contents of the QScrollArea change according to the selected tab, but there is only one QScrollArea widget. (Duplicating it each time a new tab is created would cause its own problems.)

So does anybody know a way to either:

(i) tell the QScrollArea to draw a frame without the top line; or

(ii) use the same widget for each tab in a QTabWidget?

Update 3 For another approach, see my answer below.

Update 1 I have implemented zvezdi's suggestion, and the unsightly line has disappeared:

This is an improvement. But it's not right. Look at the gaps between the scroll bars and the border. On the right, it's two pixels instead of one; on the bottom, it's three pixels. And the gap on the right between the QScrollArea border and the mainWidget border is one pixel too big. This is due to QTabWidget's border style, which I am losing my sanity trying to change. If I say:

MyTabWidget -> setStyleSheet ("QTabWidget::pane { margin: 0px,0px,0px,0px }") ;

then the margins seem to be right, but the borders disappear:

If I say:

MyTabWidget -> setStyleSheet ("QTabWidget::pane { "
  " margin: 0px,0px,0px,0px;"
  " border: 1px solid darkgray;"
  "}") ;

then I'm almost back to where I started:

If I try to remedy this with:

ApplicationTabWidget -> setStyleSheet ("QTabWidget::pane { "
"   margin: 0px,0px,0px,0px;"
" border: 1px solid darkgray;"
" border-top: 0px;"
      "}") ;

then again I am mocked for my pains:

Update 2 If I forget setStyleSheet and just turn documentMode on, this is what I get:

Please somebody, tell me I'm being stupid, and there's a perfectly simple solution to all this.