问:
Gson ignore null when deserializing object
I want to deserialize a json string that containts a null value in Java. I want to deserialize the object to a Properties object. The json string is something like:

```<code>{"prop1":null, "propr2":"fancy value"}
</code>```

When I deserialize using

```<code>String json = //
new Gson().fromJson(json, Properties.class);
</code>```

I get a null pointer exception because of the Hastable that into the Properties object. How can I instruct Gson to ignore deserialization of null values?

答:
We have this solution:

1. All of your data classes need to extends abstract class

```<code>abstract class PoJoClass
</code>```

2. Create this safe deserializer to delete nulls from JSON

```<code>class SafeDeserializer<T : PoJoClass>(private val gson: Gson) :JsonDeserializer<T> {
    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): T {

        val jsonObject = json as JsonObject
        removeNullsFromJson(jsonObject)
        return gson.fromJson(jsonObject, typeOfT)
    }

    private fun removeNullsFromJson(jsonObject: JsonObject) {
        val iterator = jsonObject.keySet().iterator()

        while (iterator.hasNext()) {
            val key = iterator.next()
            when(val json = jsonObject[key]){
                is JsonObject -> removeNullsFromJson(json)
                is JsonNull -> iterator.remove()
            }
        }
    }
}
</code>```

3. And register it in your GSON instance

```<code>val gson = Gson().newBuilder()
                .registerTypeHierarchyAdapter(PoJoClass::class.java, SafeDeserializer<PoJoClass>(Gson()))
                .create()
</code>```

Body:
I want to deserialize a json string that containts a null value in Java. I want to deserialize the object to a Properties object. The json string is something like:

{"prop1":null, "propr2":"fancy value"}

When I deserialize using

String json = //
new Gson().fromJson(json, Properties.class);

I get a null pointer exception because of the Hastable that into the Properties object. How can I instruct Gson to ignore deserialization of null values?

Body:
We have this solution:

1. All of your data classes need to extends abstract class

abstract class PoJoClass

2. Create this safe deserializer to delete nulls from JSON

class SafeDeserializer<T : PoJoClass>(private val gson: Gson) :JsonDeserializer<T> {
    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): T {

        val jsonObject = json as JsonObject
        removeNullsFromJson(jsonObject)
        return gson.fromJson(jsonObject, typeOfT)
    }

    private fun removeNullsFromJson(jsonObject: JsonObject) {
        val iterator = jsonObject.keySet().iterator()

        while (iterator.hasNext()) {
            val key = iterator.next()
            when(val json = jsonObject[key]){
                is JsonObject -> removeNullsFromJson(json)
                is JsonNull -> iterator.remove()
            }
        }
    }
}

3. And register it in your GSON instance

val gson = Gson().newBuilder()
                .registerTypeHierarchyAdapter(PoJoClass::class.java, SafeDeserializer<PoJoClass>(Gson()))
                .create()


来源: stackexchange

问:
Call to undefined method Maatwebsite\Excel\Excel::create() in Laravel 5.8
I am using Laravel 5.8 and maatwebsite/excel 3.1 to export to Excel but got an error.

Call to undefined method Maatwebsite\Excel\Excel::create()

I have written export code in Controller and View

config/app.php

```<code>        /*
         * Package Service Providers...
         */
Maatwebsite\Excel\ExcelServiceProvider::class,

//Class Aliases
'Excel' => Maatwebsite\Excel\Facades\Excel::class,

</code>```

Controller

```<code>use Excel;

     public function msisdnExport()
    {
     $msisdns = User::select(
               "phone"
             )
               ->get();

     // Initialize the array which will be passed into the Excel
     // generator.
     $msisdnsArray = [];

     // Define the Excel spreadsheet headers
     $msisdnsArray[] = ['MSISDN'];

     // Convert each member of the returned collection into an array,
     // and append it to the payments array.
     foreach ($msisdns as $msisdn) {
          $msisdnsArray[] = $msisdn->toArray();
     }

     // Generate and return the spreadsheet
    // Excel::create('MSISDN', function($excel) use ($msisdnsArray) {
        Excel::download('MSISDN', function($excel) use ($msisdnsArray) {

          // Set the spreadsheet title, creator, and description
          $excel->setTitle('MSISDN');
          $excel->setCreator('Developers')->setCompany('Cloud Africa');
          $excel->setDescription('users msisdn file');

          // Build the spreadsheet, passing in the payments array
          $excel->sheet('sheet1', function($sheet) use ($msisdnsArray) {
               $sheet->fromArray($msisdnsArray, null, 'A1', false, false);
          });

     })->download('xlsx');
}
</code>```

View

```<code><a href="{{ route('msisdn-export') }}" class="btn btn-block btn-primary" style="margin-right: 15px;"><i class="fa fa-file-excel-o"></i> Excel</a>
</code>```

When I click on Excel in view, it suppose to export to excel but got this error.

Call to undefined method Maatwebsite\Excel\Excel::create()

答:
The create method has been removed. You have to use one of the following:

```<code>Excel::download($yourExport);
Excel::store($yourExport);
</code>```

As stated in the upgrade guide:

Excel::create() is removed and replaced by Excel::download/Excel::store($yourExport)

Source: https://docs.laravel-excel.com/3.1/getting-started/upgrade.html#upgrading-to-3-from-2-1

ContentLicense: CC BY-SA 4.0

Body:
I am using Laravel 5.8 and maatwebsite/excel 3.1 to export to Excel but got an error.

Call to undefined method Maatwebsite\Excel\Excel::create()

I have written export code in Controller and View

config/app.php

        /*
         * Package Service Providers...
         */
Maatwebsite\Excel\ExcelServiceProvider::class,

//Class Aliases
'Excel' => Maatwebsite\Excel\Facades\Excel::class,

Controller

use Excel;

     public function msisdnExport()
    {
     $msisdns = User::select(
               "phone"
             )
               ->get();

     // Initialize the array which will be passed into the Excel
     // generator.
     $msisdnsArray = [];

     // Define the Excel spreadsheet headers
     $msisdnsArray[] = ['MSISDN'];

     // Convert each member of the returned collection into an array,
     // and append it to the payments array.
     foreach ($msisdns as $msisdn) {
          $msisdnsArray[] = $msisdn->toArray();
     }

     // Generate and return the spreadsheet
    // Excel::create('MSISDN', function($excel) use ($msisdnsArray) {
        Excel::download('MSISDN', function($excel) use ($msisdnsArray) {

          // Set the spreadsheet title, creator, and description
          $excel->setTitle('MSISDN');
          $excel->setCreator('Developers')->setCompany('Cloud Africa');
          $excel->setDescription('users msisdn file');

          // Build the spreadsheet, passing in the payments array
          $excel->sheet('sheet1', function($sheet) use ($msisdnsArray) {
               $sheet->fromArray($msisdnsArray, null, 'A1', false, false);
          });

     })->download('xlsx');
}

View

 Excel

When I click on Excel in view, it suppose to export to excel but got this error.

Call to undefined method Maatwebsite\Excel\Excel::create()

Body:
The create method has been removed. You have to use one of the following:

Excel::download($yourExport);
Excel::store($yourExport);

As stated in the upgrade guide:

Excel::create() is removed and replaced by Excel::download/Excel::store($yourExport)

Source: https://docs.laravel-excel.com/3.1/getting-started/upgrade.html#upgrading-to-3-from-2-1


问:
OpenCover not finding solution modules
I'm trying to use OpenCover to produce some code coverage reports for my solution.  I've got it running with assistance from this blog post http://www.allenconway.net/2015/06/using-opencover-and-reportgenerator-to.html, but it's currently not identifying and loading the modules which I want to report on.

Here is what I'm executing:

```<code>"%~dp0..\packages\OpenCover.4.7.922\tools\OpenCover.Console.exe" ^
-register:user ^
-target:"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\mstest.exe" ^
-targetargs:"/testcontainer:\"%~dp0..\My.Project_Tests\bin\Debug\My.Project_Tests.dll\" /resultsfile:\"%~dp0My.Project.trx\"" ^
-filter:"+[My.Project*]* -[My.Project_Tests]*" ^
-mergebyhash ^
-skipautoprops ^
-output:"%~dp0\GeneratedReports\WebsiteReport.xml"
</code>```

The output I get:

```<code>No tests to execute.
Committing...
No results, this could be for a number of reasons. The most common reasons are:
1) missing PDBs for the assemblies that match the filter please review the
output file and refer to the Usage guide (Usage.rtf) about filters.
2) the profiler may not be registered correctly, please refer to the Usage
guide and the -register switch.
</code>```

I've tried changing the filter to include everything:

```<code>-filter:"+[*]*"
</code>```

This finds and reports on code coverage within the test project, but doesn't manage to identify or report on coverage in any of the referenced projects which I actually want to test (My.Project).

The projects are all being built and .pdb files are present in the bin folder of the test project.

I would like code coverage reports from all projects referenced by my test project.  Does anyone have any idea what's going wrong?

答:
Turns out that I'm an idiot and was running MSTest when I should have been running NUnit console since our tests are all using NUnit.

Posting this just in case it helps someone else out.

Title: OpenCover not finding solution modules

Body:
I'm trying to use OpenCover to produce some code coverage reports for my solution.  I've got it running with assistance from this blog post http://www.allenconway.net/2015/06/using-opencover-and-reportgenerator-to.html, but it's currently not identifying and loading the modules which I want to report on.

Here is what I'm executing:

"%~dp0..\packages\OpenCover.4.7.922\tools\OpenCover.Console.exe" ^
-register:user ^
-target:"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\mstest.exe" ^
-targetargs:"/testcontainer:\"%~dp0..\My.Project_Tests\bin\Debug\My.Project_Tests.dll\" /resultsfile:\"%~dp0My.Project.trx\"" ^
-filter:"+[My.Project*]* -[My.Project_Tests]*" ^
-mergebyhash ^
-skipautoprops ^
-output:"%~dp0\GeneratedReports\WebsiteReport.xml"

The output I get:

