问:
adding missing dates into a data table based on some conditions in R
I have a data table like this :

```<code>timestamp    Status
05-01-2020    0
06-01-2020    0
07-01-2020    1
08-01-2020    1
09-01-2020    1
11-01-2020    0
13-01-2020    1
</code>```

If The status is 1 and status 0 are appearing on two different days, then I need to fill the missing dates. Here on 9th last value of status is 1 and it is becoming 0 on 11th only. So in between I have 10th. I need to add these dates to the existing data table  or create a new data table and put status as 1

I am aware of this :

```<code>library(tidyverse)

complete(dt, status, timestamp)
</code>```

Expected output:

```<code> timestamp    Status
    05-01-2020    0
    06-01-2020    0
    07-01-2020    1
    08-01-2020    1
    09-01-2020    1
    10-01-2020    1
    11-01-2020    0
    13-01-2020    1
</code>```

This should repeat for any number of days in between. But only for conditions between 1 and 0 and not between 0 and 1

答:
This is an interesting question. If I understand correctly, the OP asks to insert additional rows between each group of contiguous values of Status if the previuos group had Status == 1 and the current group has Status == 0. In addtion, I understand that filling up missing dates within a streak of Status == 1 is not requested.

So here are two different data.table approaches:

1. Grouping and prepending additional rows to each Status == 0 group

This solution borrows from Matt Dowle's answer to Get the last row of a previous group in data.table (see here for another use case).

It creates groups of contiguous streaks of 0/1 values in Status (using rleid()). For each group, it is checked whether it is required to insert rows. If so, the additional rows are prepended to the rows of the current group (using rbind()).

```<code>library(data.table)
options(datatable.print.class = TRUE)
dt[, timestamp := as.IDate(timestamp, "%d-%m-%Y")]   # coerce character date to numeric
dt[, grp := rleid(Status)]   # create groups of consecutive values of Status
dt[, new := ""]   # just for test & demonstration
pg <- first(dt)  # initialise storage of last row of previous group
dt[, {
  if (first(timestamp) - pg$timestamp > 1L & pg$Status == 1L) {
    # if there is a gap and Status switches from 1 to 0 the fill the gap
    add <- .(timestamp = seq(pg$timestamp + 1L, first(timestamp) - 1L, by = 1L), Status = 1L, new = "*")
  } else {
    # no gap to fill
    add <- .SD[0L]
  }
  pg <- last(.SD)   # remember last row
  rbind(add, .SD)   # prepend additional rows
}, by = grp][, grp := NULL][]   # remove grouping variable
</code>```

```<code>     timestamp Status    new
        <IDat>  <int> <char>
 1: 2020-01-05      0
 2: 2020-01-06      0
 3: 2020-01-07      1
 4: 2020-01-08      1
 5: 2020-01-09      1
 6: 2020-01-10      1      *
 7: 2020-01-11      0
 8: 2020-01-13      1
 9: 2020-01-14      0
10: 2020-01-16      1
11: 2020-01-17      1
12: 2020-01-18      1      *
13: 2020-01-19      1      *
14: 2020-01-20      0
</code>```

Note that an enhanced dataset has been used (see below) to allow for a more thoroughly testing. Also, the column new has been added just to demonstrate where the rows have been inserted.

2. Identify gaps, create missing rows, append and re-order

This approach is different. It identifies the gaps which are to be filled, creates the missing rows, appends them to the original dataset, and re-orders the rows by timestamp:

```<code>library(data.table)
options(datatable.print.class = TRUE)
library(magrittr)   # piping used to improve readability
dt[, timestamp := as.IDate(timestamp, "%d-%m-%Y")] # coerce character date to numeric
lapply(
  dt[, .I[timestamp - shift(timestamp, fill = first(timestamp)) > 1L & shift(Status) == 1 & Status == 0]],
  function(i) dt[, .(timestamp = seq(timestamp[i - 1L] + 1L, timestamp[i] - 1L, by = 1L), Status = 1L)]
) %>%
  c(list(dt)) %>%
  rbindlist() %>%
  .[order(timestamp)]
</code>```

```<code>     timestamp Status
        <IDat>  <int>
 1: 2020-01-05      0
 2: 2020-01-06      0
 3: 2020-01-07      1
 4: 2020-01-08      1
 5: 2020-01-09      1
 6: 2020-01-10      1
 7: 2020-01-11      0
 8: 2020-01-13      1
 9: 2020-01-14      0
10: 2020-01-16      1
11: 2020-01-17      1
12: 2020-01-18      1
13: 2020-01-19      1
14: 2020-01-20      0
</code>```

The expression

```<code>dt[, .I[timestamp - shift(timestamp, fill = first(timestamp)) > 1L & shift(Status) == 1 & Status == 0]]
</code>```

identifies the gaps to be filled by returning the indices in the original dataset dt where the additional rows need to be inserted before.

```<code>[1]  6 11
</code>```

So, the additional rows need to be inserted between rows 5 to 6, and 10 to 11, resp.

3. Data

The dataset has been expanded to allow for a more thoroughly testing.

```<code>dt <- fread(
  "timestamp    Status
05-01-2020    0
06-01-2020    0
07-01-2020    1
08-01-2020    1
09-01-2020    1
11-01-2020    0
13-01-2020    1
14-01-2020    0
16-01-2020    1
17-01-2020    1
20-01-2020    0")
</code>```

Note that all solutions posted so far assume that dt is ordered by increasing timestamp. If not, it can be achieved by

```<code>setorder(dt, timestamp)
</code>```

Body:
I have a data table like this :

timestamp    Status
05-01-2020    0
06-01-2020    0
07-01-2020    1
08-01-2020    1
09-01-2020    1
11-01-2020    0
13-01-2020    1

If The status is 1 and status 0 are appearing on two different days, then I need to fill the missing dates. Here on 9th last value of status is 1 and it is becoming 0 on 11th only. So in between I have 10th. I need to add these dates to the existing data table  or create a new data table and put status as 1

I am aware of this :

library(tidyverse)

complete(dt, status, timestamp)

Expected output:

 timestamp    Status
    05-01-2020    0
    06-01-2020    0
    07-01-2020    1
    08-01-2020    1
    09-01-2020    1
    10-01-2020    1
    11-01-2020    0
    13-01-2020    1

This should repeat for any number of days in between. But only for conditions between 1 and 0 and not between 0 and 1

Body:
This is an interesting question. If I understand correctly, the OP asks to insert additional rows between each group of contiguous values of Status if the previuos group had Status == 1 and the current group has Status == 0. In addtion, I understand that filling up missing dates within a streak of Status == 1 is not requested.

So here are two different data.table approaches:

1. Grouping and prepending additional rows to each Status == 0 group

This solution borrows from Matt Dowle's answer to Get the last row of a previous group in data.table (see here for another use case).

It creates groups of contiguous streaks of 0/1 values in Status (using rleid()). For each group, it is checked whether it is required to insert rows. If so, the additional rows are prepended to the rows of the current group (using rbind()).

library(data.table)
options(datatable.print.class = TRUE)
dt[, timestamp := as.IDate(timestamp, "%d-%m-%Y")]   # coerce character date to numeric
dt[, grp := rleid(Status)]   # create groups of consecutive values of Status
dt[, new := ""]   # just for test & demonstration
pg <- first(dt)  # initialise storage of last row of previous group
dt[, {
  if (first(timestamp) - pg$timestamp > 1L & pg$Status == 1L) {
    # if there is a gap and Status switches from 1 to 0 the fill the gap
    add <- .(timestamp = seq(pg$timestamp + 1L, first(timestamp) - 1L, by = 1L), Status = 1L, new = "*")
  } else {
    # no gap to fill
    add <- .SD[0L]
  }
  pg <- last(.SD)   # remember last row
  rbind(add, .SD)   # prepend additional rows
}, by = grp][, grp := NULL][]   # remove grouping variable

     timestamp Status    new
        <IDat>  <int> <char>
 1: 2020-01-05      0
 2: 2020-01-06      0
 3: 2020-01-07      1
 4: 2020-01-08      1
 5: 2020-01-09      1
 6: 2020-01-10      1      *
 7: 2020-01-11      0
 8: 2020-01-13      1
 9: 2020-01-14      0
10: 2020-01-16      1
11: 2020-01-17      1
12: 2020-01-18      1      *
13: 2020-01-19      1      *
14: 2020-01-20      0

Note that an enhanced dataset has been used (see below) to allow for a more thoroughly testing. Also, the column new has been added just to demonstrate where the rows have been inserted.

2. Identify gaps, create missing rows, append and re-order

This approach is different. It identifies the gaps which are to be filled, creates the missing rows, appends them to the original dataset, and re-orders the rows by timestamp:

library(data.table)
options(datatable.print.class = TRUE)
library(magrittr)   # piping used to improve readability
dt[, timestamp := as.IDate(timestamp, "%d-%m-%Y")] # coerce character date to numeric
lapply(
  dt[, .I[timestamp - shift(timestamp, fill = first(timestamp)) > 1L & shift(Status) == 1 & Status == 0]],
  function(i) dt[, .(timestamp = seq(timestamp[i - 1L] + 1L, timestamp[i] - 1L, by = 1L), Status = 1L)]
) %>%
  c(list(dt)) %>%
  rbindlist() %>%
  .[order(timestamp)]

     timestamp Status
        <IDat>  <int>
 1: 2020-01-05      0
 2: 2020-01-06      0
 3: 2020-01-07      1
 4: 2020-01-08      1
 5: 2020-01-09      1
 6: 2020-01-10      1
 7: 2020-01-11      0
 8: 2020-01-13      1
 9: 2020-01-14      0
10: 2020-01-16      1
11: 2020-01-17      1
12: 2020-01-18      1
13: 2020-01-19      1
14: 2020-01-20      0

The expression

dt[, .I[timestamp - shift(timestamp, fill = first(timestamp)) > 1L & shift(Status) == 1 & Status == 0]]

identifies the gaps to be filled by returning the indices in the original dataset dt where the additional rows need to be inserted before.

[1]  6 11

So, the additional rows need to be inserted between rows 5 to 6, and 10 to 11, resp.

3. Data

The dataset has been expanded to allow for a more thoroughly testing.