No tests to execute.
Committing...
No results, this could be for a number of reasons. The most common reasons are:
1) missing PDBs for the assemblies that match the filter please review the
output file and refer to the Usage guide (Usage.rtf) about filters.
2) the profiler may not be registered correctly, please refer to the Usage
guide and the -register switch.

I've tried changing the filter to include everything:

-filter:"+[*]*"

This finds and reports on code coverage within the test project, but doesn't manage to identify or report on coverage in any of the referenced projects which I actually want to test (My.Project).

The projects are all being built and .pdb files are present in the bin folder of the test project.

I would like code coverage reports from all projects referenced by my test project.  Does anyone have any idea what's going wrong?


问:
How do you debug heavily templated code in c++?
I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.

What tips or advice can you offer when trying to figure out why something is not compiling other than just picking through the code manually and hoping it will come to me?

答:
You get used to it as time goes by, and unfortunately if you plan on using C++, you have to.
Because, some libraries like VC9 have good error messages, but as soon as you move to say GCC, or some other compiler, the messages are gone. And even VC9 won't help you much when you have errors from some library written by someone else, or yourself during a late-night, even some Boost libraries aren't that friendly. Simply because not every author has taken the trouble to make things clear when an error occurs, and that is even more common with new libraries (that tend to have the most errors and less help).

Also you must remember that the nice STATIC_ERRORS you may find here and there in code, are placed by the authors where things commonly break, and there will always be horrible corner cases, that the author didn't contemplate, that will produce 400 lines of error messages because you missed a const somewhere for example.

Using tools will help you out in the beginning, but hurt you on the long run. And since the problem is inherent of C++, its not going away any day soon. And these walls of errors will likely be with us until C++ is no longer in use. So tools will just cut your teeth, when you need them to survive. If you planning on leaving C++ soon, then please feel free to use them. Nowadays I can normally understand those 400-line error messages in one glance, so they are crystal clear to my eyes, but thats not thanks to any tools.

As with everything, especially C++, it takes experience and training.

OwnerDisplayName: Dan

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: David Segonds

OwnerDisplayName: Robert Gould


问:
Problem in porting Chicken of VNC Mac application into iphone application
I'm porting Chicken of VNC Mac application into iphone application

I am having source code of Chicken of VNC Mac application which take vnc of any LAN connected mac. I have to do same with iphone app. So while debugging mac source code I am not able to figure out how that mac app establish an authenticated VNC connection?

My Current Progress
I have done some progress. Now i am able to connect any LAN connected MAC and can take VNC of it. But i think the way i am doing is wrong. Actually now i am calling unstoppable timer again & again for [conn startTalking] and making RFBConnection with server on every mseconds for uninterrupted connection. Is this is a right way ? But this arise a new problem i cannot scroll my vnc view because on every mseconds screen is refreshing with new RFBConnection. Can any one guide me ?

Its pretty strange that none of experts are sharing their views on
  this thread

答: See section 7.1 (handshaking messages) and 7.2 (security types) of this page describing the RFB protocol.</p>

ContentLicense: CC BY-SA 3.0


问:
How to calculate the consecutive sum of number in a string?
I would like to find the sum of integer in string. For example:

```<code>String myString= "The price is 345and the tax1 is 12sales";
String output = "The price is 12and the tax1 is 3sales";
</code>```

I found few approaches none is displaying the final output the way I need.

```<code>int sum = 0;
for (int I =0; i < myString.lengh(); i++)
{
   char c = myString.charAt(i);
   if(Character.isDigit(c))
   {
      int value = Integer.parseInt(String.valueOf(c));
   }
}
</code>```

I am getting the total sum but I would like to be able to append the string with individual sums.
    output = "The price is 12and the tax1 is 3sales"

答:
add an if statement checking the next character for a digit, if it's a digit add it, otherwise you are done and can print it.
However, your input is quite unusual, are you sure you can not improve the input itself?</p>

Body:
I would like to find the sum of integer in string. For example:

String myString= "The price is 345and the tax1 is 12sales";
String output = "The price is 12and the tax1 is 3sales";

I found few approaches none is displaying the final output the way I need.

int sum = 0;
for (int I =0; i < myString.lengh(); i++)
{
   char c = myString.charAt(i);
   if(Character.isDigit(c))
   {
      int value = Integer.parseInt(String.valueOf(c));
   }
}

I am getting the total sum but I would like to be able to append the string with individual sums.
    output = "The price is 12and the tax1 is 3sales"


问:
catching response of post request after post's succeeded
I am creating a post request and it's executing successfully and I can see that response in the network tab.

I am trying to store that response so that I can use that further ahead, but I am not able to do so. I don't exactly know how can I store that response, can anyone guide me about that?

I have created a post like below sample and I was trying to put .then after but I think it just hadn't worked for me.

```<code>const current = api();
await current.post(`/sampleUrl`,formData);
</code>```

答:
Which module are you using for POST requests?

In request this saves the response. This might do it for you.

```<code>const request = require("request");
const response = request.post(data);
</code>```

Body:
I am creating a post request and it's executing successfully and I can see that response in the network tab.

I am trying to store that response so that I can use that further ahead, but I am not able to do so. I don't exactly know how can I store that response, can anyone guide me about that?

I have created a post like below sample and I was trying to put .then after but I think it just hadn't worked for me.

const current = api();
await current.post(`/sampleUrl`,formData);

Body:
Which module are you using for POST requests?

In request this saves the response. This might do it for you.

const request = require("request");
const response = request.post(data);


问:
Environment variables containing newlines in Node?
I'm attempting to load an RSA private key into my nodejs application using environment variables, but the newlines seem to be being auto-escaped.

For the following, assume that the PRIVATE_KEY env var is set to the following (not my actual key):

```<code>PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp\nwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5\n1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh\n3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2\npIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX\nGukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il\nAkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF\nL0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k\nX6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl\nU9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ\n37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=\n-----END RSA PRIVATE KEY-----"
</code>```

If I call console.log directly with the preceding string, I get the following as output:

```<code>-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp
wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5
1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh
3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2
pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il
AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF
L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k
X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl
U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ
37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=
-----END RSA PRIVATE KEY-----
</code>```

You can see that the newline chars are being respected. However, if I call console.log(process.env["PRIVATE_KEY"]), the output contains the \n literal instead of actual newlines:

```<code>-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp\nwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5\n1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh\n3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2\npIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX\nGukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il\nAkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF\nL0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k\nX6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl\nU9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ\n37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=\n-----END RSA PRIVATE KEY-----
</code>```

I've been trying to find more information online about how node processes environment variables with no luck. How do I load this key via env vars while maintaining newline characters? If that's not possible, how can I restore them?

答:
I was using:

```<code>JSON.parse(`"${process.env.PUBPEM}"`)
</code>```

which suddenly started to fail.
So I changed it to:

```<code>JSON.parse(JSON.stringify(process.env.PUBPEM))
</code>```

Which solved it for me.

Body:
I'm attempting to load an RSA private key into my nodejs application using environment variables, but the newlines seem to be being auto-escaped.

For the following, assume that the PRIVATE_KEY env var is set to the following (not my actual key):

PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp\nwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5\n1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh\n3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2\npIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX\nGukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il\nAkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF\nL0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k\nX6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl\nU9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ\n37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=\n-----END RSA PRIVATE KEY-----"

If I call console.log directly with the preceding string, I get the following as output:

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp
wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5
1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh
3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2
pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il
AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF
L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k
X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl
U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ
37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=
-----END RSA PRIVATE KEY-----

You can see that the newline chars are being respected. However, if I call console.log(process.env["PRIVATE_KEY"]), the output contains the \n literal instead of actual newlines:

-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp\nwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5\n1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh\n3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2\npIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX\nGukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il\nAkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF\nL0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k\nX6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl\nU9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ\n37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=\n-----END RSA PRIVATE KEY-----

I've been trying to find more information online about how node processes environment variables with no luck. How do I load this key via env vars while maintaining newline characters? If that's not possible, how can I restore them?

Body:
I was using:

JSON.parse(`"${process.env.PUBPEM}"`)

which suddenly started to fail.
So I changed it to:

JSON.parse(JSON.stringify(process.env.PUBPEM))

Which solved it for me.


问:
How to approach find+replace with RST files using Python or Grep
I'm trying to automate a find+replace for a series of broken image links in .rst files. I have a csv file where column A is the "old" link (which is seen in the .rst files) and column B is the new replacement link for each row.

I can't use pandoc first to convert to HTML because it "breaks" the rst file.
I did this once for a set of HTML files using BeautifulSoup and regex,but that parser wont work for my rst files.

A coworker suggested trying Grep, but I can't seem to figure out how to call in the csv file to make the "match" and switch.

for the html files, it would loop through each file, search for an img tag and replace links using the csv file as a dict

```<code>with open(image_csv, newline='') as f:
reader = csv.reader(f)
next(reader, None)  # Ignore the header row
for row in reader:
    graph_main_nodes.append(row[0])
    graph_child_nodes.append(row[1:])
graph = dict(zip(graph_main_nodes, graph_child_nodes))  # Dict with keys in correct location, vals in old locations

graph = dict((v, k) for k in graph for v in graph[k])

for fixfile in html:
try:
    with open(fixfile, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f, 'html.parser')
        tags =  soup.findAll('img')
        for tag in tags:
            print(tag['src'])
            if tag['src'] in graph.keys():
                tag['src'] = tag['src'].replace(tag['src'], graph[tag['src']])
                replaced_links += 1
                print("Match found!")
            else:
                orphan_links.append(tag["src"])
                print("Ignore")
</code>```

I would love some suggestions on how to approach this. I'd love to repurpose my BeautifulSoup code but I'm not sure if that's realistic.

答:
This question has information on parsing an RST file, but I don't think it's necessary. Your question boils down to replace textA with textB. You already have your graph with the csv loaded, so should be ok with just this (credit to this answer)

# Read in the file
filedata = None
with open('fixfile', 'r', encoding='utf-8') as file:
  filedata = file.read()

# Replace the target strings
for old, new in graph.items():
  filedata.replace(old, new)

# Write the file out again
with open('fixfile', 'w', encoding='utf-8') as file:
  file.write(filedata)
```

<p>This is also a good candidate for <code>sed</code> or <code>perl</code>. Using something like this answer Also used this answer for help on specifying a rare delimiter for sed. (change the <code>-n</code> to <code>-i</code> and the <code>p</code> to <code>g</code> after testing to get it to actually save the file): </p>

<pre class="lang-sh prettyprint-override"><code>DELIM=$(echo -en "\001");
IFS=","
cat csvFile | while read PATTERN REPLACEMENT  # You feed the while loop with stdout lines and read fields separated by ":"
do
   sed -n "\\${DELIM}${PATTERN}${DELIM},\\${DELIM}${REPLACEMENT}${DELIM}p" fixfile.rst
done
</code>```

Body:
I'm trying to automate a find+replace for a series of broken image links in .rst files. I have a csv file where column A is the "old" link (which is seen in the .rst files) and column B is the new replacement link for each row.

I can't use pandoc first to convert to HTML because it "breaks" the rst file.
I did this once for a set of HTML files using BeautifulSoup and regex,but that parser wont work for my rst files.

A coworker suggested trying Grep, but I can't seem to figure out how to call in the csv file to make the "match" and switch.

for the html files, it would loop through each file, search for an img tag and replace links using the csv file as a dict

with open(image_csv, newline='') as f:
reader = csv.reader(f)
next(reader, None)  # Ignore the header row
for row in reader:
    graph_main_nodes.append(row[0])
    graph_child_nodes.append(row[1:])
graph = dict(zip(graph_main_nodes, graph_child_nodes))  # Dict with keys in correct location, vals in old locations

graph = dict((v, k) for k in graph for v in graph[k])

for fixfile in html:
try:
    with open(fixfile, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f, 'html.parser')
        tags =  soup.findAll('img')
        for tag in tags:
            print(tag['src'])
            if tag['src'] in graph.keys():
                tag['src'] = tag['src'].replace(tag['src'], graph[tag['src']])
                replaced_links += 1
                print("Match found!")
            else:
                orphan_links.append(tag["src"])
                print("Ignore")

I would love some suggestions on how to approach this. I'd love to repurpose my BeautifulSoup code but I'm not sure if that's realistic.

Body:
This question has information on parsing an RST file, but I don't think it's necessary. Your question boils down to replace textA with textB. You already have your graph with the csv loaded, so should be ok with just this (credit to this answer)

# Read in the file
filedata = None
with open('fixfile', 'r', encoding='utf-8') as file:
  filedata = file.read()

# Replace the target strings
for old, new in graph.items():
  filedata.replace(old, new)

# Write the file out again
with open('fixfile', 'w', encoding='utf-8') as file:
  file.write(filedata)

This is also a good candidate for sed or perl. Using something like this answer Also used this answer for help on specifying a rare delimiter for sed. (change the -n to -i and the p to g after testing to get it to actually save the file):

DELIM=$(echo -en "\001");
IFS=","
cat csvFile | while read PATTERN REPLACEMENT  # You feed the while loop with stdout lines and read fields separated by ":"
do
   sed -n "\\${DELIM}${PATTERN}${DELIM},\\${DELIM}${REPLACEMENT}${DELIM}p" fixfile.rst
done


问:
Unbalanced Panel data: How to use Time Series Splits Cross-Validation?
I am currently working with a big unbalanced data set, and was wondering whether it is possible to use the Time Series Splits Cross-Validation from sklearn to split my training sample into several 'folds'. I want each fold to contain only cross-sectional observations within the timeframe of that specific fold.

As previously mentioned, I am working with an unbalanced panel data set which makes use of the multi-indexing from Pandas. Here a reproducible example to provide some more intuition:

arrays = [np.array(['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D']),
           np.array(['2000-01', '2000-02', '2000-03', '1999-12', '2000-01',
          '2000-01', '2000-02', '1999-12', '2000-01', '2000-02', '2000-03'])]

s = pd.DataFrame(np.random.randn(11, 4), index=arrays)
```

Which then looks as follows:

For instance, I would like to initially have all cross sectional units in 1999-12 as training sample and all cross sectional units in 2000-01 as validation. Next, I want all cross-sectional units in 1999-12 and 2000-01 as training, and all cross sectional units in 2000-02 as validation, and so forth. Is this possible with the TimeSeriesSplit function, or do I need to look somewhere else?

答:
TimeSeriesSplit is a variation of KFold that ensures ascending index values across each successive fold. As noted in the docs:

In each split, test indices must be higher than before... [also] note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them.

docs

Also remember that KFold and TimeSeriesSplit return indices. You already have the index that you want.

One issue is that accessing a DateTimeIndex slice in a MultiIndex is overly difficult and complicated. See here, here and here. Since you're extracting the data at this point anyway, resetting the index and slicing seems acceptable. Especially since resetting the index doesn't happen in place.

Finally I recommend casting that datetime-like index to an actual datetime data type.

```<code>import pandas as pd
import numpy as np
import datetime
arrays = [np.array(['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D']),
           np.array(['2000-01', '2000-02', '2000-03', '1999-12', '2000-01',
          '2000-01', '2000-02', '1999-12', '2000-01', '2000-02', '2000-03'])]

# Cast as datetime
arrays[1] = pd.to_datetime(arrays[1])

df = pd.DataFrame(np.random.randn(11, 4), index=arrays)
df.index.sort_values()

folds = df.reset_index() # df still has its multindex after this

# You can tack an .iloc[:, 2:] to the end of these lines for just the values
# Use your predefined conditions to access the datetimes
fold1 = folds[folds["level_1"] <=datetime.datetime(2000, 1, 1)]
fold2 = folds[folds["level_1"] == datetime.datetime(2000, 2, 1)]
fold3 = folds[folds["level_1"] == datetime.datetime(2000, 3, 1)]
</code>```

Body:
I am currently working with a big unbalanced data set, and was wondering whether it is possible to use the Time Series Splits Cross-Validation from sklearn to split my training sample into several 'folds'. I want each fold to contain only cross-sectional observations within the timeframe of that specific fold.

As previously mentioned, I am working with an unbalanced panel data set which makes use of the multi-indexing from Pandas. Here a reproducible example to provide some more intuition:

arrays = [np.array(['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D']),
           np.array(['2000-01', '2000-02', '2000-03', '1999-12', '2000-01',
          '2000-01', '2000-02', '1999-12', '2000-01', '2000-02', '2000-03'])]

s = pd.DataFrame(np.random.randn(11, 4), index=arrays)

Which then looks as follows:

For instance, I would like to initially have all cross sectional units in 1999-12 as training sample and all cross sectional units in 2000-01 as validation. Next, I want all cross-sectional units in 1999-12 and 2000-01 as training, and all cross sectional units in 2000-02 as validation, and so forth. Is this possible with the TimeSeriesSplit function, or do I need to look somewhere else?

Body:
TimeSeriesSplit is a variation of KFold that ensures ascending index values across each successive fold. As noted in the docs:

In each split, test indices must be higher than before... [also] note that unlike standard cross-validation methods, successive training sets are supersets of those that come before them.

docs

Also remember that KFold and TimeSeriesSplit return indices. You already have the index that you want.

One issue is that accessing a DateTimeIndex slice in a MultiIndex is overly difficult and complicated. See here, here and here. Since you're extracting the data at this point anyway, resetting the index and slicing seems acceptable. Especially since resetting the index doesn't happen in place.

Finally I recommend casting that datetime-like index to an actual datetime data type.

import pandas as pd
import numpy as np
import datetime
arrays = [np.array(['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'D', 'D']),
           np.array(['2000-01', '2000-02', '2000-03', '1999-12', '2000-01',
          '2000-01', '2000-02', '1999-12', '2000-01', '2000-02', '2000-03'])]

# Cast as datetime
arrays[1] = pd.to_datetime(arrays[1])

df = pd.DataFrame(np.random.randn(11, 4), index=arrays)
df.index.sort_values()

folds = df.reset_index() # df still has its multindex after this

# You can tack an .iloc[:, 2:] to the end of these lines for just the values
# Use your predefined conditions to access the datetimes
fold1 = folds[folds["level_1"] <=datetime.datetime(2000, 1, 1)]
fold2 = folds[folds["level_1"] == datetime.datetime(2000, 2, 1)]
fold3 = folds[folds["level_1"] == datetime.datetime(2000, 3, 1)]


问:
What is the difference between an Instance and an Object?
What is the difference between an Instance and an Object?
Is there a difference or not?</p>

答:
An object is a generic thing, for example, take a linear function in maths

ax+b is an object, While 3x+2 is an instance of that object

Object<<< Instance

General<<< Specific

There is nothing more to this


问:
Firebase Function returns null data object
I have a Firebase Cloud Function that works (it writes to my database as Admin, and also checks for an existing entry with an email string ID). My issue is that it doesn't return the data back to the client app properly.

When I trace the value of result it is {data: null}

I would also like to throw an error if the email exists, but it complains about an unhandled promise (see the comments in the code below).

So there are two questions here. The first being the most pressing.

```<code>exports.saveData = functions.https.onCall( (data, context) => {

    // check if the email exists
    admin.database().ref('competition_entries/' + data.compId + '/' + data.emailStringId).once('value').then(function(snapshot) {
        if (snapshot.val() == null){

          console.log("Writing data to "+data.compId+" : "+data.emailStringId);

          let current_datetime = new Date()
          let formatted_time = current_datetime.getHours() + ":" + current_datetime.getMinutes() + ":" + current_datetime.getSeconds();
          let formatted_date = current_datetime.getDate() + "/" + (current_datetime.getMonth() + 1) + "/" + current_datetime.getFullYear();
          let timestamp_string = formatted_time+" "+formatted_date;
          console.log(formatted_date)

          admin.database().ref('competition_entries/' + data.compId + '/' + data.emailStringId).set({
            name: data.name,
            email: data.email,
            phone: data.phone,
            selectedItem: data.selectedItem,
            submitted_date: timestamp_string
          })
          .then(() => {
            console.log("success");
            return {
              "error": "none",
              "message": "success"
            };
          }).catch(function(error) {
            throw error;
          });

        }else{
            // email address exists as a data entry so tell the user that they have already submitted
            let code = "already-exists";
            let message = "Email address already exists";
            let details = "A user with the same email address has already entered the competition.";
            console.log(message+"/"+details);

            /*
              TODO: throwing an HttpsError directly here was causing an unresolved promise error. This would be the better way to tell the client that the user has already submitted their data.
            */
            // throw error;
            //throw new functions.https.HttpsError(code, message, details);

            // this resolves the promise error but is a hack
            return {
              error: new functions.https.HttpsError(code, message, details),
              message: message
            }
        }
    }).catch(function(error) {
      throw error;
    });
});
</code>```

答:
I think the problem is you are not returning enough. Functions needs every function to return something to execute succesfully.

Commonly is return true or return Promise

So it should be something like this:

```<code>//check if email exist
return admin.databse...

    //If there is no user create it
     return.admin...