dt <- fread(
  "timestamp    Status
05-01-2020    0
06-01-2020    0
07-01-2020    1
08-01-2020    1
09-01-2020    1
11-01-2020    0
13-01-2020    1
14-01-2020    0
16-01-2020    1
17-01-2020    1
20-01-2020    0")

Note that all solutions posted so far assume that dt is ordered by increasing timestamp. If not, it can be achieved by

setorder(dt, timestamp)


来源: stackexchange

问:
Can I generate a REST service from a GraphQL schema?
I'd like to build a Django app with both a GraphQL endpoint and a REST API. Maintaining both separately would be too much of a pain; I'm looking for a good way to only maintain the GraphQL service and have the REST endpoints generated automagically.

Does anyone know about a good way to do this?

I know there are ways to build a GraphQL server on top of REST endpoints, but I'd rather have it the other way around, as the REST API requirement might go away in the future.

答:
If you don't mind using Node.js, there is a library that does that (graphql2rest): https://github.com/sisense/graphql2rest

You can use it to automatically generate a REST API from your existing GraphQL schema.

"GraphQL2REST is a Node.js library that reads your GraphQL schema and a user-provided manifest file and automatically generates an Express router with fully RESTful HTTP routes — a full-fledged REST API."

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Passing parameter from android to .net web service
Im using ksoap2 to call web .net services. The call works just fine except when I pass paramaters. The passed paramaters are always recieved as null values by the web service. I dont know what the problem is, I hope someone can help. Thanks,

My code is below please help me

```<code>package com.android.countrycode;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class CountryActivity extends Activity {
    /** Called when the activity is first created. */

    private static final String SOAP_ACTION = "http://www.webserviceX.NET/GetCountryByCountryCode";
    private static final String OPERATION_NAME = "GetCountryByCountryCode";
    private static final String WSDL_TARGET_NAMESPACE = "http://www.webserviceX.NET/";
    private static final String SOAP_ADDRESS = "http://www.webservicex.net/country.asmx";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textView = new TextView(this);
        setContentView(textView);
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
        //PropertyInfo pi = new PropertyInfo();
        //pi.setName("CountryCode");
        //pi.setValue("AS");
        //request.addProperty(pi);
        //request.addAttribute("CountryName", "Portugal");
        //request.setProperty(1, "Portugal");
        request.addProperty("CountryCode","AS");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
        try
        {

        httpTransport.call(SOAP_ACTION, envelope);
        Object response = envelope.getResponse();
        textView.setText(response.toString());
        System.out.println(response.toString());
        }
        catch (Exception exception)
        {
        String exceptionStr=exception.toString();
        textView.setText(exceptionStr);
        System.out.println(exceptionStr);
        Log.i("TAG",exceptionStr);
        }

    }
}
</code>```

答:
May be try this...

```<code>String parameter="as";
</code>```

then

```<code> request.addProperty("CountryCode",parameter);
</code>```

Body:
Im using ksoap2 to call web .net services. The call works just fine except when I pass paramaters. The passed paramaters are always recieved as null values by the web service. I dont know what the problem is, I hope someone can help. Thanks,

My code is below please help me

package com.android.countrycode;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class CountryActivity extends Activity {
    /** Called when the activity is first created. */

    private static final String SOAP_ACTION = "http://www.webserviceX.NET/GetCountryByCountryCode";
    private static final String OPERATION_NAME = "GetCountryByCountryCode";
    private static final String WSDL_TARGET_NAMESPACE = "http://www.webserviceX.NET/";
    private static final String SOAP_ADDRESS = "http://www.webservicex.net/country.asmx";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textView = new TextView(this);
        setContentView(textView);
        SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
        //PropertyInfo pi = new PropertyInfo();
        //pi.setName("CountryCode");
        //pi.setValue("AS");
        //request.addProperty(pi);
        //request.addAttribute("CountryName", "Portugal");
        //request.setProperty(1, "Portugal");
        request.addProperty("CountryCode","AS");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
        try
        {

        httpTransport.call(SOAP_ACTION, envelope);
        Object response = envelope.getResponse();
        textView.setText(response.toString());
        System.out.println(response.toString());
        }
        catch (Exception exception)
        {
        String exceptionStr=exception.toString();
        textView.setText(exceptionStr);
        System.out.println(exceptionStr);
        Log.i("TAG",exceptionStr);
        }

    }
}

Body:
May be try this...

String parameter="as";

then

 request.addProperty("CountryCode",parameter);


问:
Converting timestamp to time ago in PHP - Plurality
With the help of Stackoverflow (Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...) I found out how to convert a timestamp to time ago format in PHP. In the current solution the plurality is defined as + 's' (which is fine in English)... but what to do if you want to change this logic manually for each time unit (because for some languages this logic is not effective)? So for example in Dutch year = jaar and years = jaren, month = maand and months = maanden, week = week and weeks = weken.</p>

```<code>    function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );

    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
</code>```

答:
Here is a version of that function which uses an array for each period to indicate the word to use for singular and plural periods:

```<code>function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $periods = array(
        'y' => ['jaar', 'jaren'],
        'm' => ['maand', 'maanden'],
        'w' => ['week', 'weken'],
        'd' => ['dag', 'dagen'],
        'h' => ['uur', 'uren'],
        'i' => ['minuut', 'minuten'],
        's' => ['seconde', 'seconden']
    );

    $parts = array();
    foreach ($periods as $k => &$v) {
        if ($diff->$k) {
            $parts[] = $diff->$k . ' ' . $v[$diff->$k > 1];
        }
    }

    if (!$full) $parts = array_slice($parts, 0, 1);
    return $parts ? implode(', ', $parts) . ' ago' : 'just now';
}
</code>```

Sample usage:

```<code>echo time_elapsed_string('2020-03-21 00:30:16') . PHP_EOL;
echo time_elapsed_string('2020-03-21 00:30:16', true) . PHP_EOL;
</code>```

Output:

```<code>2 maanden ago
2 maanden, 1 week, 3 dagen, 14 uren, 6 minuten, 55 seconden ago
</code>```

Demo on 3v4l.org

Body:
With the help of Stackoverflow (Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...) I found out how to convert a timestamp to time ago format in PHP. In the current solution the plurality is defined as + 's' (which is fine in English)... but what to do if you want to change this logic manually for each time unit (because for some languages this logic is not effective)? So for example in Dutch year = jaar and years = jaren, month = maand and months = maanden, week = week and weeks = weken.

    function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );

    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

Body:
Here is a version of that function which uses an array for each period to indicate the word to use for singular and plural periods:

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $periods = array(
        'y' => ['jaar', 'jaren'],
        'm' => ['maand', 'maanden'],
        'w' => ['week', 'weken'],
        'd' => ['dag', 'dagen'],
        'h' => ['uur', 'uren'],
        'i' => ['minuut', 'minuten'],
        's' => ['seconde', 'seconden']
    );

    $parts = array();
    foreach ($periods as $k => &$v) {
        if ($diff->$k) {
            $parts[] = $diff->$k . ' ' . $v[$diff->$k > 1];
        }
    }

    if (!$full) $parts = array_slice($parts, 0, 1);
    return $parts ? implode(', ', $parts) . ' ago' : 'just now';
}

Sample usage:

echo time_elapsed_string('2020-03-21 00:30:16') . PHP_EOL;
echo time_elapsed_string('2020-03-21 00:30:16', true) . PHP_EOL;

Output:

2 maanden ago
2 maanden, 1 week, 3 dagen, 14 uren, 6 minuten, 55 seconden ago

Demo on 3v4l.org


问:
LoadLibraryExW() fails, last error is ERROR_MOD_NOT_FOUND, but no missing dependencies?
A customer is using our dll which is creating a child process which uses an open source library, which ultimately fails because of a call to LoadLibraryExW(), the last error returned is ERROR_MOD_NOT_FOUND.  This occurs on WinXP 32-bit, but not on other machines.  But we know the correct set of dependencies is installed and even in the same directory.

So we thought naturally, to use Dependency Walker to look for what dependency is missing on that particular machine.  Unfortunately it doesn't show any missing, just some delay-load warnings that aren't direct dependencies of the library.  In my experience using depends.exe has always revealed what the missing dependency is.

So at this point I've pulled my hair out trying to understand why I'm getting ERROR_MOD_NOT_FOUND if all of the library's dependencies are there?  The only other thing that makes this machine unique is it's very secure because it's used by the government, but if we were having an access/permissions issue I'd expect a different type of error code.

I've built a small Win32 executable that does nothing but call LoadLibraryExW() on the said library, when it's run from the same directory as the library is located, it loads the library without issue, on the customer's problematic machine.

One thing is that our product is an ActiveX plugin which launches a child process, the child process calls into the 3rd party library, the 3rd party library has the problematic LoadLibraryExW() call.  So maybe why it's failing is the context it's running (e.g. from the browser)?

答:
Your dependencies might be present on the system but they could be in a folder that is not part of the search order during LoadLibraryExW().
A SetDllDirectory() or AddDllDirectory() call would ensure that the folder containing the dependencies is searched during the LoadLibraryExW() call</p>


问:
Automatically set appsettings.json for dev and release environments in asp.net core?
I've defined some values in my appsettings.json for things like database connection strings, webapi locations and the like which are different for development, staging and live environments.

Is there a way to have multiple appsettings.json files (like appsettings.live.json, etc, etc) and have the asp.net app just 'know' which one to use based on the build configuration it's running?

答:
.vscode/launch.json file is only used by Visual Studio as well as /Properties/launchSettings.json file. Don't use these files in production.

The launchSettings.json file:

Is only used on the local development machine.

Is not deployed.

contains profile settings.

Environment values set in launchSettings.json override values set in the system environment

To use a file 'appSettings.QA.json' for example. You can use 'ASPNETCORE_ENVIRONMENT'. Follow the steps below.

Add a new Environment Variable on the host machine and call it 'ASPNETCORE_ENVIRONMENT'. Set its value to 'QA'.

Create a file 'appSettings.QA.json' in your project. Add your configuration here.

Deploy to the machine in step 1. Confirm 'appSettings.QA.json' is deployed.

Load your website. Expect appSettings.QA.json to be used in here.


问:
two algorithms, same results on my machine, different results on tests
I am new in code, so, it would be cool,if somebody would helo me.
Task:
You have target-numer and a lot of other numbers. You need to find the numbers that you add up to get a sum equal to the target-number. If you found this numbers, you type "1" in out-put file, otherwise type "0". All numbers are in diapason 0 < N < 999 999 999

input-file format:
5
1 8 9 2 4 1 5 3....

I wrote 2 different algorithms, both work correctly. But I have tests,(no code sources, they are on the website, where I found task) and first algorithm passes all test accept of speed-test, but second can't pass even 1st test, have error "wrong answer".
I want to test my fastest version.
This algorithm does:

Open the file with numbers.

Convert all strings with numbers to numbers. Write all the numbers in a slice.

Write the target from the array to a separate variable. Target = the first element of the slice due to the input format.

Create a new slice. Rewrite it with all the numbers that < = target.

Sort the slice in ascending order (built-in sorting from golang)

Find the sum:
6.1 take the current slice element and subtract it from the target. The resulting number = the second term.
6.2 using the binary array dissection Method, we search for this number in the slice. (method from golanfg package)
6.3 If found, write 1 to the output file and exit the program.
6.4 Otherwise go to a new iteration of the loop and return to point 6.1
6.5 If the cycle has ended and we haven't left the program, we assume that there are no 2 numbers forming the sum for the target. print 0 to the output file.

Could you help me to find, where is mistake?
Here is the link for the file on my git:
https://github.com/0xBECEDA/ozon-tasks/blob/master/task-f/SO1.go
This file will create test-file with numbers:
https://github.com/0xBECEDA/ozon-tasks/blob/master/task-f/make-test-file.go
This is test-file:
https://github.com/0xBECEDA/ozon-tasks/blob/master/task-f/input.txt

答: first your problem, you read input from file to only 100 byte slice, but your input data can consume more place All numbers are in diapason 0 < N < 999 999 999 ,so i think you don`t read all the data from file


问:
Floating point multiplication on VC++ 2008 express
why the following snippet

```<code>int i = 30;
int p = 0.7f * i;
printf("p is %d\n", p);
</code>```

gives 20 instead of 21 on vc++ 2008 express ?
I know it's an old compiler!

答:
The number 0.7 is not representable in the binary-based floating-point format your compiler uses for float. When the decimal numeral “0.7” is converted to float, the result is the nearest representable value. That is a number slightly below 0.7.

Multiplying that by 30 produces a number slightly below 21, and converting it to int with truncation produces 20.

Body:
why the following snippet

int i = 30;
int p = 0.7f * i;
printf("p is %d\n", p);

gives 20 instead of 21 on vc++ 2008 express ?
I know it's an old compiler!


问:
How to order html elements in the same order as array using jQuery?
I'd like to order html elements in the same order as arrayData.

JavaScript

```<code>    var arrayData = [59, 56, 57];
</code>```

HTML

```<code>    <div class="selectize-input">
        <div class="item" data-value="56">Dog</div>
        <div class="item" data-value="57">Rabbit</div>
        <div class="item" data-value="59">Cat</div>
    </div>