</code>```

The code does write the database but since it was no return that happened asynchronously, and the code would keep executing from top to bottom making the function to response jibberish to the client.

You should

if (!snapshot) shortcircuiting is better because snapshot could be undefined causing an exception when checkinf if snapshot data is null

You dont need to use the admin sdk for the database, Functions is considered a trusted enviroments so operations are runned with admin privileges. You can CRUD anything despite rules or user restrictions

Body:
I have a Firebase Cloud Function that works (it writes to my database as Admin, and also checks for an existing entry with an email string ID). My issue is that it doesn't return the data back to the client app properly.

When I trace the value of result it is {data: null}

I would also like to throw an error if the email exists, but it complains about an unhandled promise (see the comments in the code below).

So there are two questions here. The first being the most pressing.

exports.saveData = functions.https.onCall( (data, context) => {

    // check if the email exists
    admin.database().ref('competition_entries/' + data.compId + '/' + data.emailStringId).once('value').then(function(snapshot) {
        if (snapshot.val() == null){

          console.log("Writing data to "+data.compId+" : "+data.emailStringId);

          let current_datetime = new Date()
          let formatted_time = current_datetime.getHours() + ":" + current_datetime.getMinutes() + ":" + current_datetime.getSeconds();
          let formatted_date = current_datetime.getDate() + "/" + (current_datetime.getMonth() + 1) + "/" + current_datetime.getFullYear();
          let timestamp_string = formatted_time+" "+formatted_date;
          console.log(formatted_date)

          admin.database().ref('competition_entries/' + data.compId + '/' + data.emailStringId).set({
            name: data.name,
            email: data.email,
            phone: data.phone,
            selectedItem: data.selectedItem,
            submitted_date: timestamp_string
          })
          .then(() => {
            console.log("success");
            return {
              "error": "none",
              "message": "success"
            };
          }).catch(function(error) {
            throw error;
          });

        }else{
            // email address exists as a data entry so tell the user that they have already submitted
            let code = "already-exists";
            let message = "Email address already exists";
            let details = "A user with the same email address has already entered the competition.";
            console.log(message+"/"+details);

            /*
              TODO: throwing an HttpsError directly here was causing an unresolved promise error. This would be the better way to tell the client that the user has already submitted their data.
            */
            // throw error;
            //throw new functions.https.HttpsError(code, message, details);

            // this resolves the promise error but is a hack
            return {
              error: new functions.https.HttpsError(code, message, details),
              message: message
            }
        }
    }).catch(function(error) {
      throw error;
    });
});

Body:
I think the problem is you are not returning enough. Functions needs every function to return something to execute succesfully.

Commonly is return true or return Promise

So it should be something like this:

//check if email exist
return admin.databse...

    //If there is no user create it
     return.admin...

The code does write the database but since it was no return that happened asynchronously, and the code would keep executing from top to bottom making the function to response jibberish to the client.

You should

if (!snapshot) shortcircuiting is better because snapshot could be undefined causing an exception when checkinf if snapshot data is null

You dont need to use the admin sdk for the database, Functions is considered a trusted enviroments so operations are runned with admin privileges. You can CRUD anything despite rules or user restrictions


问:
Cannot add Entity Data Model in Visual Studio
I am running Visual Studio 08 Team Edition with .NET Framework 3.5 SP1 on WinXP.  I am trying to add a Entity Data Model to my project, however, the option to add an "ADO.NET Entity Data Model" selection does not appear.  To give you a visual, I am essentially following the directions here, but cannot get past step 5 (Right click on project and click Add New Item) because the option to add an EDM does not appear.

Any ideas?  I'm sure I have all of the prerequisites.

答:
Here is a blog post about the issue.

Essentially, installing VS2008 SP1 (even if the about box on your installation can claim it's already SP1) resolved the issue for me.

Download page for SP1 here.


问:
Stacked and Grouped Chart with ExtJS 4
I'm trying to convert from Fusion Charts to the builtin ExtJS 4 charts and I can't find a way to create a Stacked and Grouped Chart. Has anyone been successful getting this to work with ExtJS 4? </p>

答:
I found the solution, You should add the second bar series and for each use render handler like this:

```<code>renderer: function(sprite, config, rendererData, index){ var w = config.width;
config.width = 30;
config.x = config.x + (w-30)/2 - 20; <--- -20 for first bar and + 20 for second

}
</code>```

Source:

Title: Stacked and Grouped Chart with ExtJS 4

Body:
I found the solution, You should add the second bar series and for each use render handler like this:

renderer: function(sprite, config, rendererData, index){ var w = config.width;
config.width = 30;
config.x = config.x + (w-30)/2 - 20; <--- -20 for first bar and + 20 for second

}

Source:


问:
getenv("APPDATA") returns incorrect values if current user having username containing unicode characters
Windows gives an api to get environment variable values using getenv(). If current user is having username containing localised characters (i.e. multibyte characters), then getenv returns incorrect value.

current user with username: テスト :
getenv("AppData") returns C:\Users\???\AppData\Roaming

It should return C:\Users\テスト\AppData\Roaming

Is there any alternative to getenv in Windows?

答:
Is there any alternative to getenv in windows?

The most accurate way to get a user's APPDATA folder is to ask the OS directly, not query the environment of the calling process at all.

You can use SHGetFolderPathW() with CSIDL_(LOCAL_)APPDATA.

On Vista and later, you can (and should) alternatively use SHGetKnownFolderPath() with FOLDERID_(Roaming|Local)AppData.


问:
iOS, Universal links, Swift. continueUserActivity not calling
I working on Universal links implementation for our iOS app.

Here is my small piece of AppDelegate:

```<code>private func application(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool {
    DeepLinkHelpers.handleUniversalLink(url.absoluteString)
    return true
}

private func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
    DeepLinkHelpers.handleUniversalLink(userActivity.webpageURL?.absoluteString)
    return true
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    signalRConnector.launch()

    NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.processRestartSignalRNotification(_:)), name: NSNotification.Name(rawValue: "restartSignalR"), object: nil)

    NotificationCenter.default.addObserver(self,                            selector: #selector(AppDelegate.reachabilityChanged(_:)),
                                           name: ReachabilityChangedNotification,
                                           object: reachability)

    do {
        try reachability.startNotifier()
    } catch {
        Logger.save(text: "Unable to start notifier")
    }
    return true
}
</code>```

I have processed all other steps for universal links integration:

Published apple-app-site-association file in our Web application

Switched on Associated domains feature on developers.apple.com

Specified associated domains in xcode

Checked Target Membership for entitlements file

Said xcode to wait until app will be started manually (instead of
autostart)

I doing following to debug:

Connecting ipad

Starting project in xcode

In ipad opening Calendar and click on link contained in some event.
Link has following format: app.domain.com/#/123456789

Ipad opens app but continueUserActivity not calling and i can't
handle code from the url for navigate to exact state within an app.

According documentation continueUserActivity should be executed. It is not executing both when app is running in background and when app not running.

Thank you in advance! Any help appreciated.

答:
In 2019, this is what helped me (from this guide: https://medium.com/@abhimuralidharan/universal-links-in-ios-79c4ee038272 ):</p>

```<code>func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    print("Continue User Activity called: ")
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
        let url = userActivity.webpageURL!
        print(url.absoluteString)
        //handle url and open whatever page you want to open.
    }
    return true
}
</code>```

Body:
I working on Universal links implementation for our iOS app.

Here is my small piece of AppDelegate:

private func application(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: AnyObject) -> Bool {
    DeepLinkHelpers.handleUniversalLink(url.absoluteString)
    return true
}

private func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
    DeepLinkHelpers.handleUniversalLink(userActivity.webpageURL?.absoluteString)
    return true
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    signalRConnector.launch()

    NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.processRestartSignalRNotification(_:)), name: NSNotification.Name(rawValue: "restartSignalR"), object: nil)

    NotificationCenter.default.addObserver(self,                            selector: #selector(AppDelegate.reachabilityChanged(_:)),
                                           name: ReachabilityChangedNotification,
                                           object: reachability)

    do {
        try reachability.startNotifier()
    } catch {
        Logger.save(text: "Unable to start notifier")
    }
    return true
}

I have processed all other steps for universal links integration:

Published apple-app-site-association file in our Web application

Switched on Associated domains feature on developers.apple.com

Specified associated domains in xcode

Checked Target Membership for entitlements file

Said xcode to wait until app will be started manually (instead of
autostart)

I doing following to debug:

Connecting ipad

Starting project in xcode

In ipad opening Calendar and click on link contained in some event.
Link has following format: app.domain.com/#/123456789

Ipad opens app but continueUserActivity not calling and i can't
handle code from the url for navigate to exact state within an app.

According documentation continueUserActivity should be executed. It is not executing both when app is running in background and when app not running.

Thank you in advance! Any help appreciated.

Body:
In 2019, this is what helped me (from this guide: https://medium.com/@abhimuralidharan/universal-links-in-ios-79c4ee038272 ):

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    print("Continue User Activity called: ")
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
        let url = userActivity.webpageURL!
        print(url.absoluteString)
        //handle url and open whatever page you want to open.
    }
    return true
}


问:
Default first boot activity on Android 2.2?
I'm working on modifying a firmware/ROM for an unbranded Chinese Android tablet i got. When i flash it to the Tablet and get to the lockscreen, unlocking it starts the Setup Wizard - but there appear to be TWO - As Android asks me to choose between two activities - the Setup Wizard and some 'defaultActivity'.

So i wonder - Where and how is this controlled by Android to know what to launch on first boot?

答: I had to remove Provision.APK to get rid of the duplicate APK - According to Cyanogenmod's Barebones page it isnt needed. Not much of a proper solution, But thats all i could find lacking any kind of source code for this device.</p>


问:
How to send a file to aws s3 using node Js?
So I am new to MERN stack and have setup a form for uploading an image and sending it to my bucket in aws s3. I am getting no response. I am sure there must be some error in my code. I am getting no response. I have followed a tutorial but my code is not working.
Server.js

```<code>const express = require("express");
const aws = require("aws-sdk");
var cors = require("cors");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const items = require("./routes/api/items"); // Contains all the api routes

// for uploading the images
const fs = require("fs");
const fileType = require("file-type");
const bluebird = require("bluebird");
const multiparty = require("multiparty");

// Body Parser middleware
app.use(bodyParser.json());
app.use(cors());
// DB config
const db = require("./config/keys").mongoURI;

// config for access key and id
aws.config.update({
  region: "us-east-1",
  accessKeyId: process.env.AWSAccessKeyId,
  secretAccessKey: process.env.AWSSecretKey
});

const S3_BUCKET = process.env.bucket;
console.log(S3_BUCKET);

exports.sign_s3 = (req, res) => {
  const s3 = new aws.S3(); // Create a new instance of S3
  const fileName = req.body.fileName;
  const fileType = req.body.fileType;

  // Set up the payload of what we are sending to the S3 api
  const s3Params = {
    Bucket: S3_BUCKET,
    Key: fileName,
    Expires: 500,
    ContentType: fileType,
    ACL: "public-read"
  };

  // Make a request to the S3 API to get a signed URL which we can use to upload our file
  s3.getSignedUrl("putObject", s3Params, (err, data) => {
    if (err) {
      console.log(err);
      res.json({ success: false, error: err });
    }

    // Data payload of what we are sending back, the url of the signedRequest and a URL where we can access the content after its saved.

    const returnData = {
      signedRequest: data,
      url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
    };
    // Send it all back

    res.json({ success: true, data: { returnData } });
  });
};

mongoose
  .connect(db, { useNewUrlParser: true })
  .then(() => console.log("Mongo is laoded"))
  .catch(err => console.log(err));

app.use("/api/items", items); // redirecting api routes to items

const port = process.env.PORT || 5000;

app.listen(port, () => console.log("Server started"));
</code>```

I have stored my aws credentials in a .env file in the root directory. The other components of my form are working fine. Only the image is not getting stored in aws.
I will try to abstract the code to remove unwanted details.
UserForm.jsx

```<code> handleSubmit = e => {
    e.preventDefault();
    let file = this.uploadInput.files[0];
    // Split the filename to get the name and type
    let fileParts = this.uploadInput.files[0].name.split(".");
    let fileName = fileParts[0];
    let fileType = fileParts[1];
    console.log("Preparing the upload");
    axios
      .post("http://localhost:5000/api/items", {
        fileName: fileName,
        fileType: fileType
      })
      .then(response => {
        var returnData = response.data.data.returnData;
        var signedRequest = returnData.signedRequest;
        var url = returnData.url;
        this.setState({ url: url });
        console.log("Recieved a signed request " + signedRequest);

        // Put the fileType in the headers for the upload
        var options = {
          headers: {
            "Content-Type": fileType
          }
        };
        axios
          .put(signedRequest, file, options)
          .then(result => {
            console.log("Response from s3");
            this.setState({ success: true });
          })
          .catch(error => {
            alert("ERROR " + JSON.stringify(error));
          });
      })
      .catch(error => {
        alert(JSON.stringify(error));
      });

    // update ends
    const users = {
      name: this.state.name,
      contact: this.state.contact,
      company: this.state.company,
      mail: this.state.mail,
      key: this.state.key,
      apps_no: this.state.apps_no
    };

    axios
      .post(
        "http://localhost:5000/api/items",
        {
          name: users.name,
          contact_no: users.contact,
          company_name: users.company,
          key: users.key,
          mail: users.mail,
          apps_no: users.apps_no
        },
        {
          headers: {
            "content-type": "application/json"
          }
        }
      )
      .then(res => {
        console.log("Post submitted with response " + res.status);
        console.log("Mail: " + users.mail);
      })
      .catch(function(error) {
        console.log(error);
      });

    this.props.history.push("/form-submitted");
  };

  componentDidMount() {
    axios.get("http://localhost:5000/api/items").then(resp => {
      console.log(resp.data);
    });
  }
</code>```

In render function, I am using onClick tag in form tag to submit the details. Input field:
<

```<code>center>
            <h1>UPLOAD A FILE</h1>
            {this.state.success ? <Success_message /> : null}
            <input
              onChange={this.handleFileChange.bind(this)}
              ref={ref => {
                this.uploadInput = ref;
              }}
              type="file"
            />
            <br />
</code>```

console:

```<code>Array(22)
UserForm.jsx:54 Preparing the upload
UserForm.jsx:115 Post submitted with response 200
</code>```

There is clearly a lot wrong with my code. Help would be appreciated.
Edit:
items.js-

```<code>const express = require("express");
const router = express.Router();

// Item model
const Item = require("../../models/Item");

// Routes
// @get API item get all items
// make a get req
router.get("/", (req, res) => {
  Item.find().then(items => res.json(items));
});

// @get Api item POST all items
// make a post req
// create an item
router.post("/", (req, res) => {
  const newItem = new Item({
    name: req.body.name,
    contact_no: req.body.contact_no,
    company_name: req.body.company_name,
    key: req.body.key,
    mail: req.body.mail,
    apps_no: req.body.apps_no
  });

  newItem.save().then(item => res.json(item));
});

// @del api item.
// delete request
router.delete("/:id", (req, res) => {
  Item.findById(req.params.id)
    .then(item => item.remove().then(() => res.json({ success: true })))
    .catch(err => res.status(404).json({ success: false }));
});

module.exports = router;
</code>```

答:
This is what we've done :

We did configure AWS cli in our environment check this link : https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html , on live make your project to configure and read needed AWS keys in a secured way but don't store any keys in .env file or in code then after the script looks like :

```<code>const AWS = require('aws-sdk');
const s3 = new AWS.S3();

let putParams = {
            Body: fileCotent,
            Bucket: s3BucketName,
            Key: fileName,
            ContentType:'image/png'

        };
        s3.putObject(putParams, function(err, data) {
            if (err) console.log(err, err.stack);
            else     console.log(data);
            done();

        });