</code>```

I want the result like this.

```<code>    <div class="selectize-input">
        <div class="item" data-value="59">Cat</div>
        <div class="item" data-value="56">Dog</div>
        <div class="item" data-value="57">Rabbit</div>
    </div>
</code>```

Is there any good way to achive this?
Thank you in advance.

[Additional]
I want to get result something like this, but don't now how to apply it to html elements and render on browser.

```<code>const orderRule = ['Cat', 'Rabbit', 'Dog', 'Pig', 'Mouse'],
      array = ['Mouse','Rabbit', 'Pig', 'Dog', 'Cat'];

const sortArray = [...array].sort((a, b) => orderRule.indexOf(a) - orderRule.indexOf(b));
console.log(sortArray);
</code>```

答:
You can loop over your array using $.each and then use append to add div at particular position.

Here is demo code :

var arrayData = [59, 56, 57];
//looping through array
$.each(arrayData, function() {
//append div at particular positon using data-value
  $(".selectize-input").append($("div [data-value=" + this + "]"));
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="selectize-input">
  <div class="item" data-value="56">Dog</div>
  <div class="item" data-value="57">Rabbit</div>
  <div class="item" data-value="59">Cat</div>
</div></code>```

Body:
I'd like to order html elements in the same order as arrayData.

JavaScript

    var arrayData = [59, 56, 57];

HTML

Dog

Rabbit

Cat

I want the result like this.

Cat

Dog

Rabbit

Is there any good way to achive this?
Thank you in advance.

[Additional]
I want to get result something like this, but don't now how to apply it to html elements and render on browser.

const orderRule = ['Cat', 'Rabbit', 'Dog', 'Pig', 'Mouse'],
      array = ['Mouse','Rabbit', 'Pig', 'Dog', 'Cat'];

const sortArray = [...array].sort((a, b) => orderRule.indexOf(a) - orderRule.indexOf(b));
console.log(sortArray);

Body:
You can loop over your array using $.each and then use append to add div at particular position.

Here is demo code :