</code>```

Body:
So I am new to MERN stack and have setup a form for uploading an image and sending it to my bucket in aws s3. I am getting no response. I am sure there must be some error in my code. I am getting no response. I have followed a tutorial but my code is not working.
Server.js

const express = require("express");
const aws = require("aws-sdk");
var cors = require("cors");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const items = require("./routes/api/items"); // Contains all the api routes

// for uploading the images
const fs = require("fs");
const fileType = require("file-type");
const bluebird = require("bluebird");
const multiparty = require("multiparty");

// Body Parser middleware
app.use(bodyParser.json());
app.use(cors());
// DB config
const db = require("./config/keys").mongoURI;

// config for access key and id
aws.config.update({
  region: "us-east-1",
  accessKeyId: process.env.AWSAccessKeyId,
  secretAccessKey: process.env.AWSSecretKey
});

const S3_BUCKET = process.env.bucket;
console.log(S3_BUCKET);

exports.sign_s3 = (req, res) => {
  const s3 = new aws.S3(); // Create a new instance of S3
  const fileName = req.body.fileName;
  const fileType = req.body.fileType;

  // Set up the payload of what we are sending to the S3 api
  const s3Params = {
    Bucket: S3_BUCKET,
    Key: fileName,
    Expires: 500,
    ContentType: fileType,
    ACL: "public-read"
  };

  // Make a request to the S3 API to get a signed URL which we can use to upload our file
  s3.getSignedUrl("putObject", s3Params, (err, data) => {
    if (err) {
      console.log(err);
      res.json({ success: false, error: err });
    }

    // Data payload of what we are sending back, the url of the signedRequest and a URL where we can access the content after its saved.

    const returnData = {
      signedRequest: data,
      url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
    };
    // Send it all back

    res.json({ success: true, data: { returnData } });
  });
};

mongoose
  .connect(db, { useNewUrlParser: true })
  .then(() => console.log("Mongo is laoded"))
  .catch(err => console.log(err));

app.use("/api/items", items); // redirecting api routes to items

const port = process.env.PORT || 5000;

app.listen(port, () => console.log("Server started"));

I have stored my aws credentials in a .env file in the root directory. The other components of my form are working fine. Only the image is not getting stored in aws.
I will try to abstract the code to remove unwanted details.
UserForm.jsx

 handleSubmit = e => {
    e.preventDefault();
    let file = this.uploadInput.files[0];
    // Split the filename to get the name and type
    let fileParts = this.uploadInput.files[0].name.split(".");
    let fileName = fileParts[0];
    let fileType = fileParts[1];
    console.log("Preparing the upload");
    axios
      .post("http://localhost:5000/api/items", {
        fileName: fileName,
        fileType: fileType
      })
      .then(response => {
        var returnData = response.data.data.returnData;
        var signedRequest = returnData.signedRequest;
        var url = returnData.url;
        this.setState({ url: url });
        console.log("Recieved a signed request " + signedRequest);

        // Put the fileType in the headers for the upload
        var options = {
          headers: {
            "Content-Type": fileType
          }
        };
        axios
          .put(signedRequest, file, options)
          .then(result => {
            console.log("Response from s3");
            this.setState({ success: true });
          })
          .catch(error => {
            alert("ERROR " + JSON.stringify(error));
          });
      })
      .catch(error => {
        alert(JSON.stringify(error));
      });

    // update ends
    const users = {
      name: this.state.name,
      contact: this.state.contact,
      company: this.state.company,
      mail: this.state.mail,
      key: this.state.key,
      apps_no: this.state.apps_no
    };

    axios
      .post(
        "http://localhost:5000/api/items",
        {
          name: users.name,
          contact_no: users.contact,
          company_name: users.company,
          key: users.key,
          mail: users.mail,
          apps_no: users.apps_no
        },
        {
          headers: {
            "content-type": "application/json"
          }
        }
      )
      .then(res => {
        console.log("Post submitted with response " + res.status);
        console.log("Mail: " + users.mail);
      })
      .catch(function(error) {
        console.log(error);
      });

    this.props.history.push("/form-submitted");
  };

  componentDidMount() {
    axios.get("http://localhost:5000/api/items").then(resp => {
      console.log(resp.data);
    });
  }

In render function, I am using onClick tag in form tag to submit the details. Input field:
<

center>

UPLOAD A FILE

            {this.state.success ? <Success_message /> : null}
            <input
              onChange={this.handleFileChange.bind(this)}
              ref={ref => {
                this.uploadInput = ref;
              }}
              type="file"
            />

console:

Array(22)
UserForm.jsx:54 Preparing the upload
UserForm.jsx:115 Post submitted with response 200

There is clearly a lot wrong with my code. Help would be appreciated.
Edit:
items.js-

const express = require("express");
const router = express.Router();

// Item model
const Item = require("../../models/Item");

// Routes
// @get API item get all items
// make a get req
router.get("/", (req, res) => {
  Item.find().then(items => res.json(items));
});

// @get Api item POST all items
// make a post req
// create an item
router.post("/", (req, res) => {
  const newItem = new Item({
    name: req.body.name,
    contact_no: req.body.contact_no,
    company_name: req.body.company_name,
    key: req.body.key,
    mail: req.body.mail,
    apps_no: req.body.apps_no
  });

  newItem.save().then(item => res.json(item));
});

// @del api item.
// delete request
router.delete("/:id", (req, res) => {
  Item.findById(req.params.id)
    .then(item => item.remove().then(() => res.json({ success: true })))
    .catch(err => res.status(404).json({ success: false }));
});

module.exports = router;

Body:
This is what we've done :

We did configure AWS cli in our environment check this link : https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html , on live make your project to configure and read needed AWS keys in a secured way but don't store any keys in .env file or in code then after the script looks like :

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

let putParams = {
            Body: fileCotent,
            Bucket: s3BucketName,
            Key: fileName,
            ContentType:'image/png'

        };
        s3.putObject(putParams, function(err, data) {
            if (err) console.log(err, err.stack);
            else     console.log(data);
            done();

        });


问:
Conditional Probability a Raffle
I would like to know the probability of each number coming out in a raffle in which we have from 1 to 25 and are drawn 15 numbers.

would be 1/15 or 1/25, or another percentage?

Similar problem:

What is the probability of getting two five consecutive with a six-sided die? The probability of each independent event is equal to 1/6. This gives us 1/6 × 1/6 = 1/36, 0.027 or 2.7%.

答:
Probability of each number coming out in a raffle is 1/25.

It is similar to the example you mentioned. Probability of getting a number from rolling dice is 1/6 whether you roll the dice once or multiple times.

Title: Conditional Probability a Raffle


问:
View Controller open from AppDelegate (from Universal Link) don't have the navigation controller
I created a universal link for an app. It works great. It opens the app and goes to the view controller defined and it shows the correct info passed through the universal link. The problem is that the view controller has a navigation controller. But when I access directly from appdelegate, it doesn't show this navigation controller.

How I can define the present in AppDelegate to show the view controller with the navigation controller?

```<code>if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "AnuncioV2ViewController") as? AnuncioV2ViewController {
    if let window = self.window, let rootViewController = window.rootViewController {
        var currentController = rootViewController
        while let presentedController = currentController.presentedViewController {
            currentController = presentedController
        }
        controller.idAd = adID
        controller.id_usuario = self.userID
        controller.anuncio = anuncio as! [String:Any]

        DispatchQueue.main.async {
            currentController.present(controller, animated: true, completion: nil)
        }
    }
}
</code>```

答: Unless AnuncioV2ViewController is a subclass of UINavigationController, you're literally just leaving out a step. If it's all set up correctly in your storyboard, just provide the parent navigation controller an identifier and instantiate that instead. You can then access the AnuncioV2ViewController instance by using navigationController.children.first! as! AnuncioV2ViewController. (If this is in your storyboard and this works at least once correctly, those force-unwraps should be fine for prime-time.)

Body:
I created a universal link for an app. It works great. It opens the app and goes to the view controller defined and it shows the correct info passed through the universal link. The problem is that the view controller has a navigation controller. But when I access directly from appdelegate, it doesn't show this navigation controller.

How I can define the present in AppDelegate to show the view controller with the navigation controller?

if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "AnuncioV2ViewController") as? AnuncioV2ViewController {
    if let window = self.window, let rootViewController = window.rootViewController {
        var currentController = rootViewController
        while let presentedController = currentController.presentedViewController {
            currentController = presentedController
        }
        controller.idAd = adID
        controller.id_usuario = self.userID
        controller.anuncio = anuncio as! [String:Any]

        DispatchQueue.main.async {
            currentController.present(controller, animated: true, completion: nil)
        }
    }
}


问:
How to return the last 9 results for each horse
I have query via sql that lists all a horses performances for previous races. I would like to just list their last 9 performances. </p>

<p>I have been trying to find an answer searching various sites for a while but cannot find one that suits. I would appreciate any help. </p>

```<code>SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
FROM Form1
WHERE Horse in ('SOHO PICASSO','LITTLE BITOF FUN','BEEJAYS STAR','MISS STARFIRE','MEDIEVAL MAN','BLUE STONE','SOHO MAJOR PLAYER NZ','HUMBLE FELLA','STARS OF GOLD','MISS SERENA','MISS MARGARETA','NIGHTWATCH STAR','PURE IMAGE','VILLAGE BENNY','CAPTAIN CROISSANT','JESSIE JOAN','THE GLASS CEILING','BROOK PARKS LAST','ANTAGONISTIC NZ');
</code>```

答:
Use ROW_NUMBER function.

```<code>SELECT*
FROM(
  SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
    ,ROW_NUMBER() OVER(PARTITION BY Horse ORDER BY Date) rn
  FROM Form1
  WHERE Horse in ('SOHO PICASSO','LITTLE BITOF FUN','BEEJAYS STAR','MISS STARFIRE','MEDIEVAL MAN','BLUE STONE','SOHO MAJOR PLAYER NZ','HUMBLE FELLA','STARS OF GOLD','MISS SERENA','MISS MARGARETA','NIGHTWATCH STAR','PURE IMAGE','VILLAGE BENNY','CAPTAIN CROISSANT','JESSIE JOAN','THE GLASS CEILING','BROOK PARKS LAST','ANTAGONISTIC NZ')
)T
WHERE rn <= 9
</code>```

If your DB doesn't support ROW_NUMBER use that query:

```<code>SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
FROM (
  SELECT t1.Horse, t1.Date, COUNT(*) AS rn
  FROM Form1 AS t1
  INNER JOIN Form1 AS t2
  ON t2.Horse = t1.Horse
  AND t2.Date >= t1.Date
  GROUP BY t1.Horse, t1.Date
  HAVING COUNT(*) <= 9
)t
INNER JOIN Form1
ON Form1.Horse = t.Horse
AND Form1.Date = t.Date
</code>```

The inner query simulates the ROW_NUMBER and filters to rows with rn <= 9.

Body:
I have query via sql that lists all a horses performances for previous races. I would like to just list their last 9 performances.

I have been trying to find an answer searching various sites for a while but cannot find one that suits. I would appreciate any help.

SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
FROM Form1
WHERE Horse in ('SOHO PICASSO','LITTLE BITOF FUN','BEEJAYS STAR','MISS STARFIRE','MEDIEVAL MAN','BLUE STONE','SOHO MAJOR PLAYER NZ','HUMBLE FELLA','STARS OF GOLD','MISS SERENA','MISS MARGARETA','NIGHTWATCH STAR','PURE IMAGE','VILLAGE BENNY','CAPTAIN CROISSANT','JESSIE JOAN','THE GLASS CEILING','BROOK PARKS LAST','ANTAGONISTIC NZ');

Body:
Use ROW_NUMBER function.

SELECT*
FROM(
  SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
    ,ROW_NUMBER() OVER(PARTITION BY Horse ORDER BY Date) rn
  FROM Form1
  WHERE Horse in ('SOHO PICASSO','LITTLE BITOF FUN','BEEJAYS STAR','MISS STARFIRE','MEDIEVAL MAN','BLUE STONE','SOHO MAJOR PLAYER NZ','HUMBLE FELLA','STARS OF GOLD','MISS SERENA','MISS MARGARETA','NIGHTWATCH STAR','PURE IMAGE','VILLAGE BENNY','CAPTAIN CROISSANT','JESSIE JOAN','THE GLASS CEILING','BROOK PARKS LAST','ANTAGONISTIC NZ')
)T
WHERE rn <= 9

If your DB doesn't support ROW_NUMBER use that query:

SELECT Form1.Horse, Form1.Date, Form1.[Mile Rate], Form1.[Beaten M], Form1.Distance, Form1.[M or S], Form1.[Class], Form1.[1Q], Form1.[2Q], Form1.[3Q], Form1.Bar, Form1.Driver, Form1.Comment, Form1.Trainer, Form1.Adj, Form1.[Race%], Form1.[Bell Pos], Form1.Pegs, Form1.[Adj LH], Form1.[M LastL], Form1.[Track]
FROM (
  SELECT t1.Horse, t1.Date, COUNT(*) AS rn
  FROM Form1 AS t1
  INNER JOIN Form1 AS t2
  ON t2.Horse = t1.Horse
  AND t2.Date >= t1.Date
  GROUP BY t1.Horse, t1.Date
  HAVING COUNT(*) <= 9
)t
INNER JOIN Form1
ON Form1.Horse = t.Horse
AND Form1.Date = t.Date

The inner query simulates the ROW_NUMBER and filters to rows with rn <= 9.


问:
PHP How to remove white spaces, obfuscating the output HTML CODE on the fly at the Server
I have a simple website in PHP.

My website does not use any Data Source, just some simple PHP scripts to allow some basic functionality.

As for my understanding when a User request my website the PHP code generates the HTML code that will be read by their browser.

I need to make difficult (in some how obfuscate) the HTML generated, so if the user would save a HTML page the code would be difficult to modify and uneasy to interpreter.

My basic need are basically COMPRESSING the HTML:

Eliminate white space. So all code would be packed in few line. Making it in some how human unreadable

Encode the HTML (optional)

Because I have many pages in my website. I'm looking for an automatic solution so I can add some code in one place and have for the next moment all pages output as described above.

Any idea how to do it?

Thanks for your time.

答:
If you want to compress the generated HTML pages on the way to the user, enable compression by i.e. using mod_gzip or mod_deflate in apache.

If, on the other hand, you want "protection" - this is not possible. The music and film industry have been trying that for decades. You could of course generate a big fat image (jpeg) from your page and serve that as an image map :)


问:
How do I ensure I'm writing my output JSON files in UTF-8?
I am trying to write my output JSON files in Python to UTF-8. However, I am not sure if I am doing it correctly and I'm not sure how to verify the output is in utf-8. I am calling:

```<code>json_output = json.dump(new_json, outfile, ensure_ascii = False)
</code>```

where new_json is my data.

Will this encode in UTF-8?

答:
something like?</p>

```<code>   with open('myfile.json', 'w', encoding='utf-8') as outfile:
        json.dump(new_json, outfile)
</code>```

Body:
I am trying to write my output JSON files in Python to UTF-8. However, I am not sure if I am doing it correctly and I'm not sure how to verify the output is in utf-8. I am calling:

json_output = json.dump(new_json, outfile, ensure_ascii = False)

where new_json is my data.

Will this encode in UTF-8?

Body:
something like?

   with open('myfile.json', 'w', encoding='utf-8') as outfile:
        json.dump(new_json, outfile)


问:
How do I solve this scanner issue? I want the four actions to work but whenever I type it in and click enter it doesn't work
I'm trying to create a bootleg pokemon game but this scanner isn't working.

JavaBattle object is instantiated inside of driver. Everything works in the driver, but this code doesn't. "Cyclone", "Tornado Spin", "Thermal" and "Huff 'n Puff" all should work but don't on the first try.

I don't really know what I should do.

```<code>import java.util.*;
public class JavaBattle{
    private int opponentHealth;

    public void fight(){
        opponentHealth = 100;
        Scanner attackchoice = new Scanner(System.in);
        System.out.println("Attacks:\nCylcone\nTornado Spin\nThermal\nHuff 'n Puff");
        System.out.println("Choose One:");
        String ability = attackchoice.nextLine();
        if(!ability.equals("Cyclone")||!ability.equals("Tornado
Spin")||!ability.equals("Thermal")||!ability.equals("Huff 'n Puff")){
            System.out.println("Not available. Please Try Again.");
            System.out.println("Attacks:\nCylcone\nTornado Spin\nThermal\nHuff 'n Puff");
            System.out.println("Choose One: ");
            ability = attackchoice.nextLine();
        }
        int randAttackDamage = (int)(Math.random()*16)+15;
        int randOpponentAttack = (int)(Math.random()*21)+10;
        System.out.println(ability + " was used." + "("+randAttackDamage+")");
        opponentHealth = opponentHealth - randAttackDamage;
        System.out.println("Opponents Current Health: " + opponentHealth);
    }
}
</code>```

答: You need to replace your logical OR operators || with AND operators &&. With the code you have, your if clause is only true if ability is all four of the abilities at once. You want to check if the ability is none of the available abilities.

Body:
I'm trying to create a bootleg pokemon game but this scanner isn't working.

JavaBattle object is instantiated inside of driver. Everything works in the driver, but this code doesn't. "Cyclone", "Tornado Spin", "Thermal" and "Huff 'n Puff" all should work but don't on the first try.

I don't really know what I should do.

import java.util.*;
public class JavaBattle{
    private int opponentHealth;

    public void fight(){
        opponentHealth = 100;
        Scanner attackchoice = new Scanner(System.in);
        System.out.println("Attacks:\nCylcone\nTornado Spin\nThermal\nHuff 'n Puff");
        System.out.println("Choose One:");
        String ability = attackchoice.nextLine();
        if(!ability.equals("Cyclone")||!ability.equals("Tornado
Spin")||!ability.equals("Thermal")||!ability.equals("Huff 'n Puff")){
            System.out.println("Not available. Please Try Again.");
            System.out.println("Attacks:\nCylcone\nTornado Spin\nThermal\nHuff 'n Puff");
            System.out.println("Choose One: ");
            ability = attackchoice.nextLine();
        }
        int randAttackDamage = (int)(Math.random()*16)+15;
        int randOpponentAttack = (int)(Math.random()*21)+10;
        System.out.println(ability + " was used." + "("+randAttackDamage+")");
        opponentHealth = opponentHealth - randAttackDamage;
        System.out.println("Opponents Current Health: " + opponentHealth);
    }
}


问:
How to calculate the consecutive sum of number in a string?
I would like to find the sum of integer in string. For example:

```<code>String myString= "The price is 345and the tax1 is 12sales";
String output = "The price is 12and the tax1 is 3sales";
</code>```

I found few approaches none is displaying the final output the way I need.

```<code>int sum = 0;
for (int I =0; i < myString.lengh(); i++)
{
   char c = myString.charAt(i);
   if(Character.isDigit(c))
   {
      int value = Integer.parseInt(String.valueOf(c));
   }
}
</code>```

I am getting the total sum but I would like to be able to append the string with individual sums.
    output = "The price is 12and the tax1 is 3sales"

答:
I'm using a StringBuilder for building the result string. You have to keep adding the digits as long as you encounter digits. When you encounter a character, you have to append the sum at hand (if you have) and then append the character.

Note: This won't work if the sum can be 0 (and needs to be tweaked to support that).

```<code>int sum = 0;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < myString.length(); i++)
{
    char c = myString.charAt(i);
    if(Character.isDigit(c))
    {
        sum += Integer.parseInt(String.valueOf(c));
    } else {
        if (sum != 0) {
            builder.append(sum);
        }
        builder.append(c);
        sum = 0; //reset
    }
}
</code>```

Body:
I would like to find the sum of integer in string. For example:

String myString= "The price is 345and the tax1 is 12sales";
String output = "The price is 12and the tax1 is 3sales";

I found few approaches none is displaying the final output the way I need.

int sum = 0;
for (int I =0; i < myString.lengh(); i++)
{
   char c = myString.charAt(i);
   if(Character.isDigit(c))
   {
      int value = Integer.parseInt(String.valueOf(c));
   }
}

I am getting the total sum but I would like to be able to append the string with individual sums.
    output = "The price is 12and the tax1 is 3sales"

Body:
I'm using a StringBuilder for building the result string. You have to keep adding the digits as long as you encounter digits. When you encounter a character, you have to append the sum at hand (if you have) and then append the character.

Note: This won't work if the sum can be 0 (and needs to be tweaked to support that).

int sum = 0;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < myString.length(); i++)
{
    char c = myString.charAt(i);
    if(Character.isDigit(c))
    {
        sum += Integer.parseInt(String.valueOf(c));
    } else {
        if (sum != 0) {
            builder.append(sum);
        }
        builder.append(c);
        sum = 0; //reset
    }
}


问:
How can be add orWhere conditions in cakephp3.7 because in 3.7 orWhere deprecated
orWhere conditions in cakephp3.7 because in 3.7 orWhere deprecated</p>

```<code>select * from Users where Users.state = 'UP' Or (Users.status =1 and Users.role=2)
</code>```

答:
You can use either the OR keyword (and for better readability the optional AND keyword) with the nested array syntax:

```<code>$query->where([
    'OR' => [
        'Users.state' => 'UP',
        'AND' => [
            'Users.status' => 1,
            'Users.role' => 2
        ]
    ]
]);
</code>```

or expressions:

```<code>$query->where(function (
    \Cake\Database\Expression\QueryExpression $exp,
    \Cake\ORM\Query $query
) {
    return $exp->or_([
        'Users.state' => 'UP',
        $query->newExpr()->and_([
            'Users.status' => 1,
            'Users.role' => 2
        ])
    ]);
});
</code>```

See also

Cookbook > Database Access & ORM > Query Builder > Advanced Conditions

Body:
orWhere conditions in cakephp3.7 because in 3.7 orWhere deprecated

select * from Users where Users.state = 'UP' Or (Users.status =1 and Users.role=2)

Body:
You can use either the OR keyword (and for better readability the optional AND keyword) with the nested array syntax:

$query->where([
    'OR' => [
        'Users.state' => 'UP',
        'AND' => [
            'Users.status' => 1,
            'Users.role' => 2
        ]
    ]
]);

or expressions:

$query->where(function (
    \Cake\Database\Expression\QueryExpression $exp,
    \Cake\ORM\Query $query
) {
    return $exp->or_([
        'Users.state' => 'UP',
        $query->newExpr()->and_([
            'Users.status' => 1,
            'Users.role' => 2
        ])
    ]);
});

See also

Cookbook > Database Access & ORM > Query Builder > Advanced Conditions


问: Extracting contents inside

答:
Assuming the rest of the code works, a simple regex should do the trick :)

import urllib.request
import re
import json
from bs4 import BeautifulSoup

url = 'https://www.broadwayinbound.com/shows/'
response = urllib.request.urlopen(url)
data = response.read()      # a `bytes` object
soup = BeautifulSoup(data)
results = soup.findAll('script', {'type':'text/javascript'})
r = []
for result in results :
    if 'var shows = [' in result.text:
        x = re.findall(r"var shows = (\[.*\])", result.text)
        if (len(x) > 0):
            r.append(x[0])

print(json.loads(r[0]))
print(json.loads(r[0])[0]["Id"])
```