var arrayData = [59, 56, 57];
//looping through array
$.each(arrayData, function() {
//append div at particular positon using data-value
  $(".selectize-input").append($("div [data-value=" + this + "]"));
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="selectize-input">
  <div class="item" data-value="56">Dog</div>
  <div class="item" data-value="57">Rabbit</div>
  <div class="item" data-value="59">Cat</div>
</div>


问:
java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED
I have a service that is expected to execute requests at ~5 or more requests/min. This service depends on Apache AsyncHttpClient. After every few minutes, the clients hits some condition which causes java.lang.IllegalStateException: Request cannot be executed; I/O reactor status: STOPPED. All requests to the client start failing with same exception message. After service is restarted, this cycle repeats.

It is really hard to debug this problem as the request execution failure surprisingly does not cause a callback to the failed() method of the AsyncResponse.

From what I could gather, there has been a fix HTTPCORE-370 in HttpCore NIO which solved a similar problem in 4.3.2. I am using the following version -

commons-httpclient-3.1.jar

httpasyncclient-4.1.1.jar

httpcore-4.4.4.jar

httpcore-nio-4.4.4.jar

Yet seeing this problem.

答:
In my case, using Elasticsearch high level client, this exception is due to esclient.indexAsync(indexRequest,RequestOptions.DEFAULT,null)

I fixed it by add an action listeners in all async requests like this

esclient.indexAsync(indexRequest,RequestOptions.DEFAULT,
              new ActionListener<IndexResponse>() {

                    @Override

                    public void onResponse(IndexResponse response) {

                    }
                    @Override
                    public void onFailure(Exception e) {

                });
```


问:
Dynamically changing the height of a div

Possible Duplicate:

  Height of a div

Hello,

I have a DIV where I want the height to be based on the viewable area of the browser - 100px. Is there a way that I can make this happen so that the DIV height is set correctly in the first place and then adjusted if the user goes in and resizes the browser. I imagine this would involve javascript.

Thanks,

答:
There is a post on net Change DIV height/width with body width/height using jQuery

```<code><script language=”javascript”>

$(document).ready(function(){

var height1 = $(document).height(); // height of full document

var height2 = $(“#header”).height(); // height of header

var height_diff = height1 – height2 + “px”;

document.getElementById(‘test’).style.height = height_diff; // Set the remaining height in test DIV.

});

</script>
</code>```

where test is the div's id.

Body:
There is a post on net Change DIV height/width with body width/height using jQuery

<script language=”javascript”>

$(document).ready(function(){

var height1 = $(document).height(); // height of full document

var height2 = $(“#header”).height(); // height of header

var height_diff = height1 – height2 + “px”;

document.getElementById(‘test’).style.height = height_diff; // Set the remaining height in test DIV.

});

</script>

where test is the div's id.


问:
Why the if condition is always false?
I was doing some java coding exercises and this add 2 binary number exercise.
I am not sure why the if condition is always false, even if I put actual int into the variable.

whats the problem???

```<code>public class Main {
    public static void main(String[]args){
        long bin1 = 10, bin2 = 101;
        int carry = 0, i = 0;

        int bin1Length = String.valueOf(bin1).length();
        int bin2Length = String.valueOf(bin2).length();
        int length;

        System.out.println("bin1: " + bin1Length);
        System.out.println("bin2: " + bin2Length);

        if(bin1Length > bin2Length){     // not sure why its always false in all 3 conditions
            length = bin1Length;
        } else if (bin2Length < bin1Length){
            length = bin2Length;
        } else if (bin1Length == bin2Length){
            length = bin1Length;
        }

        int [] finalOutput = new int [length];

        while(bin1 != 0 || bin2 != 0){
            finalOutput[i++] = (int)(carry + (bin1 % 10 + bin2 % 10) % 2);
            carry = (int)((carry + bin1 % 10 + bin2 % 10)/2);
            bin1 = bin1/10;
            bin2 = bin2/10;
        }

        if(carry != 0){
            finalOutput[i] = carry;
        }

        System.out.print("Output: ");

        while(i >= 0){
            System.out.print(finalOutput[i--]);
        }
    }
}
</code>```

edit: and this is the error.

Thanks.

答:
bin1Length is 2 and bin2Length is 3. That's why the if condition will always be false.

Also, optimized code would be:

```<code>length = bin1Length;
if (bin2Length > bin1Length)
    length = bin2Length;
</code>```

Title: Why the if condition is always false?

Body:
I was doing some java coding exercises and this add 2 binary number exercise.
I am not sure why the if condition is always false, even if I put actual int into the variable.

whats the problem???

public class Main {
    public static void main(String[]args){
        long bin1 = 10, bin2 = 101;
        int carry = 0, i = 0;

        int bin1Length = String.valueOf(bin1).length();
        int bin2Length = String.valueOf(bin2).length();
        int length;

        System.out.println("bin1: " + bin1Length);
        System.out.println("bin2: " + bin2Length);

        if(bin1Length > bin2Length){     // not sure why its always false in all 3 conditions
            length = bin1Length;
        } else if (bin2Length < bin1Length){
            length = bin2Length;
        } else if (bin1Length == bin2Length){
            length = bin1Length;
        }

        int [] finalOutput = new int [length];

        while(bin1 != 0 || bin2 != 0){
            finalOutput[i++] = (int)(carry + (bin1 % 10 + bin2 % 10) % 2);
            carry = (int)((carry + bin1 % 10 + bin2 % 10)/2);
            bin1 = bin1/10;
            bin2 = bin2/10;
        }

        if(carry != 0){
            finalOutput[i] = carry;
        }

        System.out.print("Output: ");

        while(i >= 0){
            System.out.print(finalOutput[i--]);
        }
    }
}

edit: and this is the error.

Thanks.

Body:
bin1Length is 2 and bin2Length is 3. That's why the if condition will always be false.

Also, optimized code would be:

length = bin1Length;
if (bin2Length > bin1Length)
    length = bin2Length;


问:
SQL query to return The last name of actor who has worked with each actor the most
I am new to sql and im trying to write a query to return the last name of an actor who has worked with each actor the most.

I have 3 tables

```<code>Actor- id, first_name,last_name
Movie- id, title
Cast- pid, mid
</code>```

This is what I got now but it doesn't work:

```<code>SELECT tt.ll
FROM Actor as AA ,Movie,Cast,(select a.id as idd, a.first_name,a.last_name as ll, count(*)
from Actor a
join Cast c on c.pid = a.id
where mid in (select mid from Cast where pid = AA.id)
and pid <> AA.id
group by a.id
order by count(*) desc, a.last_name ASC limit 1) tt
WHERE pid=AA.id AND Cast.mid=Movie.id
group by AA.id;
</code>```

答:
You can get the number of times that pairs of actors work together with a self join on cast or a correlated subquery:

```<code>select c.aid, c2.aid, count(*)
from cast c join
     cast c2
     on c.mid = c2.mid   -- same movie
group by c.aid, c2.aid
</code>```

To get the most for each actor in column one, use a window function:

```<code>select aa.*
from (select c.aid, c2.aid as aid_2, count(*) as cnt,
             row_number() over (partition by c.aid order by count(*) desc) as seqnum
      from cast c join
           cast c2
           on c.mid = c2.mid   -- same movie
      group by c.aid, c2.aid
     ) aa
where seqnum = 1;
</code>```

Then to fill in the movies, you can use two joins to the actors table.  I'll let you construct that.

Body:
I am new to sql and im trying to write a query to return the last name of an actor who has worked with each actor the most.

I have 3 tables

Actor- id, first_name,last_name
Movie- id, title
Cast- pid, mid

This is what I got now but it doesn't work:

SELECT tt.ll
FROM Actor as AA ,Movie,Cast,(select a.id as idd, a.first_name,a.last_name as ll, count(*)
from Actor a
join Cast c on c.pid = a.id
where mid in (select mid from Cast where pid = AA.id)
and pid <> AA.id
group by a.id
order by count(*) desc, a.last_name ASC limit 1) tt
WHERE pid=AA.id AND Cast.mid=Movie.id
group by AA.id;

Body:
You can get the number of times that pairs of actors work together with a self join on cast or a correlated subquery:

select c.aid, c2.aid, count(*)
from cast c join
     cast c2
     on c.mid = c2.mid   -- same movie
group by c.aid, c2.aid

To get the most for each actor in column one, use a window function:

select aa.*
from (select c.aid, c2.aid as aid_2, count(*) as cnt,
             row_number() over (partition by c.aid order by count(*) desc) as seqnum
      from cast c join
           cast c2
           on c.mid = c2.mid   -- same movie
      group by c.aid, c2.aid
     ) aa
where seqnum = 1;

Then to fill in the movies, you can use two joins to the actors table.  I'll let you construct that.


问:
Matplotlib: how to call a pick_event only upon a left-click button_press_event?
I have a simple interactive plot with a button_press_event and a pick_event handler:

```<code>    fig, ax1 = plt.subplots()
    line, = ax1.plot(x, y, picker=10)

    def pick_handler(event):
        print "Pick_handler called!"
        if isinstance(event.artist, Line2D):
            # do something

    def click_handler(event):
        if event.button == 1:
            print "Click_handler called by left-click!"
            fig.canvas.mpl_connect('pick_event', pick_handler)
        if event.button == 3:
            print "Click_handler called by right-click!"
            # do something

    fig.canvas.mpl_connect('button_press_event', click_handler)
    plt.show()
</code>```

The desired behaviour is the following: only if I do a left-click in the plot, the pick_handler() should be called.

The given code behaves not as desired, there are several strange things happening.

1) When the plot appears and I do the first left-click anywhere in the plot, the click_handler() is called and print "Click_handler called by left-click!" is executed, but the pick_handler() is not called; only beginning with the second left-click the pick_handler() is called.

2) When I do the second and any further left-click anywhere in the plot, the click_handler() first calls the pick_handler() and only after that print "Click_handler called by left-click!" is executed, but according to the code it should be vice versa.

3) When the plot appears and my very first click is a right-click anywhere in the plot (aynwhere means even if I right-click some Line2D object), the code acts correctly – it just calls the click_handler() and executes print "Click_handler called by right-click!". But if my very first click is a left-click anywhere in the plot, and the second click is a right-click on some Line2D object in the plot, then the code calls the click_handler(), the click_handler() first calls and fully executes the pick_handler() and then executes print "Click_handler called by right-click!", but according to the code the pick_handler() should never be called by any right-click.

Is my code wrong or is my understanding of click- and pick-handlers wrong?

答:
I think the following code is doing what you wanted:</p>

```<code>fig, ax1 = plt.subplots()
line, = ax1.plot(x, y, 'o', picker=10)

def pick_handler(event):
    print("Pick_handler called!")
    if event.mouseevent.button==1 and isinstance(event.artist, Line2D):
        print("Do the thing.")

def click_handler(event):
    if event.button == 3:
        print("Click_handler called by right-click!")
        # do something

fig.canvas.mpl_connect('pick_event', pick_handler)
fig.canvas.mpl_connect('button_press_event', click_handler)
plt.show()
</code>```

Body:
I have a simple interactive plot with a button_press_event and a pick_event handler:

    fig, ax1 = plt.subplots()
    line, = ax1.plot(x, y, picker=10)

    def pick_handler(event):
        print "Pick_handler called!"
        if isinstance(event.artist, Line2D):
            # do something

    def click_handler(event):
        if event.button == 1:
            print "Click_handler called by left-click!"
            fig.canvas.mpl_connect('pick_event', pick_handler)
        if event.button == 3:
            print "Click_handler called by right-click!"
            # do something

    fig.canvas.mpl_connect('button_press_event', click_handler)
    plt.show()

The desired behaviour is the following: only if I do a left-click in the plot, the pick_handler() should be called.

The given code behaves not as desired, there are several strange things happening.

1) When the plot appears and I do the first left-click anywhere in the plot, the click_handler() is called and print "Click_handler called by left-click!" is executed, but the pick_handler() is not called; only beginning with the second left-click the pick_handler() is called.

2) When I do the second and any further left-click anywhere in the plot, the click_handler() first calls the pick_handler() and only after that print "Click_handler called by left-click!" is executed, but according to the code it should be vice versa.

3) When the plot appears and my very first click is a right-click anywhere in the plot (aynwhere means even if I right-click some Line2D object), the code acts correctly – it just calls the click_handler() and executes print "Click_handler called by right-click!". But if my very first click is a left-click anywhere in the plot, and the second click is a right-click on some Line2D object in the plot, then the code calls the click_handler(), the click_handler() first calls and fully executes the pick_handler() and then executes print "Click_handler called by right-click!", but according to the code the pick_handler() should never be called by any right-click.

Is my code wrong or is my understanding of click- and pick-handlers wrong?

Body:
I think the following code is doing what you wanted:

fig, ax1 = plt.subplots()
line, = ax1.plot(x, y, 'o', picker=10)

def pick_handler(event):
    print("Pick_handler called!")
    if event.mouseevent.button==1 and isinstance(event.artist, Line2D):
        print("Do the thing.")

def click_handler(event):
    if event.button == 3:
        print("Click_handler called by right-click!")
        # do something

fig.canvas.mpl_connect('pick_event', pick_handler)
fig.canvas.mpl_connect('button_press_event', click_handler)
plt.show()


问:
Slow rendering objects while scrolling through a .net FlowLayoutControl
I have a FlowLayoutControl on my form that I am populating with 20-100 graphics heavy UserControls. The only problem I am having is that, while scrolling, the graphics "drag" (similar to dragging windows while it's slow, creating a duplicate image wherever the window is dragged).

I need a way to be able to scroll through the FLC without the images dragging or glitching.  I need the scrolling to be smooth.  Is there any possible way to buffer the controls or fix this problem without any MAJOR changes?

Thanks if you can!

(If you are confused about what I mean when referring to "Window Lag", it's something similar to the following example here)

Here is an actual picture of the lag issue I am dealing with:

答:
I had a similar problem and found that setting the WS_EX_COMPOSITED extended style on the parent form fixed it.

```<code>protected override CreateParams CreateParams
{
   get
   {
       CreateParams cp = base.CreateParams;
       cp.ExStyle |= 0x02000000;
       return cp;
   }
}
</code>```

See http://social.msdn.microsoft.com/forums/en-US/winforms/thread/aaed00ce-4bc9-424e-8c05-c30213171c2c/

ContentLicense: CC BY-SA 2.5

Body:
I had a similar problem and found that setting the WS_EX_COMPOSITED extended style on the parent form fixed it.

protected override CreateParams CreateParams
{
   get
   {
       CreateParams cp = base.CreateParams;
       cp.ExStyle |= 0x02000000;
       return cp;
   }
}

See http://social.msdn.microsoft.com/forums/en-US/winforms/thread/aaed00ce-4bc9-424e-8c05-c30213171c2c/


问:
Execute an Authorization Code Grant Flow Using Java Spring Rest Api
I'm trying to call a 3rd party endpoint that requires authorization using Java spring rest Api, so I need to execute an Authorization Code Grant Flow.

I understand the flow where I need to first get the code then exchange the code for a JWT and finally use the JWT to be able to do the secure call.

What's not making sense to me is how am I suppose to set up a redirect URI when I'm using solely working with a backend rest api with no UI. Usually the user is redirected to a login page where they either login with a username/password or 3rd party accounts (google/facebook...)

After alot of googling, all the searches ended with guides to secure my own endpoints rather than access a secure endpoint from my spring boot service

Edit: It's worth mentioning that I'm using solely a backend with no front end (or MVC) whatsoever, after @Partha's comment I did the following:

First, I added a new login endpoint, when accessed via browser(this won't work with swagger/postman) it should redirect the user to the Authorization Server:

```<code>@GetMapping
public void login(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", getAuthServerEndpoint());
    httpServletResponse.setStatus(302);
}
</code>```

Where I built the endpoint to have all the data needed (client_id,redirect_uri...) so it looks something like

https://idpserver.bla/oauth/authorize?client_id=xyz&redirect_uri=http://localhost:8080/token&response_type=code&scope=xyz

Now it sends me to the Login page of the auth Server, after I login, I expect it to redirect me to localhost/token (which is a get request that would retrieve the code and do a post request to get a jwt and save it) but instead, I'm receiving a invalid redirect uri and I'm really not sure if this is an issue from my implementation or the server's

EDIT2: I did a dumb mistake by NOT adding http://localhost:8080/token as a redirect url in the Auth Server since I assumed I didn't need to

答: Not really sure how are you trying.. idea here is .. your api server should have a get endpoint /login. In your controller of /login , you should redirect to IDP say http://idpserver.bla?client_id=xxx&grant_type=code&nonce=yyy&redirect_uri=http://localhost:8080/token ( note, its redirect, not make an api request ). So, with this, when you hit http://localhost:8080/login in ur browser, you should see it being redirected to IDP. now you enter ur credentials, IDP validates that and redirect back to http://localhost:8080/token?code=XYZABC or something similar. Your controller code of /token API should read the code from url param. and make a call (this is api call, not redirect) to IDP to exchange the code for a token ( idToken / accessToken) based on your scope. And using the token you should be able to access protected resources. Hope that helps</p>

Body:
I'm trying to call a 3rd party endpoint that requires authorization using Java spring rest Api, so I need to execute an Authorization Code Grant Flow.

I understand the flow where I need to first get the code then exchange the code for a JWT and finally use the JWT to be able to do the secure call.

What's not making sense to me is how am I suppose to set up a redirect URI when I'm using solely working with a backend rest api with no UI. Usually the user is redirected to a login page where they either login with a username/password or 3rd party accounts (google/facebook...)

After alot of googling, all the searches ended with guides to secure my own endpoints rather than access a secure endpoint from my spring boot service

Edit: It's worth mentioning that I'm using solely a backend with no front end (or MVC) whatsoever, after @Partha's comment I did the following:

First, I added a new login endpoint, when accessed via browser(this won't work with swagger/postman) it should redirect the user to the Authorization Server:

@GetMapping
public void login(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", getAuthServerEndpoint());
    httpServletResponse.setStatus(302);
}

Where I built the endpoint to have all the data needed (client_id,redirect_uri...) so it looks something like

https://idpserver.bla/oauth/authorize?client_id=xyz&redirect_uri=http://localhost:8080/token&response_type=code&scope=xyz

Now it sends me to the Login page of the auth Server, after I login, I expect it to redirect me to localhost/token (which is a get request that would retrieve the code and do a post request to get a jwt and save it) but instead, I'm receiving a invalid redirect uri and I'm really not sure if this is an issue from my implementation or the server's

EDIT2: I did a dumb mistake by NOT adding http://localhost:8080/token as a redirect url in the Auth Server since I assumed I didn't need to


问:
replace dot with comma in vba it doesnt work
I have currency sheet and after run my listing I have numbers like Euro currency 45018,0000 instead 4,5018  What is wrong?</p>

```<code>Application.Workbooks("Zaliczenie.xlsm").Worksheets("Arkusz1").Range("G3:H12").Replace What:=".", Replacement:=","
</code>```

答:
Honestly, I do not exactly understand why you are replacing "." with ",", but if I'm right, you want to replace decimal points with ",". If so, the right way to do it is as follows:

```<code>    With Application
        .DecimalSeparator = ","
        .ThousandsSeparator = "."
        .UseSystemSeparators = False
    End With
</code>```

By default, Excel uses system separators for displaying numbers (e.g., 4,5018.00). But after running the code in my answer, you tell the Excel that:

do not use system separators (and use those that are defined by me, instead)

set decimal separator = "," and

set thousands separator = "."

for example, the number 4,5018.00 will be shown as 4.5018,00.

Body:
I have currency sheet and after run my listing I have numbers like Euro currency 45018,0000 instead 4,5018  What is wrong?

Application.Workbooks("Zaliczenie.xlsm").Worksheets("Arkusz1").Range("G3:H12").Replace What:=".", Replacement:=","

Body:
Honestly, I do not exactly understand why you are replacing "." with ",", but if I'm right, you want to replace decimal points with ",". If so, the right way to do it is as follows:

    With Application
        .DecimalSeparator = ","
        .ThousandsSeparator = "."
        .UseSystemSeparators = False
    End With

By default, Excel uses system separators for displaying numbers (e.g., 4,5018.00). But after running the code in my answer, you tell the Excel that:

do not use system separators (and use those that are defined by me, instead)

set decimal separator = "," and

set thousands separator = "."

for example, the number 4,5018.00 will be shown as 4.5018,00.


问:
Python Pexpect and Minicom not working as expected
I need to perform a number of processes to Switch that I can only execute through serial port.
To do this I use Pexpect and Minicom.
I am able to execute the command child.sendcontrol(“c”) to open the menu.
But from the menu I can't choose any of the options.

When I do this manually through the Minicom it works without a problem.
what could be the problem?

Note I use child.after to verify that the actions were actually performed.

This is my code:

```<code>#!/usr/bin/python3

import pexpect

print("Waiting for connection....") # for check
child = pexpect.spawn("minicom")
child.expect(r".*Hit.*", timeout=120)
test = child.after
fileNameone = "/root/Desktop/fileone.txt"
file = open(fileNameone, "wb")
file.write(test)
file.close

child.sendcontrol("c")
print("menu") # for check

child.expect(".*selection.*", timeout=10)
testtwo = child.after
fileNametwo = "/root/Desktop/filetwo.txt"
file = open(fileNametwo, "wb")
file.write(testtwo)
file.close
child.sendline("1")
print("choose 1") # for check

child.expect(".*Gateway.*", timeout=40)
child.sendline("admin")
child.expect(".*Password.*", timeout=10)
child.sendline("admin")
print("connect!") # for check
</code>```

This is the request to press ctrl + c to open the menu (The log was taken from pexpect through minicom):

```<code>[23;80H [24;1H************ Hit 'Ctrl + C' for boot menu ************
[23;80H [24;1H
[23;80H [24;1H 2
</code>```

This is the menu (The log was taken from pexpect through minicom):

```<code>[23;80H [24;1HWelcome to Embedded Boot Menu :
[23;80H [24;1H
[23;80H [24;1H[24;9H1. Start in normal Mode
[23;80H [24;1H[24;9H2. Start in debug Mode
[23;80H [24;1H[24;9H3. Start in maintenance Mode
[23;80H [24;1H[24;9H4. Restore to Factory Defaults (local)
[23;80H [24;1H[24;9H5. Install/Update Image from Network
[23;80H [24;1H[24;9H6. Restart Boot-Loader
[23;80H [24;1H[24;9H7. Run Hardware diagnostics
[23;80H [24;1H[24;9H8. Upload preset configuration file
[23;80H [24;1H[24;9H9. Delete preset configuration file
[23;80H [24;1H
[23;80H [24;1H[24;9HPlease enter your selection (pres
</code>```

I'm trying to choose option 1, for the test.
But it is not performed.
The same goes for each menu option.

```<code>child.expect(".*selection.*", timeout=10)
child.sendline("1")
</code>```

This is the error:
(Should not take more than 15 seconds to boot)

```<code>Traceback (most recent call last):
  File "./test.py", line 33, in <module>
    child.expect(".*Gateway.*", timeout=40)
  File "/usr/local/lib/python3.6/site-packages/pexpect/spawnbase.py", line 344, in expect
    timeout, searchwindowsize, async_)
  File "/usr/local/lib/python3.6/site-packages/pexpect/spawnbase.py", line 372, in expect_list
    return exp.expect_loop(timeout)
  File "/usr/local/lib/python3.6/site-packages/pexpect/expect.py", line 181, in expect_loop
    return self.timeout(e)
  File "/usr/local/lib/python3.6/site-packages/pexpect/expect.py", line 144, in timeout
    raise exc
pexpect.exceptions.TIMEOUT: Timeout exceeded.
<pexpect.pty_spawn.spawn object at 0x7fefa0934a90>
command: /usr/bin/minicom
args: ['/usr/bin/minicom']
buffer (last 100 chars): b's ENTER to finish) :1\r\n\x1b[23;80H \x1b[24;1H'
before (last 100 chars): b's ENTER to finish) :1\r\n\x1b[23;80H \x1b[24;1H'
after: <class 'pexpect.exceptions.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 10862
child_fd: 5
closed: False
timeout: 30
delimiter: <class 'pexpect.exceptions.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
searcher: searcher_re:
    0: re.compile(b'.*Gateway.*')
</code>```

答:
I was able to solve the problem, minicom must get manual enter.
Even that child.sendline sends with Enter.
For some reason the minicom doesn't get the enter.
Child.send ("\r\n") doesn't work either.

The solution is:

After the line child.sendline("1")

I added the line child.sendcontrol("m") for press enter.

Now it works properly.

Body:
I need to perform a number of processes to Switch that I can only execute through serial port.
To do this I use Pexpect and Minicom.
I am able to execute the command child.sendcontrol(“c”) to open the menu.
But from the menu I can't choose any of the options.

When I do this manually through the Minicom it works without a problem.
what could be the problem?

Note I use child.after to verify that the actions were actually performed.

This is my code:

#!/usr/bin/python3

import pexpect

print("Waiting for connection....") # for check
child = pexpect.spawn("minicom")
child.expect(r".*Hit.*", timeout=120)
test = child.after
fileNameone = "/root/Desktop/fileone.txt"
file = open(fileNameone, "wb")
file.write(test)
file.close

child.sendcontrol("c")
print("menu") # for check

child.expect(".*selection.*", timeout=10)
testtwo = child.after
fileNametwo = "/root/Desktop/filetwo.txt"
file = open(fileNametwo, "wb")
file.write(testtwo)
file.close
child.sendline("1")
print("choose 1") # for check

child.expect(".*Gateway.*", timeout=40)
child.sendline("admin")
child.expect(".*Password.*", timeout=10)
child.sendline("admin")
print("connect!") # for check

This is the request to press ctrl + c to open the menu (The log was taken from pexpect through minicom):

[23;80H [24;1H************ Hit 'Ctrl + C' for boot menu ************
[23;80H [24;1H
[23;80H [24;1H 2

This is the menu (The log was taken from pexpect through minicom):

[23;80H [24;1HWelcome to Embedded Boot Menu :
[23;80H [24;1H
[23;80H [24;1H[24;9H1. Start in normal Mode
[23;80H [24;1H[24;9H2. Start in debug Mode
[23;80H [24;1H[24;9H3. Start in maintenance Mode
[23;80H [24;1H[24;9H4. Restore to Factory Defaults (local)
[23;80H [24;1H[24;9H5. Install/Update Image from Network
[23;80H [24;1H[24;9H6. Restart Boot-Loader
[23;80H [24;1H[24;9H7. Run Hardware diagnostics
[23;80H [24;1H[24;9H8. Upload preset configuration file
[23;80H [24;1H[24;9H9. Delete preset configuration file
[23;80H [24;1H
[23;80H [24;1H[24;9HPlease enter your selection (pres

I'm trying to choose option 1, for the test.
But it is not performed.
The same goes for each menu option.

child.expect(".*selection.*", timeout=10)
child.sendline("1")

This is the error:
(Should not take more than 15 seconds to boot)

Traceback (most recent call last):
  File "./test.py", line 33, in <module>
    child.expect(".*Gateway.*", timeout=40)
  File "/usr/local/lib/python3.6/site-packages/pexpect/spawnbase.py", line 344, in expect
    timeout, searchwindowsize, async_)
  File "/usr/local/lib/python3.6/site-packages/pexpect/spawnbase.py", line 372, in expect_list
    return exp.expect_loop(timeout)
  File "/usr/local/lib/python3.6/site-packages/pexpect/expect.py", line 181, in expect_loop
    return self.timeout(e)
  File "/usr/local/lib/python3.6/site-packages/pexpect/expect.py", line 144, in timeout
    raise exc
pexpect.exceptions.TIMEOUT: Timeout exceeded.
<pexpect.pty_spawn.spawn object at 0x7fefa0934a90>
command: /usr/bin/minicom
args: ['/usr/bin/minicom']
buffer (last 100 chars): b's ENTER to finish) :1\r\n\x1b[23;80H \x1b[24;1H'
before (last 100 chars): b's ENTER to finish) :1\r\n\x1b[23;80H \x1b[24;1H'
after: <class 'pexpect.exceptions.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 10862
child_fd: 5
closed: False
timeout: 30
delimiter: <class 'pexpect.exceptions.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
searcher: searcher_re:
    0: re.compile(b'.*Gateway.*')


问:
Date as variable name
I'd like to use the date as a variable name. I understand I'll need to append a character to the front and also that it's not a good way to store data (it's purely for report aesthetics). I've tried %eval() but can't solve it.

```<code>%let var_date = '_'||today();
data date;
    %eval(&var_date) = .;
run;
</code>```

I'd like the variable name to be _02JUN2011. Thanks for any help.

答:
This does what I'm looking for. Is this maintainable?</p>

```<code>data date1;
    date = put(today(),date9.);
    text = '';
    do i = 1 to 5;
        output;
    end;
run;
proc transpose data = date1 out = date2;
    by i;
    id date;
    var text;
run;
</code>```

Title: Date as variable name

Body:
I'd like to use the date as a variable name. I understand I'll need to append a character to the front and also that it's not a good way to store data (it's purely for report aesthetics). I've tried %eval() but can't solve it.

%let var_date = '_'||today();
data date;
    %eval(&var_date) = .;
run;

I'd like the variable name to be _02JUN2011. Thanks for any help.

Body:
This does what I'm looking for. Is this maintainable?

data date1;
    date = put(today(),date9.);
    text = '';
    do i = 1 to 5;
        output;
    end;
run;
proc transpose data = date1 out = date2;
    by i;
    id date;
    var text;
run;


问:
Can't start service on boot after Android 7
I want to start a service on boot.
This code only works on Android versions that came before 7.
What should I change to make it work on newer versions? Should I use JobScheduler or maybe WorkManager instead?
For what I know Timer, Handler and AlarmManager are deprecated or have different purposes.
I suspect that after Android 7 they removed the option of starting a service on boot in order to save battery life and avoid slowing down the phone. Can you confirm that?

This is my broadcast receiver

```<code>package com.kev.boot21;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BroadcastReceiverOnBootComplete extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("tag","xyz broadcast 1");
        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            Intent serviceIntent = new Intent(context, AndroidServiceStartOnBoot.class);
            context.startService(serviceIntent);
        }
    }
}
</code>```

This is my service

```<code>package com.kev.boot21;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class AndroidServiceStartOnBoot extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("tag","xyz service");
    }

}
</code>```

This is my manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kev.boot21">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <receiver
            android:name="com.kev.boot21.BroadcastReceiverOnBootComplete"
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service android:name="com.kev.boot21.AndroidServiceStartOnBoot"></service>

        <activity
            android:name="com.kev.boot21.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
I found that WorkManager is the best way to handle this problem.
I managed to run a PeriodicWorkRequest after reboot on Android 7, 8 and 9 using the example code from the official documentation:
https://developer.android.com/topic/libraries/architecture/workmanager/basics

Android 10 behaves in a different way. After reboot the PeriodicWorkRequest works only after opening the app. I guess it's for performance/security reasons

Body:
I want to start a service on boot.
This code only works on Android versions that came before 7.
What should I change to make it work on newer versions? Should I use JobScheduler or maybe WorkManager instead?
For what I know Timer, Handler and AlarmManager are deprecated or have different purposes.
I suspect that after Android 7 they removed the option of starting a service on boot in order to save battery life and avoid slowing down the phone. Can you confirm that?

This is my broadcast receiver

package com.kev.boot21;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BroadcastReceiverOnBootComplete extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("tag","xyz broadcast 1");
        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            Intent serviceIntent = new Intent(context, AndroidServiceStartOnBoot.class);
            context.startService(serviceIntent);
        }
    }
}

This is my service

package com.kev.boot21;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class AndroidServiceStartOnBoot extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("tag","xyz service");
    }

}

This is my manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.kev.boot21">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <receiver
            android:name="com.kev.boot21.BroadcastReceiverOnBootComplete"
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service android:name="com.kev.boot21.AndroidServiceStartOnBoot"></service>

        <activity
            android:name="com.kev.boot21.MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
Check if a value is between other values(properties) in an object with the object being in an array
I want to check if a value is between object values with the object being in an array.
The aim is to try to see if a start and end unix time is between other time sessions . This offers a simpler way of asking the question

EXPECTED :

The code below should return true because the values 7 and 9 aren't in any of the objects of the values.

Values like newStart = 4 to newEnd = 5should return false

Values like newStart = 5 to newEnd = 11 should return a false

```<code>let newStart = 7
let newEnd = 9

const bookedValues = [{start:4,end:6},{start:10,end:12}]

const isValidStart =
      bookedValues.some(booking => newStart < booking.start && newStart > booking.end)
const isValidEnd =
      bookedValues.some(booking =>  newEnd < booking.start && newEnd > booking.end)

console.log(isValidStart) //returns false
console.log(isValidEnd) //returns false
</code>```

答:
Your code works the way it should.
If we consider the array.some method

The some() method tests whether at least one element in the array passes the test implemented by the provided function. If one element does pass return true else false

instead, use the array.every method, if you want to consider the boolean status of both items in the array

The every() method tests whether all elements in the array pass the test implemented by the provided function. If all elements pass return true else if only some or no element passes return false

in both your some methods, neither object in the array passes the function and false is returned because no variable (number) can be greater and lesser than a range at the same time, so use OR operator instead. Since if a number is less than the beginning of a range or greater than the end of the range it isn't in the range.

let newStart = 7
let newEnd = 9
let bookedValues = [{start:4,end:6},{start:10,end:12}]

 let isValidStart =
      bookedValues.every(booking => newStart < booking.start || newStart > booking.end)
 let isValidEnd =
      bookedValues.every(booking =>  newEnd < booking.start || newEnd > booking.end)

console.log(isValidStart) //doesn't return false
console.log(isValidEnd) //doesn't return false```

Body:
I want to check if a value is between object values with the object being in an array.
The aim is to try to see if a start and end unix time is between other time sessions . This offers a simpler way of asking the question

EXPECTED :

The code below should return true because the values 7 and 9 aren't in any of the objects of the values.

Values like newStart = 4 to newEnd = 5should return false

Values like newStart = 5 to newEnd = 11 should return a false

let newStart = 7
let newEnd = 9

const bookedValues = [{start:4,end:6},{start:10,end:12}]

const isValidStart =
      bookedValues.some(booking => newStart < booking.start && newStart > booking.end)
const isValidEnd =
      bookedValues.some(booking =>  newEnd < booking.start && newEnd > booking.end)

console.log(isValidStart) //returns false
console.log(isValidEnd) //returns false


问:
Swift UITabBarController, save the order tab
Today I start practice how to use the UITabBarController. I have few tabs but notice when I see "More" (if I have 7 tabs), click edit to rearrange but notice when I close app and re-open the app, rearrange is gone. I believe it will not save the rearrange. I have UserDefaults.standard but couldn't figure how to save rearrange into my UserDefault.standard. I'm using Swift 4. Here my codes:</p>

```<code>func create_tab_controller() {
   let first_view = UIViewController()
   first_view.tabBarItem.image = UIImage(systemName: "house", withConfiguration: main_symbol_configuration)
   first_view.tabBarItem.title = "Home"
   first_view.view.backgroundColor = UIColor.black

   let second_view = UIViewController()
   second_view.tabBarItem.image = UIImage(systemName: "rectangle", withConfiguration: main_symbol_configuration)
   second_view.tabBarItem.title = "Second View"
   second_view.view.backgroundColor = UIColor.darkGray

   let third_view = UIViewController()
   third_view.tabBarItem.image = UIImage(systemName: "gear", withConfiguration: main_symbol_configuration)
   third_view.tabBarItem.title = "Setting"
   third_view.view.backgroundColor = UIColor.gray

   main_tab_controller_order = [first_view, second_view, third_view]
   main_tab_controller.viewControllers = main_tab_controller_order
   view.addSubview(main_tab_controller.view)
}
</code>```

答:
Maybe I can point you to the general direction of what you can do:

Within the viewController which controls the UITabBarController, you can use

main_tab_controller_order.delegate = self

to sign up for the delegate methods of UITabbarController.

Then you need to implement the UITabbarDelegate protocol in your view controller

The UITabbarDelegate protocol contains a method called func tabBar(UITabBar, didEndCustomizing: [UITabBarItem], changed: Bool). This method is called whenever you UITabbar is changed, i.e. also when the order of its view controllers changes.

Within this method, you can then save the order of view controllers to UserDefaults (for example as strings)

Then, on start of the application, read the value from UserDefaults and create your UITabbarController accordingly.

To elaborate on the UserDefaults part:
You could iterate over all elements in main_tab_controller.view_controllers and for each controller in there, you could store it's class name as a string in UserDefaults.  This might be the least complicated method to get you started.

Body:
Today I start practice how to use the UITabBarController. I have few tabs but notice when I see "More" (if I have 7 tabs), click edit to rearrange but notice when I close app and re-open the app, rearrange is gone. I believe it will not save the rearrange. I have UserDefaults.standard but couldn't figure how to save rearrange into my UserDefault.standard. I'm using Swift 4. Here my codes:

func create_tab_controller() {
   let first_view = UIViewController()
   first_view.tabBarItem.image = UIImage(systemName: "house", withConfiguration: main_symbol_configuration)
   first_view.tabBarItem.title = "Home"
   first_view.view.backgroundColor = UIColor.black

   let second_view = UIViewController()
   second_view.tabBarItem.image = UIImage(systemName: "rectangle", withConfiguration: main_symbol_configuration)
   second_view.tabBarItem.title = "Second View"
   second_view.view.backgroundColor = UIColor.darkGray

   let third_view = UIViewController()
   third_view.tabBarItem.image = UIImage(systemName: "gear", withConfiguration: main_symbol_configuration)
   third_view.tabBarItem.title = "Setting"
   third_view.view.backgroundColor = UIColor.gray

   main_tab_controller_order = [first_view, second_view, third_view]
   main_tab_controller.viewControllers = main_tab_controller_order
   view.addSubview(main_tab_controller.view)
}


问:
Java.How to use multiple variables and iterate over a multiple objects in for loop?
For starters, i'm new in Java

I'm trying like

```<code>for(forWriting  f : treeSet, forDrawing f2 : treeSet2)
</code>```

but it doesn't work like that

It works only when i use one variable and iterate over a single object, like that

```<code>for(forWriting  f : treeSet)
</code>```

How can i do it in Java? Thanks for your help!

答:
It's clear and more readable to don't want to do something like what you are asking.In java you must iterate over a single iterable object using for loop. If the two structures you are iterating into are of the same length you can write a single for loop and get the element from each variable in this way (in pseudo code)</p>

```<code>for(int i = 0; i< treeSet.Lenght; i++) {
   // get the i-th value from treeSet
   // get i-th valut from treeSet2

   // ... execute other statements
}
</code>```

Body:
For starters, i'm new in Java

I'm trying like

for(forWriting  f : treeSet, forDrawing f2 : treeSet2)

but it doesn't work like that

It works only when i use one variable and iterate over a single object, like that

for(forWriting  f : treeSet)

How can i do it in Java? Thanks for your help!

Body:
It's clear and more readable to don't want to do something like what you are asking.In java you must iterate over a single iterable object using for loop. If the two structures you are iterating into are of the same length you can write a single for loop and get the element from each variable in this way (in pseudo code)

for(int i = 0; i< treeSet.Lenght; i++) {
   // get the i-th value from treeSet
   // get i-th valut from treeSet2

   // ... execute other statements
}


问:
Access denied, error pushing image: failed to push to destination asia.gcr.io

I am facing this issue when I am deploy nodejs app to google cloud app engine. It was working fine before but now it is showing this error.

答:
Go to IAM & Admin in your Google cloud console.

Click on Add Role

Choose your member currently pushing the image.

Set role to App Engine Admin


问:
'Concatenate' a struct into a char array
I have a struct that's used in my internet application, which looks like:

```<code>struct query {
     ushort trans_id;
     ushort flags;
     ushort opcode;
     ushort content_length;
     char content[512];
};
</code>```

Basically, I'm just trying to take this structure and turn it into a "packet" to be sent. It must have the corresponding length and everything. So; if I could I would have like:
struct query q;

```<code>q.trans_id = 0x5544;
q.flags = 0x0000;
q.opcode = 0x0010;
q.content_length = 0x0001;
q.content[0] = '\0'; //I would want my packet to end up looking like this, when outputted to the socket:
//\x55\x44\x00\x00\x00\x10\x00\x01\x00
//and yes, it's going to be stored in a char buffer, but I'm not using any functions that will trim off any of the things past the null!
</code>```

I feel like it's a relatively simple question that can probably be answered by casting my data types, but I think it's a bit harder than that.

I also did try using sprintf, but it would turn my nulls into actual 0s, so 0x0000 would become 2 '0' ASCII characters!

答:
If you want to send it as a packet you need to be careful about endianness (htons). Make your own function that creates the "packet".

Create a large-enough buffer (a static char array should do fine)

Copy (memcpy) each element into it. Don't forget about htons

You might be tempted to just write the struct to the socket. You shouldn't do this, as there's no guarantee that the layout of the fields will be the same on the receiving machine (padding?).

Body:
I have a struct that's used in my internet application, which looks like:

struct query {
     ushort trans_id;
     ushort flags;
     ushort opcode;
     ushort content_length;
     char content[512];
};

Basically, I'm just trying to take this structure and turn it into a "packet" to be sent. It must have the corresponding length and everything. So; if I could I would have like:
struct query q;

q.trans_id = 0x5544;
q.flags = 0x0000;
q.opcode = 0x0010;
q.content_length = 0x0001;
q.content[0] = '\0'; //I would want my packet to end up looking like this, when outputted to the socket:
//\x55\x44\x00\x00\x00\x10\x00\x01\x00
//and yes, it's going to be stored in a char buffer, but I'm not using any functions that will trim off any of the things past the null!

I feel like it's a relatively simple question that can probably be answered by casting my data types, but I think it's a bit harder than that.

I also did try using sprintf, but it would turn my nulls into actual 0s, so 0x0000 would become 2 '0' ASCII characters!


问:
Batch - Cleaner way to find largest given variable?
The following code works for my problem but as you can see it is heavily protracted. So i was wondering if there was a more efficient way to find the largest of 6 given variables.

Code

```<code>
    @echo off
    Set /a picture0 = 4
    Set /a picture1 = 10
    Set /a picture2 = 9
    Set /a picture3 = 6
    Set /a picture4 = 71
    Set /a picture5 = 6
    Set /a picture6 = 5

    Call :TestPicture0
    Call :TestPicture1
    Call :TestPicture2
    Call :TestPicture3
    Call :TestPicture4
    Call :TestPicture5
    Call :TestPicture6
    @pause
    GoTo :EOF
</code>```

So I have the six variables I want to use right, and I call each of them separately because they are rather long.

```<code>
  :TestPicture0

    Set /a Test01 = %picture0% - %picture0%
    Set /a Result01 = 0
    Set /a Test02 = %picture0% - %picture2%
    Set /a Result02 = 0
    Set /a Test03 = %picture0% - %picture3%
    Set /a Result03 = 0
    Set /a Test04 = %picture0% - %picture4%
    Set /a Result04 = 0
    Set /a Test05 = %picture0% - %picture5%
    Set /a Result05 = 0
    Set /a Test06 = %picture0% - %picture6%
    Set /a Result06 = 0

    if %Test01% GEQ 0 (Set /a Result01 = 1)else (Set /a Result01 = 0)
    if %Test02% GEQ 0 (Set /a Result02 = 1)else (Set /a Result02 = 0)
    if %Test03% GEQ 0 (Set /a Result03 = 1)else (Set /a Result03 = 0)
    if %Test04% GEQ 0 (Set /a Result04 = 1)else (Set /a Result04 = 0)
    if %Test05% GEQ 0 (Set /a Result05 = 1)else (Set /a Result05 = 0)
    if %Test06% GEQ 0 (Set /a Result06 = 1)else (Set /a Result06 = 0)

    Set /a Picture0Final = %Result06% + %Result05% + %Result04% + %Result03% + %Result02% + %Result01%

    If %Picture0Final% EQU 6 (Echo Picture Zero) Else (Echo no)
    GoTo :EOF

    :TestPicture1
    Set /a Test10 = %picture1% - %picture0%
    Set /a Result10 = 0
    Set /a Test12 = %picture1% - %picture2%
    Set /a Result12 = 0
    Set /a Test13 = %picture1% - %picture3%
    Set /a Result13 = 0
    Set /a Test14 = %picture1% - %picture4%
    Set /a Result14 = 0
    Set /a Test15 = %picture1% - %picture5%
    Set /a Result15 = 0
    Set /a Test16 = %picture1% - %picture6%
    Set /a Result16 = 0

    if %Test10% GEQ 0 (Set /a Result10 = 1)else (Set /a Result10 = 0)
    if %Test12% GEQ 0 (Set /a Result12 = 1)else (Set /a Result12 = 0)
    if %Test13% GEQ 0 (Set /a Result13 = 1)else (Set /a Result13 = 0)
    if %Test14% GEQ 0 (Set /a Result14 = 1)else (Set /a Result14 = 0)
    if %Test15% GEQ 0 (Set /a Result15 = 1)else (Set /a Result15 = 0)
    if %Test16% GEQ 0 (Set /a Result16 = 1)else (Set /a Result16 = 0)

    Set /a Picture1Final = %Result16% + %Result15% + %Result14% + %Result13% + %Result12% + %Result10%

    If %Picture1Final% EQU 6 (Echo Picture one) Else (Echo no)
    GoTo :EOF

    :TestPicture2
    Set /a Test20 = %picture2% - %picture0%
    Set /a Result20 = 0
    Set /a Test21 = %picture2% - %picture1%
    Set /a Result21 = 0
    Set /a Test23 = %picture2% - %picture3%
    Set /a Result23 = 0
    Set /a Test24 = %picture2% - %picture4%
    Set /a Result24 = 0
    Set /a Test25 = %picture2% - %picture5%
    Set /a Result25 = 0
    Set /a Test26 = %picture2% - %picture6%
    Set /a Result26 = 0

    if %Test20% GEQ 0 (Set /a Result20 = 1)else (Set /a Result20 = 0)
    if %Test21% GEQ 0 (Set /a Result21 = 1)else (Set /a Result21 = 0)
    if %Test23% GEQ 0 (Set /a Result23 = 1)else (Set /a Result23 = 0)
    if %Test24% GEQ 0 (Set /a Result24 = 1)else (Set /a Result24 = 0)
    if %Test25% GEQ 0 (Set /a Result25 = 1)else (Set /a Result25 = 0)
    if %Test26% GEQ 0 (Set /a Result26 = 1)else (Set /a Result26 = 0)

    Set /a Picture2Final = %Result26% + %Result25% + %Result24% + %Result23% + %Result21% + %Result20%

    If %Picture2Final% EQU 6 (Echo Picture Two) Else (Echo no)
    GoTo :EOF

    :TestPicture3
    Set /a Test30 = %picture3% - %picture0%
    Set /a Result30 = 0
    Set /a Test31 = %picture3% - %picture1%
    Set /a Result11 = 0
    Set /a Test32 = %picture3% - %picture2%
    Set /a Result32 = 0
    Set /a Test34 = %picture3% - %picture4%
    Set /a Result34 = 0
    Set /a Test35 = %picture3% - %picture5%
    Set /a Result35 = 0
    Set /a Test36 = %picture3% - %picture6%
    Set /a Result36 = 0

    if %Test30% GEQ 0 (Set /a Result30 = 1)else (Set /a Result30 = 0)
    if %Test31% GEQ 0 (Set /a Result31 = 1)else (Set /a Result31 = 0)
    if %Test32% GEQ 0 (Set /a Result32 = 1)else (Set /a Result32 = 0)
    if %Test34% GEQ 0 (Set /a Result34 = 1)else (Set /a Result34 = 0)
    if %Test35% GEQ 0 (Set /a Result35 = 1)else (Set /a Result35 = 0)
    if %Test36% GEQ 0 (Set /a Result36 = 1)else (Set /a Result36 = 0)

    Set /a Picture3Final = %Result36% + %Result35% + %Result34% + %Result32% + %Result31% + %Result30%

    If %Picture3Final% EQU 6 (Echo Picture Three) Else (Echo no)
    GoTo :EOF

    :TestPicture4

    Set /a Test40 = %picture4% - %picture0%
    Set /a Result40 = 0
    Set /a Test42 = %picture4% - %picture2%
    Set /a Result42 = 0
    Set /a Test43 = %picture4% - %picture3%
    Set /a Result43 = 0
    Set /a Test41 = %picture4% - %picture1%
    Set /a Result41 = 0
    Set /a Test45 = %picture4% - %picture5%
    Set /a Result45 = 0
    Set /a Test46 = %picture4% - %picture6%
    Set /a Result46 = 0

    if %Test40% GEQ 0 (Set /a Result40 = 1)else (Set /a Result40 = 0)
    if %Test42% GEQ 0 (Set /a Result42 = 1)else (Set /a Result42 = 0)
    if %Test43% GEQ 0 (Set /a Result43 = 1)else (Set /a Result43 = 0)
    if %Test41% GEQ 0 (Set /a Result41 = 1)else (Set /a Result41 = 0)
    if %Test45% GEQ 0 (Set /a Result45 = 1)else (Set /a Result45 = 0)
    if %Test46% GEQ 0 (Set /a Result46 = 1)else (Set /a Result46 = 0)

    Set /a Picture4Final = %Result46% + %Result45% + %Result41% + %Result43% + %Result42% + %Result40%

    If %Picture4Final% GEQ 6 (Echo Picture Four) Else (Echo no)

    GoTo :EOF

    :TestPicture5
    Set /a Test50 = %picture5% - %picture0%
    Set /a Result50 = 0
    Set /a Test51 = %picture5% - %picture1%
    Set /a Result51 = 0
    Set /a Test52 = %picture5% - %picture2%
    Set /a Result52 = 0
    Set /a Test53 = %picture5% - %picture3%
    Set /a Result53 = 0
    Set /a Test54 = %picture5% - %picture5%
    Set /a Result54 = 0
    Set /a Test56 = %picture5% - %picture6%
    Set /a Result56 = 0

    if %Test50% GEQ 0 (Set /a Result50 = 1)else (Set /a Result50 = 0)
    if %Test51% GEQ 0 (Set /a Result51 = 1)else (Set /a Result51 = 0)
    if %Test52% GEQ 0 (Set /a Result52 = 1)else (Set /a Result52 = 0)
    if %Test53% GEQ 0 (Set /a Result53 = 1)else (Set /a Result53 = 0)
    if %Test54% GEQ 0 (Set /a Result54 = 1)else (Set /a Result54 = 0)
    if %Test56% GEQ 0 (Set /a Result56 = 1)else (Set /a Result56 = 0)

    Set /a Picture5Final = %Result56% + %Result54% + %Result53% + %Result52% + %Result51% + %Result50%

    If %Picture5Final% EQU 6 (Echo Picture Five) Else (Echo no)
    GoTo :EOF

    :TestPicture6
    Set /a Test60 = %picture6% - %picture0%
    Set /a Result60 = 0
    Set /a Test61 = %picture6% - %picture1%
    Set /a Result61 = 0
    Set /a Test62 = %picture6% - %picture2%
    Set /a Result62 = 0
    Set /a Test63 = %picture6% - %picture3%
    Set /a Result63 = 0
    Set /a Test64 = %picture6% - %picture6%
    Set /a Result64 = 0
    Set /a Test65 = %picture6% - %picture6%
    Set /a Result65 = 0

    if %Test60% GEQ 0 (Set /a Result60 = 1)else (Set /a Result60 = 0)
    if %Test61% GEQ 0 (Set /a Result61 = 1)else (Set /a Result61 = 0)
    if %Test62% GEQ 0 (Set /a Result62 = 1)else (Set /a Result62 = 0)
    if %Test63% GEQ 0 (Set /a Result63 = 1)else (Set /a Result63 = 0)
    if %Test64% GEQ 0 (Set /a Result64 = 1)else (Set /a Result64 = 0)
    if %Test65% GEQ 0 (Set /a Result65 = 1)else (Set /a Result65 = 0)

    Set /a Picture6Final = %Result65% + %Result64% + %Result63% + %Result62% + %Result61% + %Result60%

    If %Picture6Final% EQU 6 (Echo Picture Six) Else (Echo no)
    GoTo :EOF

</code>```

If yall know a way to make this better please let me know :D----<-<
*Edit: fixed some 0's to ones ... literally

答:
An alternative to @HackingAddict1337's answer:

A For /F loop using the Set command in conjunction with the Array variable prefix can be used to retrieve the highest value withought needing to know / reference the size of the Array:

Setlocal ENABLEdelayedexpansion
For /F "Tokens=1,2 Delims==" %%A in ('Set picture') Do If "!Max!" == "" (Set "Max=%%B" & Set "MaxV=%%A") Else If %%B GTR !Max! (Set "Max=%%B" & Set "MaxV=%%A")
```

Body:
The following code works for my problem but as you can see it is heavily protracted. So i was wondering if there was a more efficient way to find the largest of 6 given variables.

Code

    @echo off
    Set /a picture0 = 4
    Set /a picture1 = 10
    Set /a picture2 = 9
    Set /a picture3 = 6
    Set /a picture4 = 71
    Set /a picture5 = 6
    Set /a picture6 = 5

    Call :TestPicture0
    Call :TestPicture1
    Call :TestPicture2
    Call :TestPicture3
    Call :TestPicture4
    Call :TestPicture5
    Call :TestPicture6
    @pause
    GoTo :EOF

So I have the six variables I want to use right, and I call each of them separately because they are rather long.

  :TestPicture0

    Set /a Test01 = %picture0% - %picture0%
    Set /a Result01 = 0
    Set /a Test02 = %picture0% - %picture2%
    Set /a Result02 = 0
    Set /a Test03 = %picture0% - %picture3%
    Set /a Result03 = 0
    Set /a Test04 = %picture0% - %picture4%
    Set /a Result04 = 0
    Set /a Test05 = %picture0% - %picture5%
    Set /a Result05 = 0
    Set /a Test06 = %picture0% - %picture6%
    Set /a Result06 = 0

    if %Test01% GEQ 0 (Set /a Result01 = 1)else (Set /a Result01 = 0)
    if %Test02% GEQ 0 (Set /a Result02 = 1)else (Set /a Result02 = 0)
    if %Test03% GEQ 0 (Set /a Result03 = 1)else (Set /a Result03 = 0)
    if %Test04% GEQ 0 (Set /a Result04 = 1)else (Set /a Result04 = 0)
    if %Test05% GEQ 0 (Set /a Result05 = 1)else (Set /a Result05 = 0)
    if %Test06% GEQ 0 (Set /a Result06 = 1)else (Set /a Result06 = 0)

    Set /a Picture0Final = %Result06% + %Result05% + %Result04% + %Result03% + %Result02% + %Result01%

    If %Picture0Final% EQU 6 (Echo Picture Zero) Else (Echo no)
    GoTo :EOF

    :TestPicture1
    Set /a Test10 = %picture1% - %picture0%
    Set /a Result10 = 0
    Set /a Test12 = %picture1% - %picture2%
    Set /a Result12 = 0
    Set /a Test13 = %picture1% - %picture3%
    Set /a Result13 = 0
    Set /a Test14 = %picture1% - %picture4%
    Set /a Result14 = 0
    Set /a Test15 = %picture1% - %picture5%
    Set /a Result15 = 0
    Set /a Test16 = %picture1% - %picture6%
    Set /a Result16 = 0

    if %Test10% GEQ 0 (Set /a Result10 = 1)else (Set /a Result10 = 0)
    if %Test12% GEQ 0 (Set /a Result12 = 1)else (Set /a Result12 = 0)
    if %Test13% GEQ 0 (Set /a Result13 = 1)else (Set /a Result13 = 0)
    if %Test14% GEQ 0 (Set /a Result14 = 1)else (Set /a Result14 = 0)
    if %Test15% GEQ 0 (Set /a Result15 = 1)else (Set /a Result15 = 0)
    if %Test16% GEQ 0 (Set /a Result16 = 1)else (Set /a Result16 = 0)

    Set /a Picture1Final = %Result16% + %Result15% + %Result14% + %Result13% + %Result12% + %Result10%

    If %Picture1Final% EQU 6 (Echo Picture one) Else (Echo no)
    GoTo :EOF

    :TestPicture2
    Set /a Test20 = %picture2% - %picture0%
    Set /a Result20 = 0
    Set /a Test21 = %picture2% - %picture1%
    Set /a Result21 = 0
    Set /a Test23 = %picture2% - %picture3%
    Set /a Result23 = 0
    Set /a Test24 = %picture2% - %picture4%
    Set /a Result24 = 0
    Set /a Test25 = %picture2% - %picture5%
    Set /a Result25 = 0
    Set /a Test26 = %picture2% - %picture6%
    Set /a Result26 = 0

    if %Test20% GEQ 0 (Set /a Result20 = 1)else (Set /a Result20 = 0)
    if %Test21% GEQ 0 (Set /a Result21 = 1)else (Set /a Result21 = 0)
    if %Test23% GEQ 0 (Set /a Result23 = 1)else (Set /a Result23 = 0)
    if %Test24% GEQ 0 (Set /a Result24 = 1)else (Set /a Result24 = 0)
    if %Test25% GEQ 0 (Set /a Result25 = 1)else (Set /a Result25 = 0)
    if %Test26% GEQ 0 (Set /a Result26 = 1)else (Set /a Result26 = 0)

    Set /a Picture2Final = %Result26% + %Result25% + %Result24% + %Result23% + %Result21% + %Result20%

    If %Picture2Final% EQU 6 (Echo Picture Two) Else (Echo no)
    GoTo :EOF

    :TestPicture3
    Set /a Test30 = %picture3% - %picture0%
    Set /a Result30 = 0
    Set /a Test31 = %picture3% - %picture1%
    Set /a Result11 = 0
    Set /a Test32 = %picture3% - %picture2%
    Set /a Result32 = 0
    Set /a Test34 = %picture3% - %picture4%
    Set /a Result34 = 0
    Set /a Test35 = %picture3% - %picture5%
    Set /a Result35 = 0
    Set /a Test36 = %picture3% - %picture6%
    Set /a Result36 = 0

    if %Test30% GEQ 0 (Set /a Result30 = 1)else (Set /a Result30 = 0)
    if %Test31% GEQ 0 (Set /a Result31 = 1)else (Set /a Result31 = 0)
    if %Test32% GEQ 0 (Set /a Result32 = 1)else (Set /a Result32 = 0)
    if %Test34% GEQ 0 (Set /a Result34 = 1)else (Set /a Result34 = 0)
    if %Test35% GEQ 0 (Set /a Result35 = 1)else (Set /a Result35 = 0)
    if %Test36% GEQ 0 (Set /a Result36 = 1)else (Set /a Result36 = 0)

    Set /a Picture3Final = %Result36% + %Result35% + %Result34% + %Result32% + %Result31% + %Result30%

    If %Picture3Final% EQU 6 (Echo Picture Three) Else (Echo no)
    GoTo :EOF

    :TestPicture4

    Set /a Test40 = %picture4% - %picture0%
    Set /a Result40 = 0
    Set /a Test42 = %picture4% - %picture2%
    Set /a Result42 = 0
    Set /a Test43 = %picture4% - %picture3%
    Set /a Result43 = 0
    Set /a Test41 = %picture4% - %picture1%
    Set /a Result41 = 0
    Set /a Test45 = %picture4% - %picture5%
    Set /a Result45 = 0
    Set /a Test46 = %picture4% - %picture6%
    Set /a Result46 = 0

    if %Test40% GEQ 0 (Set /a Result40 = 1)else (Set /a Result40 = 0)
    if %Test42% GEQ 0 (Set /a Result42 = 1)else (Set /a Result42 = 0)
    if %Test43% GEQ 0 (Set /a Result43 = 1)else (Set /a Result43 = 0)
    if %Test41% GEQ 0 (Set /a Result41 = 1)else (Set /a Result41 = 0)
    if %Test45% GEQ 0 (Set /a Result45 = 1)else (Set /a Result45 = 0)
    if %Test46% GEQ 0 (Set /a Result46 = 1)else (Set /a Result46 = 0)

    Set /a Picture4Final = %Result46% + %Result45% + %Result41% + %Result43% + %Result42% + %Result40%

    If %Picture4Final% GEQ 6 (Echo Picture Four) Else (Echo no)

    GoTo :EOF

    :TestPicture5
    Set /a Test50 = %picture5% - %picture0%
    Set /a Result50 = 0
    Set /a Test51 = %picture5% - %picture1%
    Set /a Result51 = 0
    Set /a Test52 = %picture5% - %picture2%
    Set /a Result52 = 0
    Set /a Test53 = %picture5% - %picture3%
    Set /a Result53 = 0
    Set /a Test54 = %picture5% - %picture5%
    Set /a Result54 = 0
    Set /a Test56 = %picture5% - %picture6%
    Set /a Result56 = 0

    if %Test50% GEQ 0 (Set /a Result50 = 1)else (Set /a Result50 = 0)
    if %Test51% GEQ 0 (Set /a Result51 = 1)else (Set /a Result51 = 0)
    if %Test52% GEQ 0 (Set /a Result52 = 1)else (Set /a Result52 = 0)
    if %Test53% GEQ 0 (Set /a Result53 = 1)else (Set /a Result53 = 0)
    if %Test54% GEQ 0 (Set /a Result54 = 1)else (Set /a Result54 = 0)
    if %Test56% GEQ 0 (Set /a Result56 = 1)else (Set /a Result56 = 0)

    Set /a Picture5Final = %Result56% + %Result54% + %Result53% + %Result52% + %Result51% + %Result50%

    If %Picture5Final% EQU 6 (Echo Picture Five) Else (Echo no)
    GoTo :EOF

    :TestPicture6
    Set /a Test60 = %picture6% - %picture0%
    Set /a Result60 = 0
    Set /a Test61 = %picture6% - %picture1%
    Set /a Result61 = 0
    Set /a Test62 = %picture6% - %picture2%
    Set /a Result62 = 0
    Set /a Test63 = %picture6% - %picture3%
    Set /a Result63 = 0
    Set /a Test64 = %picture6% - %picture6%
    Set /a Result64 = 0
    Set /a Test65 = %picture6% - %picture6%
    Set /a Result65 = 0

    if %Test60% GEQ 0 (Set /a Result60 = 1)else (Set /a Result60 = 0)
    if %Test61% GEQ 0 (Set /a Result61 = 1)else (Set /a Result61 = 0)
    if %Test62% GEQ 0 (Set /a Result62 = 1)else (Set /a Result62 = 0)
    if %Test63% GEQ 0 (Set /a Result63 = 1)else (Set /a Result63 = 0)
    if %Test64% GEQ 0 (Set /a Result64 = 1)else (Set /a Result64 = 0)
    if %Test65% GEQ 0 (Set /a Result65 = 1)else (Set /a Result65 = 0)

    Set /a Picture6Final = %Result65% + %Result64% + %Result63% + %Result62% + %Result61% + %Result60%

    If %Picture6Final% EQU 6 (Echo Picture Six) Else (Echo no)
    GoTo :EOF

If yall know a way to make this better please let me know :D----<-<
*Edit: fixed some 0's to ones ... literally


问:
Python: Make dictionary with folder names as key and file names as values
I want to make a dictionary with folder names as key and file names as values
for different files in different folders. Below is my code to achieve that, but I am not getting the expected output.

I have a directory within that different folders are present. The directory name is sreekanth, within are many folders like A, A1, A2, A3, which contain .csv files.

I am trying to collect all the .csv files from the different folders and assigning them to the corresponding folder in a Python dictionary.

from os.path import os
import fnmatch

d={}

l = []
file_list = []
file_list1 = []

for path,dirs,files in os.walk('/Users/amabbu/Desktop/sreekanth'):
    for f in fnmatch.filter(files,'*.csv'):
        if os.path.basename(path) in d.keys():
            file_list.append(f)
            d = {os.path.basename(path):list(file_list)}

            print("First",d)
        else:
            d.setdefault(os.path.basename(path),f)
        print("Second",d)
```

答:
The following is a simpler way to do what you want using defaultdict module:

```<code>import os
import fnmatch
from collections import defaultdict

d=defaultdict(set)
for path,dirs,files in os.walk('/Users/amabbu/Desktop/sreekanth'):
   for f in fnmatch.filter(files,'*.csv'):
      d[os.path.basename(path)].add(f)

print(dict(d))
</code>```

Body:
The following is a simpler way to do what you want using defaultdict module:

import os
import fnmatch
from collections import defaultdict

d=defaultdict(set)
for path,dirs,files in os.walk('/Users/amabbu/Desktop/sreekanth'):
   for f in fnmatch.filter(files,'*.csv'):
      d[os.path.basename(path)].add(f)

print(dict(d))