Title: Extracting contents inside <script type="text/javascript"> and $(function ()

Body:
I am working on scraping data from websites. I was able to extract contents inside the tag . But it has '$(function () {' inside it. I want to extract contents inside it.

import urllib.request
from bs4 import BeautifulSoup
import json
url = 'https://www.broadwayinbound.com/shows/'
response = urllib.request.urlopen(url)
data = response.read()      # a `bytes` object
soup = BeautifulSoup(data)
results = soup.findAll('script', {'type':'text/javascript'})
r = []
for result in results :
    if 'var shows = [' in result.text:
        r.append(result.text)
print (r[0])

I want to extract the contents of 'var shows' alone.

{"Id":"12680","ClientClassCode":"default","ShowName":"Ain't Too Proud - The Life and Times of The Temptations","ShowCode":"AINTPROUD","SortName":"Ain't Too Proud - The Life and Times of The Temptations","ShowLogo":"/product-resources/Aint-Too-Proud-Temptations-Musical-Broadway-Group-Sales-Show-Tickets-500-102318.jpg","ShowLogoText":"Ain't Too Proud - The Life and Times of The Temptations Tickets | Broadway......


问:
Python unittest.mock: patched class method called but assertion fails
I'm trying to mock several components of a utility class. While assert_called() is ok for one method it fails for an other but I am sure that both are called. I'm running Python 3.7.3 on Windows 10.

I have stripped down my scenario to the essentials.
The utility class (util.py):

class api:

    @staticmethod
    def send(data):
        print("sending %s" % data)

    class logger:

        @staticmethod
        def info(s):
            print("INFO: %s" % s)

        @staticmethod
        def error(s):
            print("ERROR: %s" % s)
```

<p>The  unit test variant that works fine:</p>

<pre class="lang-py prettyprint-override"><code>import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api.logger")
class Test(unittest.TestCase):

    def test_do_something(self, mock_logger):
        do_something()
        mock_logger.info.assert_called()
</code>```

The one that fails:

import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api")
class Test(unittest.TestCase):

    def test_do_something(self, mock_api):
        do_something()
        mock_api.send.assert_called()
```

<p>When running the tests I am getting both <code>print()</code> outputs:</p>

```INFO: doing something
sending some data
```

<p>so I'm sure that both methods are called.</p>

<p>Very likely I'm making some stupid dummy mistake because I'm really new to python...</p>

<p>Some more background:</p>

<p>In my stripped down scenario <code>do_something()</code> is just a stand-in for a set of functions that are the object of my test and that in my real scenario are actually defined in a separate python file. In the production environment it runs in the context of a framework that provides the utility class api. In my test environment <code>util.py</code> itself is a mock of the production api. The py file to be tested (instead of <code>def do_something(): ...</code>) is loaded like so: </p>

```path = os.getcwd() + "<local path to py file to be tested>"
globals().update({ **runpy.run_path(path, init_globals=globals()), **globals() })
```

Therefore, I can't modify the do_something() code in the test scenario.

答:
This was a tricky one.

The issue is that the api class in imported by the test class well before it is patched. From the docs for patch:

The target is imported when the decorated function is executed, not at decoration time.

Since you import the api class first thing in the test class, that guy is not getting patched when you run the test. Python thinks it's already imported.

Note this is not the case with the logger class since you never import it. If you had, the first test would've failed as well.

Simplest fix - move the import inside the test function.

```<code>def do_something():
     from util import api
     api.logger.info("doing something")
     api.send("some data")
</code>```

Now patch will do the importing - so the mock is placed in the test scope instead of the actual class.

Body:
I'm trying to mock several components of a utility class. While assert_called() is ok for one method it fails for an other but I am sure that both are called. I'm running Python 3.7.3 on Windows 10.

I have stripped down my scenario to the essentials.
The utility class (util.py):

class api:

    @staticmethod
    def send(data):
        print("sending %s" % data)

    class logger:

        @staticmethod
        def info(s):
            print("INFO: %s" % s)

        @staticmethod
        def error(s):
            print("ERROR: %s" % s)

The  unit test variant that works fine:

import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api.logger")
class Test(unittest.TestCase):

    def test_do_something(self, mock_logger):
        do_something()
        mock_logger.info.assert_called()

The one that fails:

import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api")
class Test(unittest.TestCase):

    def test_do_something(self, mock_api):
        do_something()
        mock_api.send.assert_called()

When running the tests I am getting both print() outputs:

INFO: doing something
sending some data

so I'm sure that both methods are called.

Very likely I'm making some stupid dummy mistake because I'm really new to python...

Some more background:

In my stripped down scenario do_something() is just a stand-in for a set of functions that are the object of my test and that in my real scenario are actually defined in a separate python file. In the production environment it runs in the context of a framework that provides the utility class api. In my test environment util.py itself is a mock of the production api. The py file to be tested (instead of def do_something(): ...) is loaded like so:

path = os.getcwd() + "<local path to py file to be tested>"
globals().update({ **runpy.run_path(path, init_globals=globals()), **globals() })

Therefore, I can't modify the do_something() code in the test scenario.

Body:
This was a tricky one.

The issue is that the api class in imported by the test class well before it is patched. From the docs for patch:

The target is imported when the decorated function is executed, not at decoration time.

Since you import the api class first thing in the test class, that guy is not getting patched when you run the test. Python thinks it's already imported.

Note this is not the case with the logger class since you never import it. If you had, the first test would've failed as well.

Simplest fix - move the import inside the test function.

def do_something():
     from util import api
     api.logger.info("doing something")
     api.send("some data")

Now patch will do the importing - so the mock is placed in the test scope instead of the actual class.


问:
How to dynamically create multiple nested objects in thymeleaf
Currently i'm doing website with newsletter posting. I want to post and show comments under every post.

MY POST

first comment

comments to first comment

comments to second comment
-so on...

second comment

third comment

I know how to dynamically create elements in a loop with one level of nesting. But how can i create multiple nesting?

For example I can create comments:

```<code><div class='comments' th:each="comment : ${comments}">
  <div class='comment' th:text='comment'/>
</div>
</code>```

How can I create multiple nesting?

```<code><div class='comments' th:each="comment : ${comments}">
  <div class='comment' th:text='comment'>
      <div class='comment' here comment to comment/>
          etc..
  </div>
</div>
</code>```

答:
I think you'll have to do this with fragments.  For example, with an object like this:

Objects

```<code>class Comment {
    private String text;
    private List<Comment> children = new ArrayList<>();

    public Comment(String text, Comment... children) {
        this.text = text;
        this.children.addAll(Arrays.asList(children));
    }

    public String getText() {return text;}
    public void setText(String text) {this.text = text;}

    public List<Comment> getChildren() {return children;}
    public void setChildren(List<Comment> children) {this.children = children;}
}
</code>```

Controller:

```<code>List<Comment> comments = new ArrayList<>();
comments.add(new Comment("hello", new Comment("nooooo")));
comments.add(new Comment("it's another comment", new Comment("again", new Comment("yeah!"))));
comments.add(new Comment("whoopity doo"));
model.put("comments", comments);
</code>```

You can output a chain of nested comments with fragments like this:

```<code><th:block th:each="comment: ${comments}">
    <div th:replace="template :: comments(${comment})" />
</th:block>

<th:block th:if="${false}">
    <ul th:fragment="comments(comment)">
        <li>
            <div th:text="${comment.text}" />

            <th:block th:unless="${#lists.isEmpty(comment.children)}" th:each="child: ${comment.children}">
                <div th:replace="template :: comments(${child})" />
            </th:block>
        </li>
    </ul>
</th:block>
</code>```

Body:
Currently i'm doing website with newsletter posting. I want to post and show comments under every post.

MY POST

first comment

comments to first comment

comments to second comment
-so on...

second comment

third comment

I know how to dynamically create elements in a loop with one level of nesting. But how can i create multiple nesting?

For example I can create comments:

How can I create multiple nesting?

          etc..

Body:
I think you'll have to do this with fragments.  For example, with an object like this:

Objects

class Comment {
    private String text;
    private List<Comment> children = new ArrayList<>();

    public Comment(String text, Comment... children) {
        this.text = text;
        this.children.addAll(Arrays.asList(children));
    }

    public String getText() {return text;}
    public void setText(String text) {this.text = text;}

    public List<Comment> getChildren() {return children;}
    public void setChildren(List<Comment> children) {this.children = children;}
}

Controller:

List<Comment> comments = new ArrayList<>();
comments.add(new Comment("hello", new Comment("nooooo")));
comments.add(new Comment("it's another comment", new Comment("again", new Comment("yeah!"))));
comments.add(new Comment("whoopity doo"));
model.put("comments", comments);

You can output a chain of nested comments with fragments like this:

<th:block th:each="comment: ${comments}">
    <div th:replace="template :: comments(${comment})" />
</th:block>

<th:block th:if="${false}">
    <ul th:fragment="comments(comment)">
        <li>
            <div th:text="${comment.text}" />

            <th:block th:unless="${#lists.isEmpty(comment.children)}" th:each="child: ${comment.children}">
                <div th:replace="template :: comments(${child})" />
            </th:block>
        </li>
    </ul>
</th:block>


问:
all inputs of a certain class to json
I have this type of html:

```<code><input id='a1' name='a1' value='111' class='hey'/>
<input id='b1' name='b1' value='222' class='hey'/>
<input id='c1' name='b1' value='333' class='hey'/>
</code>```

and I need to obtain this json from it:

```<code>{ a1: '111', b1: '222', c1: '333' }
</code>```

anybody knows how ?

答:
```<code>var json = {};

$('input.hey').each(function(index) {
  json[$(this).attr('name')] = $(this).val();
});
</code>```

Title: all inputs of a certain class to json

Body:
I have this type of html:

<input id='a1' name='a1' value='111' class='hey'/>
<input id='b1' name='b1' value='222' class='hey'/>
<input id='c1' name='b1' value='333' class='hey'/>

and I need to obtain this json from it:

{ a1: '111', b1: '222', c1: '333' }

anybody knows how ?