问:
Minimum bounding rectangle of polygon
Let's say we have a class/struct Point

```<code>class Point
{
 int x;
int y;
}
</code>```

and a class Polygon that contains list of Points

```<code>class Polygon
{
  List<Point> points;

  Path(List<Point> points)
  {
  //some implementation
  }
}
</code>```

I am interested in finding the Minimal bounding rectangle points of the Polygon(https://en.wikipedia.org/wiki/Minimum_bounding_rectangle).  The found minimal bounding rectangle sides might not be parallel to both axis , so I am trying to find an algorithm written in Java,C#,C++ .Can anyone propose or link such a solution, thanks!

答:
It is possible to construct minimal bounding box (both min-area and min-perimeter) using Rotating Calipers approach.

You can find description at this wayback archive page

The minimum area rectangle enclosing a convex polygon P has a side
  collinear with an edge of the polygon.

The above result dramatically restricts the range of possible
  rectangles. Not only is it not necessary to check all directions, but
  only as many as the polygon's number of edges.

Illustrating the above result: the four lines of support (red), with
  one coinciding with an edge, determine the enclosing rectangle (blue).

A simple algorithm would be to compute for each edge the corresponding
  rectangle collinear with it. But the construction of this rectangle
  would imply computing the polygon's extreme points for each edge, a
  process that takes O(n) time (for n edges). The entire algorithm would
  then have quadratic time complexity.

A much more efficient algorithm can be found. Instead of recomputing
  the extreme points, it is possible to update them in constant time,
  using the Rotating Calipers. Indeed, consider a convex polygon, with a
  two pair of lines of support through all four usual extreme points in
  the x and y directions. The four lines already determine an enclosing
  rectangle for the polygon. But unless the polygon has a horizontal or
  vertical edge, this rectangle is not a candidate for the minimum area.
  However, the lines can be rotated until the above condition is
  satisfied. This procedure is at the heart of the following algorithm.
  The input is assumed to be a convex polygon with n vertices given in
  clockwise order.

Compute all four extreme points for the polygon, and call them xminP,
  xmaxP, yminP ymaxP.

Construct four lines of support for P through all four points. These
  determine two sets of "calipers".

If one (or more) lines coincide with an edge, then compute the area of
  the rectangle determined by the four lines, and keep as minimum.
  Otherwise, consider the current minimum area to be infinite.

Rotate the lines clockwise until one of them coincides with an edge of
  its polygon.

Compute the area of the new rectangle, and compare it to the current
  minimum area. Update the minimum if necessary, keeping track of the
  rectangle determining the minimum.

Repeat steps 4 and 5, until the lines have been rotated an angle
  greater than 90 degrees. Output the minimum area enclosing rectangle.
  Because two pairs of "calipers" determine an enclosing rectangle, this
  algorithm considers all possible rectangles that could have the
  minimum area. Furthermore, aside from the initialization, there are
  only as many steps in the algorithm's main loop as there are vertices.
  Thus the algorithm has linear time complexity.

Title: Minimum bounding rectangle of polygon

Body:
Let's say we have a class/struct Point

class Point
{
 int x;
int y;
}

and a class Polygon that contains list of Points

class Polygon
{
  List<Point> points;

  Path(List<Point> points)
  {
  //some implementation
  }
}

I am interested in finding the Minimal bounding rectangle points of the Polygon(https://en.wikipedia.org/wiki/Minimum_bounding_rectangle).  The found minimal bounding rectangle sides might not be parallel to both axis , so I am trying to find an algorithm written in Java,C#,C++ .Can anyone propose or link such a solution, thanks!


来源: stackexchange

问:
Implementation of ceil() and floor()
Just curious how are these implemented. I can't see where I would start. Do they work directly on the float's/double's bits?

Also where can I find the source code of functions from math.h? All I find are either headers with prototypes or files with functions that call other functions from somewhere else.

EDIT: Part of the message was lost after editing the title. What I meant in particular were the ceil() and floor() functions.

答:
Math functions like addition and division are almost always implemented by machine instructions.  The exceptions are mostly small processors, like the 8048 family, which use a library to implement the functions for which there are not a simple machine instruction sequence to compute.

Math functions like sin(), sqrt(), log(), etc. are almost always implemented in the runtime library.  A few rare CPUs, like the Cray, have a square root instruction.

Tell us which particular implementation (gcc, MSVC, etc./Mac, Linux, etc.) you are using and someone will direct you precisely where to look.

ContentLicense: CC BY-SA 3.0

Title: Implementation of ceil() and floor()


问:
Retrofit okhttp doesn't send any request
At my logcat I have such lines during server call:

```<code>Rejecting re-init on previously-failed class java.lang.Class<okhttp3.internal.platform.ConscryptPlatform$platformTrustManager$2>: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/conscrypt/ConscryptHostnameVerifier;

Caused by: java.lang.ClassNotFoundException: Didn't find class "org.conscrypt.ConscryptHostnameVerifier" on path: DexPathList[[zip file "/data/app/package-JHk9QBF7PSIufoXeKqbmNA==/base.apk"],nativeLibraryDirectories=[/data/app/package-JHk9QBF7PSIufoXeKqbmNA==/lib/x86, /system/lib, /system/vendor/lib]]
</code>```

After some time I can see such message:

```<code>okhttp.OkHttpClient: <-- HTTP FAILED: java.net.SocketTimeoutException: timeout
</code>```

And I checked that internet works well on my device. App doesn't crashes but I can't send any request. For example everything was working well during all this week, and right now smth damaged :( How to fix this error?

UPDATE

My gradle app file:

```<code>buildscript {
    ext.kotlin_version = '1.3.71'
    repositories { jcenter() }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlinx-serialization'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "package"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 87
        versionName "1.0.0"
        testInstrumentationRunner "android.support.APICallRequests.runner.AndroidJUnitRunner"
    }
    buildTypes {
        debug {
            buildConfigField "String", "API_URL", 'url'
        }
        release {
            buildConfigField "String", "API_URL", 'url'
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }

    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation files('libs/mail.jar')
    implementation 'com.jakewharton.timber:timber:4.7.1'
    implementation 'org.apache.commons:commons-io:1.3.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    testImplementation 'junit:junit:4.13'

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'

    // Retrofit
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'
    implementation 'org.jsoup:jsoup:1.13.1'

    implementation 'us.belka:androidtoggleswitch:1.2.2'
    implementation 'com.github.droidbond:LoadingButton:0.1.5'

    implementation 'io.github.tonnyl:whatsnew:0.1.1'
    implementation 'com.github.GrenderG:Toasty:1.3.1'
    implementation 'com.lsjwzh:materialloadingprogressbar:0.5.8-RELEASE'

    implementation 'com.daimajia.swipelayout:library:1.2.0@aar'

    implementation 'androidx.browser:browser:1.2.0'

    implementation 'com.google.firebase:firebase-analytics:17.4.2'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
    implementation 'com.google.firebase:firebase-messaging:20.2.0'
    implementation 'com.google.firebase:firebase-core:17.4.2'

    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0" // JVM dependency
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.72'

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
}
</code>```

答:
OkHttp attempts to detect with TLS implementation you want, and Conscrypt is one option, though it isn't the default. It looks like OkHttp is crashing because it thinks you want Conscrypt but don't have it available.

Add this line to your dependencies:

```<code>implementation 'com.squareup.okhttp3:okhttp:4.7.2'
</code>```

Then you might get a more useful stacktrace. You really want to post the stacktrace that has the Platform class in it. It should be the first one that prints.

ContentLicense: CC BY-SA 4.0

Body:
At my logcat I have such lines during server call:

Rejecting re-init on previously-failed class java.lang.Class<okhttp3.internal.platform.ConscryptPlatform$platformTrustManager$2>: java.lang.NoClassDefFoundError: Failed resolution of: Lorg/conscrypt/ConscryptHostnameVerifier;

Caused by: java.lang.ClassNotFoundException: Didn't find class "org.conscrypt.ConscryptHostnameVerifier" on path: DexPathList[[zip file "/data/app/package-JHk9QBF7PSIufoXeKqbmNA==/base.apk"],nativeLibraryDirectories=[/data/app/package-JHk9QBF7PSIufoXeKqbmNA==/lib/x86, /system/lib, /system/vendor/lib]]

After some time I can see such message:

okhttp.OkHttpClient: <-- HTTP FAILED: java.net.SocketTimeoutException: timeout

And I checked that internet works well on my device. App doesn't crashes but I can't send any request. For example everything was working well during all this week, and right now smth damaged :( How to fix this error?

UPDATE

My gradle app file:

buildscript {
    ext.kotlin_version = '1.3.71'
    repositories { jcenter() }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72"
        classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    }
}

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlinx-serialization'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "package"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 87
        versionName "1.0.0"
        testInstrumentationRunner "android.support.APICallRequests.runner.AndroidJUnitRunner"
    }
    buildTypes {
        debug {
            buildConfigField "String", "API_URL", 'url'
        }
        release {
            buildConfigField "String", "API_URL", 'url'
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }

    lintOptions {
        checkReleaseBuilds false
        // Or, if you prefer, you can continue to check for errors in release builds,
        // but continue the build even when errors are found:
        abortOnError false
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation files('libs/mail.jar')
    implementation 'com.jakewharton.timber:timber:4.7.1'
    implementation 'org.apache.commons:commons-io:1.3.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    testImplementation 'junit:junit:4.13'

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'

    // Retrofit
    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'
    implementation 'org.jsoup:jsoup:1.13.1'

    implementation 'us.belka:androidtoggleswitch:1.2.2'
    implementation 'com.github.droidbond:LoadingButton:0.1.5'

    implementation 'io.github.tonnyl:whatsnew:0.1.1'
    implementation 'com.github.GrenderG:Toasty:1.3.1'
    implementation 'com.lsjwzh:materialloadingprogressbar:0.5.8-RELEASE'

    implementation 'com.daimajia.swipelayout:library:1.2.0@aar'

    implementation 'androidx.browser:browser:1.2.0'

    implementation 'com.google.firebase:firebase-analytics:17.4.2'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
    implementation 'com.google.firebase:firebase-messaging:20.2.0'
    implementation 'com.google.firebase:firebase-core:17.4.2'

    implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0" // JVM dependency
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.72'

    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"

    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
}

Body:
OkHttp attempts to detect with TLS implementation you want, and Conscrypt is one option, though it isn't the default. It looks like OkHttp is crashing because it thinks you want Conscrypt but don't have it available.

Add this line to your dependencies:

implementation 'com.squareup.okhttp3:okhttp:4.7.2'

Then you might get a more useful stacktrace. You really want to post the stacktrace that has the Platform class in it. It should be the first one that prints.


问:
Efficiently getting most and least significant bit in javascript
In a 64 bit integer. I am trying to get the index of the leftmost non zero bit. I used the naive method of iterating over all the 64 bits to calculate this.

```<code>function getLowestBitPosition(bitstring) {
    for (a = 0; a < bitstring.length; a++) if (bitstring[a] === "1") return a;
}
</code>```

Similarly, I iterated backwards to get the index of the rightmost non zero bit.

```<code>function getHighestBitPosition(bitstring) {
    for (a = bitstring.length - 1; a >= 0; a--) if (bitstring[a] === "1") return a;
}
</code>```

I'm pretty sure that there is a more efficient way to implement this. I have seen methods in C requiring little iteration. However, all those examples are using C library functions. Is there a better way to get the index in javascript?

答:
Since you don't seem to have access to the raw binary form of those integers, but instead have to work on their bitstring representation, you will be limited to using string functions.

Most likely the built-in functions indexOf() and lastIndexOf() will be faster than a for-loop.

Other than that I don't think there is a faster way to find the first set bit in a string of ones and zeros.

Body:
In a 64 bit integer. I am trying to get the index of the leftmost non zero bit. I used the naive method of iterating over all the 64 bits to calculate this.

function getLowestBitPosition(bitstring) {
    for (a = 0; a < bitstring.length; a++) if (bitstring[a] === "1") return a;
}

Similarly, I iterated backwards to get the index of the rightmost non zero bit.

function getHighestBitPosition(bitstring) {
    for (a = bitstring.length - 1; a >= 0; a--) if (bitstring[a] === "1") return a;
}

I'm pretty sure that there is a more efficient way to implement this. I have seen methods in C requiring little iteration. However, all those examples are using C library functions. Is there a better way to get the index in javascript?


问:
Mock IOptionsMonitor
How can I make an class instance manually of a class that requires an IOptionsMonitor in the constructor?

My Class

```<code>private readonly AuthenticationSettings _authenticationSettings;

public ActiveDirectoryLogic(IOptionsMonitor<AuthenticationSettings> authenticationSettings)
{
   _authenticationSettings = authenticationSettings.CurrentValue;
}
</code>```

My test

```<code>AuthenticationSettings au = new AuthenticationSettings(){ ... };
var someOptions = Options.Create(new AuthenticationSettings());
var optionMan = new OptionsMonitor(someOptions);  // dont work.
ActiveDirectoryLogic _SUT = new ActiveDirectoryLogic(au);
</code>```

I tried to make an IOptionsMonitor object manually but can't figure out how.

答:
Achieving the same in NSubstitute:</p>

```<code>        var optionsMonitorMock = Substitute.For<IOptionsMonitor<AuthenticationSettings>>();
        optionsMonitorMock.CurrentValue.Returns(new AuthenticationSettings
        {
            // values go here
        });
</code>```

Title: Mock IOptionsMonitor

Body:
How can I make an class instance manually of a class that requires an IOptionsMonitor in the constructor?

My Class

private readonly AuthenticationSettings _authenticationSettings;

public ActiveDirectoryLogic(IOptionsMonitor<AuthenticationSettings> authenticationSettings)
{
   _authenticationSettings = authenticationSettings.CurrentValue;
}

My test

AuthenticationSettings au = new AuthenticationSettings(){ ... };
var someOptions = Options.Create(new AuthenticationSettings());
var optionMan = new OptionsMonitor(someOptions);  // dont work.
ActiveDirectoryLogic _SUT = new ActiveDirectoryLogic(au);

I tried to make an IOptionsMonitor object manually but can't figure out how.

Body:
Achieving the same in NSubstitute:

        var optionsMonitorMock = Substitute.For<IOptionsMonitor<AuthenticationSettings>>();
        optionsMonitorMock.CurrentValue.Returns(new AuthenticationSettings
        {
            // values go here
        });


问:
Named Arguments do not work in a string with conditional logic
I have a multiline string with an in-line if condition as follows:

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        Good bye. """
</code>```

However, when I insert a named parameter, it does not seem to properly treat it. With some testing I found out that removing the IF from the string would allow the named parameters to work

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}
</code>```

Is there a specific reason why this won't work?

答:
Do you mean:

my_string=  """
        Hello my name is """ + ['John' if client == "j123" else 'Mary'][0] + """

        Good bye. """
```

Body:
I have a multiline string with an in-line if condition as follows:

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        Good bye. """

However, when I insert a named parameter, it does not seem to properly treat it. With some testing I found out that removing the IF from the string would allow the named parameters to work

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}

Is there a specific reason why this won't work?


问:
Does Postgres have something similar to Oracle's Virtual Private Databases?
As the title suggests, does anyone know if such a thing exists?</p>

答: You could do something like it with views/rules of the data.  Also, 8.4 has column level permissions iirc.</p>

OwnerDisplayName: zodeus

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler


问:
Why iis return 403 error code with asp net mvc controller file stream
I have a controller whit two methods

```<code>public ActionResult Index1(string c, string d)
    {
        string path = "some path";

        if (System.IO.File.Exists(path))
        {
            var bytes = System.IO.File.ReadAllBytes(path);
            return base.File(bytes, MimeMapping.GetMimeMapping(path));
        }

        path = "/assets/images/no.jpg";
        return File(path, "application/jpeg", "no.jpg");
    }
public ActionResult Index2(string c, string d)
    {
        string path = "some path";
        string _nomefile = "some name";
        string _mime = "";
        if (System.IO.File.Exists(path))
        {
            return new FileStreamResult(new FileStream(path, FileMode.Open), _mime) { FileDownloadName = _nomefile};

        }
        path = "/assets/images/no.jpg";
        return File(path, "application/jpeg", "no.jpg");
    }
</code>```

This are used by view like this

```<code>@foreach (var item in Model.OrderBy(x => x.Titolo))
        {
            <div class="col-md-3 col-sm-12  immagini margin-bottom-20">
                <a class="image-hover" href="/Index1?c=@item.Immagine&d=N" data-toggle="tooltip" title="@item.Titolo - @item.Descrizione">
                    <img src="/Index1?c=@item.Immagine&d=M" alt="@item.Titolo"><br />
                    <span>@item.Descrizione</span>
                </a>
            </div>
        }
</code>```

The problem is that IIS return an intermittent 403 forbidden with both methods  and this is totally random. On a list with 30 images 3 or 4 are not displayed.
I do not have any authentication implemented and all files are on the same machine.

答:
Ok, this was my solution.

It was necessary to set lower limits in IIS 8.5

https://serverfault.com/a/908740

Body:
I have a controller whit two methods

public ActionResult Index1(string c, string d)
    {
        string path = "some path";

        if (System.IO.File.Exists(path))
        {
            var bytes = System.IO.File.ReadAllBytes(path);
            return base.File(bytes, MimeMapping.GetMimeMapping(path));
        }

        path = "/assets/images/no.jpg";
        return File(path, "application/jpeg", "no.jpg");
    }
public ActionResult Index2(string c, string d)
    {
        string path = "some path";
        string _nomefile = "some name";
        string _mime = "";
        if (System.IO.File.Exists(path))
        {
            return new FileStreamResult(new FileStream(path, FileMode.Open), _mime) { FileDownloadName = _nomefile};

        }
        path = "/assets/images/no.jpg";
        return File(path, "application/jpeg", "no.jpg");
    }

This are used by view like this

@foreach (var item in Model.OrderBy(x => x.Titolo))
        {

                    @item.Descrizione

        }

The problem is that IIS return an intermittent 403 forbidden with both methods  and this is totally random. On a list with 30 images 3 or 4 are not displayed.
I do not have any authentication implemented and all files are on the same machine.


问:
Converting separate month, day and year values into a timestamp
I have a month value (1-12), day value (1-31), and a year value (2010,2011,2012). I also have a hour value and a minute value.

How can I give this to strtotime() in a way it can convert it to a timestamp?

Body: strtotime($month."-".$day."-".$year)


问:
Import own files in python
Imagine a main.py.
I have the following structure

```<code>├── main.py
├── moduleX
│   ├── setup.py
│   ├── submoduleA
│   │   └── fileA.py
│   │   └── fileB.py
│   ├── submoduleC
│   │   └── fileC.py
</code>```

Main calls moduleX.setup and setup needs to call functions from submodules A and B.

However moduleX.setup is unable to find the submodules and I don't know how to import them

So it goes like this:
in main.py

```<code>import moduleX.setup
</code>```

in setup.py

```<code>from submoduleA import fileA
from submoduleA import fileB
import submoduleC
</code>```

and all submodules and files are not found.

All subfolders have empty init.py files. I am not sure how to fill them, seems like a recursive problem.

I tried adding moduleX to sys.path
I tried prpending moduleX everywhere
I tried using .. and .

I don't know what I am doing wrong.

答:
Python always uses the relative path to the file you are executing.

```<code>from moduleX.submoduleA import fileA
from moduleX.submoduleA import fileB
import moduleX.submoduleC
</code>```

should work

Title: Import own files in python

Body:
Imagine a main.py.
I have the following structure

├── main.py
├── moduleX
│   ├── setup.py
│   ├── submoduleA
│   │   └── fileA.py
│   │   └── fileB.py
│   ├── submoduleC
│   │   └── fileC.py

Main calls moduleX.setup and setup needs to call functions from submodules A and B.

However moduleX.setup is unable to find the submodules and I don't know how to import them

So it goes like this:
in main.py

import moduleX.setup

in setup.py

from submoduleA import fileA
from submoduleA import fileB
import submoduleC

and all submodules and files are not found.

All subfolders have empty init.py files. I am not sure how to fill them, seems like a recursive problem.

I tried adding moduleX to sys.path
I tried prpending moduleX everywhere
I tried using .. and .

I don't know what I am doing wrong.

Body:
Python always uses the relative path to the file you are executing.

from moduleX.submoduleA import fileA
from moduleX.submoduleA import fileB
import moduleX.submoduleC

should work


问:
Passing multiple items from selectbox is not working in laravel
In my laravel project, am showing select box which contains various clinics, each clinic have api_key and id . I want to pass both id and api_key to Laravel Controller when a form is submitted.
But now am getting only api_key  .ID is not getting.

Following is my code in view page

```<code><form method="post"  action="{{ route('viewcode') }}" name="cliniclist" id="cliniclist" enctype="multipart/form-data" novalidate>
{{ csrf_field() }}
<select class="selectpicker" data-style="btn-info btn-fill btn-block" id="clinic_id" name="clinic_id" key="clinic_key">
         @foreach($clinics as$clinic)
            <option value="{!! $clinic->api_key !!}" id="{!! $clinic->api_key !!}" clinic_key="{!! $clinic->clinicID !!}">{!! $clinic->clinicName !!}</option>
         @endforeach
 </select>

<div class="col-xs-12 col-sm-12 col-md-12 form-action">
      <button type="submit" class="btn btn-fill btn-info">Submit</button>
          <a href="" class="btn btn-default btn-fill">Cancel</a>
 </div>

</form>
</code>```

Here in my code am printing clinic id in clinic_key attribute

Following is my code in controller

```<code>public function store(Request $request)
{
    echo $request->clinic_key;
    die();
    $clinic_api_key = $request->clinic_id;
    return view('locations.viewcode')->with(['clinic_api' => $clinic_api_key]);
}
</code>```

What is the problem here

答:
Option tag can have only one value. Since you are trying to get 2 values there, you might want to join them with some special characters like hyphen "-" or maybe colon ":". In that way you can separate them by that special character in our controller later.

```<code><select class="selectpicker" data-style="btn-info btn-fill btn-block" id="clinic_id" name="clinic_id" key="clinic_key">
@foreach($clinics as$clinic)
<option value="{!! $clinic->api_key.'-'.$clinic->id !!}" id="{!! $clinic->api_key !!}" clinic_key="{!! $clinic->clinicID !!}">{!! $clinic->clinicName !!}</option>
@endforeach
 </select>
</code>```

And then in your controller just get the value of clinic_id field and separate them.

```<code>public function store(Request $request)
    {
        //make sure clinic_id and id does not contain '-' in their values
        $clinic_data = explode('-',$request->clinic_id);
        $clinic_id = $clinic_data[1];
        $clinic_api_key = $clinic_data[0];
        return view('locations.viewcode',compact('clinic_id','clinic_api_key'));

    }
</code>```

for the above code to work. please make sure your api_key and id data from the database does not contain "-" or will break. In that case, use some other separator.

Body:
In my laravel project, am showing select box which contains various clinics, each clinic have api_key and id . I want to pass both id and api_key to Laravel Controller when a form is submitted.
But now am getting only api_key  .ID is not getting.

Following is my code in view page

<form method="post"  action="{{ route('viewcode') }}" name="cliniclist" id="cliniclist" enctype="multipart/form-data" novalidate>
{{ csrf_field() }}
<select class="selectpicker" data-style="btn-info btn-fill btn-block" id="clinic_id" name="clinic_id" key="clinic_key">
         @foreach($clinics as$clinic)
            <option value="{!! $clinic->api_key !!}" id="{!! $clinic->api_key !!}" clinic_key="{!! $clinic->clinicID !!}">{!! $clinic->clinicName !!}</option>
         @endforeach
 </select>

      <button type="submit" class="btn btn-fill btn-info">Submit</button>
          Cancel

</form>

Here in my code am printing clinic id in clinic_key attribute

Following is my code in controller

public function store(Request $request)
{
    echo $request->clinic_key;
    die();
    $clinic_api_key = $request->clinic_id;
    return view('locations.viewcode')->with(['clinic_api' => $clinic_api_key]);
}

What is the problem here

Body:
Option tag can have only one value. Since you are trying to get 2 values there, you might want to join them with some special characters like hyphen "-" or maybe colon ":". In that way you can separate them by that special character in our controller later.

<select class="selectpicker" data-style="btn-info btn-fill btn-block" id="clinic_id" name="clinic_id" key="clinic_key">
@foreach($clinics as$clinic)
<option value="{!! $clinic->api_key.'-'.$clinic->id !!}" id="{!! $clinic->api_key !!}" clinic_key="{!! $clinic->clinicID !!}">{!! $clinic->clinicName !!}</option>
@endforeach
 </select>

And then in your controller just get the value of clinic_id field and separate them.

public function store(Request $request)
    {
        //make sure clinic_id and id does not contain '-' in their values
        $clinic_data = explode('-',$request->clinic_id);
        $clinic_id = $clinic_data[1];
        $clinic_api_key = $clinic_data[0];
        return view('locations.viewcode',compact('clinic_id','clinic_api_key'));

    }

for the above code to work. please make sure your api_key and id data from the database does not contain "-" or will break. In that case, use some other separator.


问:
Corresponding Spring JPA method name for requesting a random row in SQL
In order to get the a record in an SQL table with a name, I am using the following query:

```<code>SELECT * FROM User WHERE User.name = name;
</code>```

And the corresponding Spring JPA method name is the following:

```<code>UserEntity findUserByName(@Param("name") String name);
</code>```

My question is the following:

How can I request a random record from an SQL table?

I know that my SQL query should be the following:

```<code>SELECT * FROM User
ORDER BY RAND()
LIMIT 1;
</code>```

But, what should be the corresponding Spring JPA method name for that?

```<code>UserEntity findUserXXXXXXX (XXXXXXX);
</code>```

答:
if you want to random a list you can easily do it by using PagingAndSortingRepository and provide a random page number where (page_number < page_count)

e.g

```<code>long page_count = (totalRecords / perPage)
//Use PageRequest for PagingAndSortingRepository Pageable object
PageRequest.of(new Random().nextLong(page_count), perPage)
</code>```

or you can provide the random page number from front_end side

Body:
In order to get the a record in an SQL table with a name, I am using the following query:

SELECT * FROM User WHERE User.name = name;

And the corresponding Spring JPA method name is the following:

UserEntity findUserByName(@Param("name") String name);

My question is the following:

How can I request a random record from an SQL table?

I know that my SQL query should be the following:

SELECT * FROM User
ORDER BY RAND()
LIMIT 1;

But, what should be the corresponding Spring JPA method name for that?

UserEntity findUserXXXXXXX (XXXXXXX);

Body:
if you want to random a list you can easily do it by using PagingAndSortingRepository and provide a random page number where (page_number < page_count)

e.g

long page_count = (totalRecords / perPage)
//Use PageRequest for PagingAndSortingRepository Pageable object
PageRequest.of(new Random().nextLong(page_count), perPage)

or you can provide the random page number from front_end side


问:
How to create a hyperlink to file in shared network directory in Microsoft Teams Incoming WebHook?
Is there a way to send a working link to a file in Windows shared folder with Incoming WebHook? E.g. a link to\DESKTOP-HRQNAF6\Test.zip?

I use a PowerShell to send messages to Teams:

```<code>$body = '{"text":"<b>Download:</b></br><ul><li><a href=\"\\\\DESKTOP-HRQNAF6\\Temp\\Test.zip\">Test</a></li></ul>"}'

Invoke-RestMethod -Uri $connectorUri -Method Post -Body $body -ContentType 'application/json'
</code>```

But the link is blank:

I also tried to use such a link: file://desktop-hrqnaf6/Temp/Test.zip, but result is the same

答: @Aneha, Connectors supports three different action ActionCard/HttpPost/openUri using which you can send the url. Please check the documentation for more details.</p>

Body:
Is there a way to send a working link to a file in Windows shared folder with Incoming WebHook? E.g. a link to\DESKTOP-HRQNAF6\Test.zip?

I use a PowerShell to send messages to Teams:

$body = '{"text":"Download:

Test

"}'

Invoke-RestMethod -Uri $connectorUri -Method Post -Body $body -ContentType 'application/json'

But the link is blank:

I also tried to use such a link: file://desktop-hrqnaf6/Temp/Test.zip, but result is the same


问:
Where to find implementation of preprocess_input in Keras / Tensorflow 2.0?
When you use a pretrained network such as VGG, ResNet, etc. it used to be that the they all had corresponding preprocess_input functions directly implemented in the functions that were being called/imported from the VGG / ResNet / etc. modules.

These are helpful to look at for ex. if you want to reverse the transformation.

Nowadays, the functions just look like this:

```<code>@keras_modules_injection
def decode_predictions(*args, **kwargs):
    return vgg16.decode_predictions(*args, **kwargs)
</code>```

Which I got from here: https://github.com/keras-team/keras/blob/6d30ab70a4f116554aa610ec1c00a6bc5f1247f3/keras/applications/vgg16.py

If you search the Github repository for the string 'preprocess_input', there are no implementations to be found.

Where did they go?

答:
Providing answer for the details and reference for the Tensorflow 2.x implementations on for ImageNet data preprocessing & prediction decoding
 under tf.keras.applications.imagenet_utils.

Both tf.keras.applications.imagenet_utils.preprocess_input() and tf.keras.applications.imagenet_utils.decode_predictions() has been moved under a single  class.

Here is the link for the GitHub implementation on the same.

Body:
When you use a pretrained network such as VGG, ResNet, etc. it used to be that the they all had corresponding preprocess_input functions directly implemented in the functions that were being called/imported from the VGG / ResNet / etc. modules.

These are helpful to look at for ex. if you want to reverse the transformation.

Nowadays, the functions just look like this:

@keras_modules_injection
def decode_predictions(*args, **kwargs):
    return vgg16.decode_predictions(*args, **kwargs)

Which I got from here: https://github.com/keras-team/keras/blob/6d30ab70a4f116554aa610ec1c00a6bc5f1247f3/keras/applications/vgg16.py

If you search the Github repository for the string 'preprocess_input', there are no implementations to be found.

Where did they go?


问:
time complexity of if else statement c#
Which of the following two is more efficient from a processing / time complexity point - sorry just trying to get my head round time complexity and potential impact on computer processing time:

Option 1

```<code>if (condition1) {
  function1();
  function2();
}
else {
  function3();
}
</code>```

Option 2

```<code>if (condition1) {
  function1();
}
else {
  function3();
}

if (condition1) {
  function2();
}
else {
  function3();
}
</code>```

Assuming function1() and function2() are both O(N), I think both option 1 and option 2 are O(N) time complexity. However if we could measure how quick both options run on the same computer, would option 1 be quicker or will there be minimal difference?

Thanks!

答:
The Time Complexity of an if is constant, i.e. O(1). So is the complexity of two if's.

If the functions are O(N), the complexity as a whole is O(N).

Time Complexity is not a measure of efficiency, but of scalability. It does not say how much resources (CPU cycles, memory, ...) an algorithm needs, but how much more it will grab when you double the input size.

Please wrap your head aorund that first; time complexity discusses different questions than the cost of individual operations. Don't mix that up.

As for the actual performance difference:

Option 2 will call function3() two times, so comparison depends on that.

If the functions do any siginificant processing, the difference between the two options will ne negligible, it will be dominated by the fluctuations of the functions.

Generally, performance of trivial operations (like an if) cannot be discussed without context.

For conditional jumps, the primary question is: how well predictable are they?

i.e. do they take the same branch most of the time? Two well-predictable conditional jumps are much better than one badly-predicted.

Title: time complexity of if else statement c#

Body:
Which of the following two is more efficient from a processing / time complexity point - sorry just trying to get my head round time complexity and potential impact on computer processing time:

Option 1

if (condition1) {
  function1();
  function2();
}
else {
  function3();
}

Option 2

if (condition1) {
  function1();
}
else {
  function3();
}

if (condition1) {
  function2();
}
else {
  function3();
}

Assuming function1() and function2() are both O(N), I think both option 1 and option 2 are O(N) time complexity. However if we could measure how quick both options run on the same computer, would option 1 be quicker or will there be minimal difference?

Thanks!


问:
Loop Iteration Efficient
You have a loop that iterates over 1,000 items. You want to add a newline to every four items. The items are in an array structure that have numeric index starting at 0. How do you do it?</p>

答:
```<code>for (int i = 0; i < list.size(); i += 4) {
 // add to the item
}
</code>```

The above iterates over every fourth item instead of every single item.

Title: Loop Iteration Efficient

Body:
for (int i = 0; i < list.size(); i += 4) {
 // add to the item
}

The above iterates over every fourth item instead of every single item.


Title: Efficiently getting most and least significant bit in javascript

Body:
Ported/adapted from this answer, this is a nice, string-free, loop-free and conditional-free way for getting the MSB or LSB position from a BigInt.

const deBruijn = [0, 48, -1, -1, 31, -1, 15, 51, -1, 63, 5, -1, -1, -1, 19, -1, 23, 28, -1, -1, -1, 40, 36, 46, -1, 13, -1, -1, -1, 34, -1, 58, -1, 60, 2, 43, 55, -1, -1, -1, 50, 62, 4, -1, 18, 27, -1, 39, 45, -1, -1, 33, 57, -1, 1, 54, -1, 49, -1, 17, -1, -1, 32, -1, 53, -1, 16, -1, -1, 52, -1, -1, -1, 64, 6, 7, 8, -1, 9, -1, -1, -1, 20, 10, -1, -1, 24, -1, 29, -1, -1, 21, -1, 11, -1, -1, 41, -1, 25, 37, -1, 47, -1, 30, 14, -1, -1, -1, -1, 22, -1, -1, 35, 12, -1, -1, -1, 59, 42, -1, -1, 61, 3, 26, 38, 44, -1, 56];
const multiplicator = BigInt("0x6c04f118e9966f6b");

const
  b1 = BigInt(1),
  b2 = BigInt(2),
  b4 = BigInt(4),
  b8 = BigInt(8),
  b16 = BigInt(16),
  b32 = BigInt(32),
  b57 = BigInt(57);

function msb(v) {
  v |= v >> b1;
  v |= v >> b2;
  v |= v >> b4;
  v |= v >> b8;
  v |= v >> b16;
  v |= v >> b32;
  return deBruijn[
    BigInt.asUintN(
      64,
      (BigInt.asUintN(
        64,
        (v * multiplicator))) >> b57)
  ];
}

function lsb(v) {
  v = -v | v;
  return deBruijn[
    BigInt.asUintN(
      64,
      (BigInt.asUintN(
        64,
        (~(v) * multiplicator))) >> b57)
  ];
}
console.log(lsb(BigInt(18)))
console.log(msb(BigInt(18)))


问:
remove zero bytes in a
 element with CSS

Hello
I want to eliminate all this zero bytes ("[]") in my div section with a proper CSS statement.
How is that possible?
Thx in advance for any hints.

答:
In that particular case you can override children elements like that (it's a workaround):

```<code>.x-dataview-item {
  visibility: collapse;
}
.x-dataview-item .fa {
  visibility: visible;
}
</code>```

But like CBroe said - it's always better to repair such problems in the document itself.

Title: remove zero bytes in a <div> element with CSS

Body:
In that particular case you can override children elements like that (it's a workaround):

.x-dataview-item {
  visibility: collapse;
}
.x-dataview-item .fa {
  visibility: visible;
}

But like CBroe said - it's always better to repair such problems in the document itself.


问:
Calculate a pair of dates connected together
The following code outputs me next Friday and next Sunday. I need to output next Friday and next Sunday after the outputted Friday ,not just next Sunday. Otherwise If today is Friday or Saturday, It won't work.

Example: if today is Friday 05/06 my output will be Friday 05/13 and Sunday 05/07 instead of Sunday 05/15 (that is the output I need).

That is the code I'm using actually. How can I fix it to make it work ?

```<code><script type="text/javascript">
 function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date||new Date());
  ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
  return ret;
}

var date = new Date();
console.log(nextWeekdayDate(date, 5));

    $(document).ready(function() {
    $('#button').click(function(e) {
        var checkinf = nextWeekdayDate(null, 5);
        var [yyyy, mm, dd] = checkinf.toISOString().split('T')[0].split('-');
        var checkouts = nextWeekdayDate(null, 7);
            var [cyyy, cm, cd] = checkouts.toISOString().split('T')[0].split('-');

             window.open( "https://www.mydynamiclink.com" + variables );

                            });

        });

</script>

</code>```

thanks :)

答:
The assignment:

```<code>var checkouts = nextWeekdayDate(null, 7);
</code>```

gets the next Sunday after today. What you want is the Sunday after checkinf, so pass it in the call. Also, the day number for Sunday is 0:

```<code>var checkouts = nextWeekdayDate(checkinf, 0);
</code>```

function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date || new Date());
  ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
  return ret;
}

let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);

console.log('Next Friday     : ' +  nextFriday.toDateString() +
  '\nFollowing Sunday: ' + followingSunday.toDateString()); ```

Body:
The following code outputs me next Friday and next Sunday. I need to output next Friday and next Sunday after the outputted Friday ,not just next Sunday. Otherwise If today is Friday or Saturday, It won't work.

Example: if today is Friday 05/06 my output will be Friday 05/13 and Sunday 05/07 instead of Sunday 05/15 (that is the output I need).

That is the code I'm using actually. How can I fix it to make it work ?

thanks :)

Body:
The assignment:

var checkouts = nextWeekdayDate(null, 7);

gets the next Sunday after today. What you want is the Sunday after checkinf, so pass it in the call. Also, the day number for Sunday is 0:

var checkouts = nextWeekdayDate(checkinf, 0);

function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date || new Date());
  ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
  return ret;
}

let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);

console.log('Next Friday     : ' +  nextFriday.toDateString() +
  '\nFollowing Sunday: ' + followingSunday.toDateString());


问:
Visual Studio Code: Intellisense not working
My Visual Studio Code's Intellisense is not working properly. Every time I try to use it with Ctrl + Shift, it only displays a loading message. I'm using Python (with Django) and have installed ms-python.python. I also have Djaneiro. It is still not working.

What seems to be the problem here?

答: If you've tried everything but still if it doesn't work, in my case installing the extension Visual Studio IntelliCode with the Python extension worked.</p>


问:
What happens to an Android thread after the Activity that created it is destroyed?
In my Android app, the main Activity will sometimes start a Thread to load data from a server.  This thread modifies the app's database and edits some important files.  AFAIK, it would appear that this thread continues to execute.  What will happen to this thread if the Android gets into a low memory situation and decides to kill the entire Application?  Will there ever be a situation were this thread might die prematurely?  If so, is there any way I can see that the thread is being killed, and do something about it?

I'm asking because this thread modifies important data in the database, and if it is suddenly killed, the application could stop functioning properly.

答:
You should be using a service:

Because a process running a service is
  ranked higher than a process with
  background activities, an activity
  that initiates a long-running
  operation might do well to start a
  service for that operation, rather
  than simply create a worker
  thread—particularly if the operation
  will likely outlast the activity.

Take a look here: http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html#Lifecycle (where the text I pasted originates)


问:
How to call Amazon S3 bucket using postdata preSigned Url to upload a file using Karate
I have a postdata presigned URL of Amazon S3. I want to use it in a Karate feature file to upload a file (say: pdf)

Here is a sample Curl request that I need to perform Using Karate POST request

```<code>curl --location --request POST '<s3bucketURL>' \
--form 'key=some_key_fileName' \
--form 'x-amz-meta-payload={JsonObject}' \
--form 'Content-Type=application/pdf' \
--form 'bucket=<BucketName>' \
--form 'X-Amz-Algorithm=AWS4-HMAC-SHA256' \
--form 'X-Amz-Credential=<AWS_Credential>' \
--form 'X-Amz-Date=<Date>' \
--form 'Policy=<Policy_Hash>' \
--form 'X-Amz-Signature=<Signature_Hash>' \
--form 'file=@/Users/sahildua/validfile.pdf'
</code>```

I got a response (having the preSignedUrl) from a server and used using below code in a feature-file

```<code>  "url": "<s3bucketURL>",
  "fields": {
    "key": "some_key_fileName",
    "x-amz-meta-payload": "{JsonObject}",
    "Content-Type": "application/pdf",
    "bucket": "<BucketName>",
    "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
    "X-Amz-Credential": "<AWS_Credential>",
    "X-Amz-Date": "<Date>",
    "Policy": "<Policy_Hash>",
    "X-Amz-Signature": "<Signature_Hash>"
</code>```

I tried

```<code>Given url response.url
* def fieldData = response.fields
* print fieldData
* form fields fieldData
And multipart file file = { read: '../testData/validPdfFile.pdf'}
When method post
Then match responseStatus ==  204
</code>```

But I get a validation XML error from Amazon S3 for incorrect field values

```<code><Error>
<Code>InvalidArgument</Code>
<Message>Bucket POST must contain a field named 'key'. If it is specified, please check the order of the fields.</Message>
<ArgumentName>key</ArgumentName>
<ArgumentValue></ArgumentValue>
<RequestId><id></RequestId>
<HostId><someid></HostId>
</Error>
</code>```

I expect 204 No Content and the file to be uploaded the S3 bucket

答:
Try this change:

```<code>And multipart file file = { read: '../testData/validPdfFile.pdf'}
</code>```

Read this for a little more explanation: https://github.com/intuit/karate/tree/develop#multipart-file

Other than that you seem to be doing everything right. So it is up to your de-bugging skills now. Or give us a way to replicate: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Body:
I have a postdata presigned URL of Amazon S3. I want to use it in a Karate feature file to upload a file (say: pdf)

Here is a sample Curl request that I need to perform Using Karate POST request

curl --location --request POST '<s3bucketURL>' \
--form 'key=some_key_fileName' \
--form 'x-amz-meta-payload={JsonObject}' \
--form 'Content-Type=application/pdf' \
--form 'bucket=<BucketName>' \
--form 'X-Amz-Algorithm=AWS4-HMAC-SHA256' \
--form 'X-Amz-Credential=<AWS_Credential>' \
--form 'X-Amz-Date=<Date>' \
--form 'Policy=<Policy_Hash>' \
--form 'X-Amz-Signature=<Signature_Hash>' \
--form 'file=@/Users/sahildua/validfile.pdf'

I got a response (having the preSignedUrl) from a server and used using below code in a feature-file

  "url": "<s3bucketURL>",
  "fields": {
    "key": "some_key_fileName",
    "x-amz-meta-payload": "{JsonObject}",
    "Content-Type": "application/pdf",
    "bucket": "<BucketName>",
    "X-Amz-Algorithm": "AWS4-HMAC-SHA256",
    "X-Amz-Credential": "<AWS_Credential>",
    "X-Amz-Date": "<Date>",
    "Policy": "<Policy_Hash>",
    "X-Amz-Signature": "<Signature_Hash>"

I tried

Given url response.url
* def fieldData = response.fields
* print fieldData
* form fields fieldData
And multipart file file = { read: '../testData/validPdfFile.pdf'}
When method post
Then match responseStatus ==  204

But I get a validation XML error from Amazon S3 for incorrect field values

<Error>
InvalidArgument
<Message>Bucket POST must contain a field named 'key'. If it is specified, please check the order of the fields.</Message>
<ArgumentName>key</ArgumentName>
<ArgumentValue></ArgumentValue>
<RequestId><id></RequestId>
<HostId><someid></HostId>
</Error>

I expect 204 No Content and the file to be uploaded the S3 bucket

Body:
Try this change:

And multipart file file = { read: '../testData/validPdfFile.pdf'}

Read this for a little more explanation: https://github.com/intuit/karate/tree/develop#multipart-file

Other than that you seem to be doing everything right. So it is up to your de-bugging skills now. Or give us a way to replicate: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue


问:
how to get array value in ajax success method?
I want to redirect to the fastest URL after ajax called all the URLs, but when I alert the value, I get undefined:

```<code>var servers = ["url1", "url2", "url3"];
for (var i = 0; i < servers.length; i++) {
  $.ajax({
    type: "GET",
    url: servers[i],
    data: {},
    cache: false,
    success: function(output) {
      // window.location.href = servers[i]
      alert(servers[i]);
    }
  });
}
</code>```

答:
You can use Promise.race instead of iteration. MDN

```<code>const servers = ["url1", "url2", "url3"];
const requests = servers.map(server => $.ajax({...}));

Promise.race(requests)
    .then(/* handle the fastest request */)
    .catch(/* catch error here */)
</code>```

Body:
I want to redirect to the fastest URL after ajax called all the URLs, but when I alert the value, I get undefined:

var servers = ["url1", "url2", "url3"];
for (var i = 0; i < servers.length; i++) {
  $.ajax({
    type: "GET",
    url: servers[i],
    data: {},
    cache: false,
    success: function(output) {
      // window.location.href = servers[i]
      alert(servers[i]);
    }
  });
}

Body:
You can use Promise.race instead of iteration. MDN

const servers = ["url1", "url2", "url3"];
const requests = servers.map(server => $.ajax({...}));

Promise.race(requests)
    .then(/* handle the fastest request */)
    .catch(/* catch error here */)


问:
Named Arguments do not work in a string with conditional logic
I have a multiline string with an in-line if condition as follows:

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        Good bye. """
</code>```

However, when I insert a named parameter, it does not seem to properly treat it. With some testing I found out that removing the IF from the string would allow the named parameters to work

```<code>my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}
</code>```

Is there a specific reason why this won't work?

答:
With f-string it would be more effective:

my_string =  f"""
        Hello my name is {'John' if client == "j123" else 'Mary'}

        {msg_key}

        Good bye. """.format(msg_key="Additional msg")
```

Body:
I have a multiline string with an in-line if condition as follows:

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        Good bye. """

However, when I insert a named parameter, it does not seem to properly treat it. With some testing I found out that removing the IF from the string would allow the named parameters to work

my_string=  """
        Hello my name is """ + ('John' if client == "j123" else 'Mary') + """

        %(msg_key)s

        Good bye. """ % {"msg_key" : "Additional msg"}

Is there a specific reason why this won't work?


问:
Return list of all dictionary keys
Is there a way to return a list of all dictionary keys in the provided input (at all levels)?

The keys should be ordered by level, for example:

```<code>{
    "A": 1,
    "B": [{
        "B1": 1,
        "B2": 1
    }, {
        "B3": 1,
        "B4": 1
    }],
    "C": {
        "C1": 1,
        "C2": 1
    }
}
</code>```

I have tried using dict.keys() and dict.items() but did not get the desired output.

The output should be like this ["A", "B", "C", "B1", "B2", "B3", "B4", "C1", "C2"].

Any help is appreciated.

答:
I think i found it</p>

```<code>#In order to convert nested list to single list
import more_itertools
a={"A": 1,
    "B": [{
        "B1": 1,
        "B2": 1
    }, {
        "B3": 1,
        "B4": 1
    }],
    "C": {
        "C1": 1,
        "C2": 1
    }
}
dic_key=[]
for i in a:
    dic_key.append(i)
for i in a:
    if type(a[i]) is list :
        dic_key+=list(map(lambda x:list(x.keys()),a[i]))
    elif type(a[i]) is dict:
        dic_key+=list(map(lambda x: x,a[i]))
print(list(more_itertools.collapse(dic_key)))
</code>```

Title: Return list of all dictionary keys

Body:
Is there a way to return a list of all dictionary keys in the provided input (at all levels)?

The keys should be ordered by level, for example:

{
    "A": 1,
    "B": [{
        "B1": 1,
        "B2": 1
    }, {
        "B3": 1,
        "B4": 1
    }],
    "C": {
        "C1": 1,
        "C2": 1
    }
}

I have tried using dict.keys() and dict.items() but did not get the desired output.

The output should be like this ["A", "B", "C", "B1", "B2", "B3", "B4", "C1", "C2"].

Any help is appreciated.

Body:
I think i found it

#In order to convert nested list to single list
import more_itertools
a={"A": 1,
    "B": [{
        "B1": 1,
        "B2": 1
    }, {
        "B3": 1,
        "B4": 1
    }],
    "C": {
        "C1": 1,
        "C2": 1
    }
}
dic_key=[]
for i in a:
    dic_key.append(i)
for i in a:
    if type(a[i]) is list :
        dic_key+=list(map(lambda x:list(x.keys()),a[i]))
    elif type(a[i]) is dict:
        dic_key+=list(map(lambda x: x,a[i]))
print(list(more_itertools.collapse(dic_key)))


问:
How to get the entire polyline to be visible on a google map
I have a polyline that I get from a directions request and I want it to show a google map with all the points visible but I do not know how to get the camera to show all the points.
I add the polyline like this:

```<code>fun MapFragment.addPolyline(line: String) {
    val decodedPath: List<LatLng> = PolyUtil.decode(line)
    getMap()?.addPolyline(PolylineOptions().addAll(decodedPath))
}
</code>```

Then I center the camera on one of the points like this:

```<code>fun MapFragment.setCamera(latLng: LatLng) {
    getMap()?.moveCamera(
        CameraUpdateFactory.newLatLngZoom(
            latLng, 20f
        )
    )
}
</code>```

However this only shows part of the polyline. I need the zoom to change so as the map covers the entire polyline. How do I achieve that?

答:
You have to make the latlngbound .You can use this methods to draw polyline of whole points.</p>

```<code>fun drawPolyline(listlatlng: ArrayList<LatLng>) {
var latlngHistory: ArrayList<LatLng> = ArrayList()
        val bc = LatLngBounds.Builder()
        for (item in listlatlng) {
            latlngHistory.add(item)
            bc.include(item)
        }
        mMap?.clear()
        var path: Polyline = mMap!!.addPolyline(
            PolylineOptions().addAll(latlngHistory)
        )
        path.width = 10F
        path.color = Color.parseColor("#A3258F")

        if (latlngHistory != null && latlngHistory.size != 0) {
            if (latlngHistory.size < 2) {
                bc.include(latlngHistory.get(0))
                bc.include(latlngHistory.get(latlngHistory.size - 1))
            }
            //cardll is a layout refernce on which map is displaying
            val width = cardll?.width
            val height = cardll?.height
            if (width != null && height != null) {
                mMap!!.moveCamera(
                    CameraUpdateFactory.newLatLngBounds(
                        bc.build(),
                        width!!,
                        height!!,
                        60
                    )
                )
            }
        }
    }
</code>```

Body:
I have a polyline that I get from a directions request and I want it to show a google map with all the points visible but I do not know how to get the camera to show all the points.
I add the polyline like this:

fun MapFragment.addPolyline(line: String) {
    val decodedPath: List<LatLng> = PolyUtil.decode(line)
    getMap()?.addPolyline(PolylineOptions().addAll(decodedPath))
}

Then I center the camera on one of the points like this:

fun MapFragment.setCamera(latLng: LatLng) {
    getMap()?.moveCamera(
        CameraUpdateFactory.newLatLngZoom(
            latLng, 20f
        )
    )
}

However this only shows part of the polyline. I need the zoom to change so as the map covers the entire polyline. How do I achieve that?

Body:
You have to make the latlngbound .You can use this methods to draw polyline of whole points.

fun drawPolyline(listlatlng: ArrayList<LatLng>) {
var latlngHistory: ArrayList<LatLng> = ArrayList()
        val bc = LatLngBounds.Builder()
        for (item in listlatlng) {
            latlngHistory.add(item)
            bc.include(item)
        }
        mMap?.clear()
        var path: Polyline = mMap!!.addPolyline(
            PolylineOptions().addAll(latlngHistory)
        )
        path.width = 10F
        path.color = Color.parseColor("#A3258F")

        if (latlngHistory != null && latlngHistory.size != 0) {
            if (latlngHistory.size < 2) {
                bc.include(latlngHistory.get(0))
                bc.include(latlngHistory.get(latlngHistory.size - 1))
            }
            //cardll is a layout refernce on which map is displaying
            val width = cardll?.width
            val height = cardll?.height
            if (width != null && height != null) {
                mMap!!.moveCamera(
                    CameraUpdateFactory.newLatLngBounds(
                        bc.build(),
                        width!!,
                        height!!,
                        60
                    )
                )
            }
        }
    }


问:
Button does not look the same on mobile as in android studio layout view
I have defined three buttons using the same drawable background file "find_button.xml". The "start server activity" button (id="start_button") ignores for some reason the file "find_button.xml" .
I am not able to find any mistake..

Layout view in android studio:

Layout View on mobile:

xml Layoutfile:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1A91C6"
    tools:context=".ServerInitial">

    <Button
        android:id="@+id/start_button"

        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:onClick="startServerActivity"
        android:text="@string/start_server_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toTopOf="@+id/close_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ListView
        android:id="@+id/peers_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="24dp"

        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:cacheColorHint="?android:attr/colorMultiSelectHighlight"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/start_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/find_button">

    </ListView>

    <Button
        android:id="@+id/find_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:drawableLeft="@drawable/ic_search_black_72dp"
        android:gravity="left|center_vertical"
        android:onClick="sucheGeräte"
        android:text="@string/suchen_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/close_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="32dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#E3931D"
        android:onClick="closeConnection"
        android:text="@string/close_connection"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

drawable backgroundfile "find_button.xml"

```<code>    <?xml vers`enter code here`ion="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="20dp" />
</shape>
</code>```

New Info: I installed new and realized , that while permission requests showed up, the button looked as it was supposed to look.After permission requests had been confirmed, the button changed back to it's old design.

I am using a pretty nice routine "has permissions" in onCreate for checking permissions, maybe the bug is somewhere there.

```<code>public class ServerInitial extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {

public static final String TAG = MainActivity.class.getSimpleName();
public WifiP2pManager manager;
public WifiP2pManager.Channel channel2;
public BroadcastReceiver receiver;
public IntentFilter intentFilter;
private List<WifiP2pDevice> peers_list = new ArrayList<>();
private ListView peerslist;
private int count = 0;
private String[] devicenames;
public WifiP2pDevice device;
public Button start;

private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {

        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.ACCESS_FINE_LOCATION
};

public static boolean hasPermissions(Context context, String... permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    if (!hasPermissions(this, PERMISSIONS))
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);

    assert manager != null;
    channel2 = manager.initialize(this, getMainLooper(), null);
    receiver = new P2PBroadcastReceiver(manager, channel2, ServerInitial.this, ServerInitial.this,
            ServerInitial.this);
    intentFilter = new IntentFilter();
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    setContentView(R.layout.activity_server_initial);

    start = findViewById(R.id.start_button);
    // Check if recreating a previously destroyed instance.
    if (savedInstanceState != null) {
        //Restore value of members from saved state.
        devicenames = savedInstanceState.getStringArray("list");
        fillListe();
    } else {

        devicenames = null;

        // Initialize members with default values for a new instance.
        // ...
    }

    manager.discoverPeers(channel2, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            System.out.println("Da draussen ist was los .......");
            //ergebnisSuche.setText("Da ist was los...");

        }

        @Override
        public void onFailure(int reason) {
            System.out.println("Da draussen ist nix los .......");
            //ergebnisSuche.setText("Da ist nix los...");

        }
    });

}
</code>```

答:
There's nothing wrong in your code. Try reinstalling your app once and it should work fine. if it doesn't try invalidate caches and restart option in your android studio and then install/run your app.
I tried your same code in my physical device as well as in emulator and here are the outputs.
Physical Device

Body:
I have defined three buttons using the same drawable background file "find_button.xml". The "start server activity" button (id="start_button") ignores for some reason the file "find_button.xml" .
I am not able to find any mistake..

Layout view in android studio:

Layout View on mobile:

xml Layoutfile:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#1A91C6"
    tools:context=".ServerInitial">

    <Button
        android:id="@+id/start_button"

        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:onClick="startServerActivity"
        android:text="@string/start_server_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toTopOf="@+id/close_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <ListView
        android:id="@+id/peers_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginStart="24dp"

        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="24dp"
        android:cacheColorHint="?android:attr/colorMultiSelectHighlight"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="@+id/start_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/find_button">

    </ListView>

    <Button
        android:id="@+id/find_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#DCB235"
        android:drawableLeft="@drawable/ic_search_black_72dp"
        android:gravity="left|center_vertical"
        android:onClick="sucheGeräte"
        android:text="@string/suchen_button"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/close_button"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_marginStart="24dp"
        android:layout_marginLeft="24dp"
        android:layout_marginEnd="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginBottom="32dp"
        android:background="@drawable/find_button"
        android:backgroundTint="#E3931D"
        android:onClick="closeConnection"
        android:text="@string/close_connection"
        android:textColor="#FFFFFF"
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

drawable backgroundfile "find_button.xml"

    <?xml vers`enter code here`ion="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="20dp" />
</shape>

New Info: I installed new and realized , that while permission requests showed up, the button looked as it was supposed to look.After permission requests had been confirmed, the button changed back to it's old design.

I am using a pretty nice routine "has permissions" in onCreate for checking permissions, maybe the bug is somewhere there.

public class ServerInitial extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {

public static final String TAG = MainActivity.class.getSimpleName();
public WifiP2pManager manager;
public WifiP2pManager.Channel channel2;
public BroadcastReceiver receiver;
public IntentFilter intentFilter;
private List<WifiP2pDevice> peers_list = new ArrayList<>();
private ListView peerslist;
private int count = 0;
private String[] devicenames;
public WifiP2pDevice device;
public Button start;

private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {

        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.ACCESS_FINE_LOCATION
};

public static boolean hasPermissions(Context context, String... permissions) {
    if (context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    if (!hasPermissions(this, PERMISSIONS))
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);

    manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);

    assert manager != null;
    channel2 = manager.initialize(this, getMainLooper(), null);
    receiver = new P2PBroadcastReceiver(manager, channel2, ServerInitial.this, ServerInitial.this,
            ServerInitial.this);
    intentFilter = new IntentFilter();
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    setContentView(R.layout.activity_server_initial);

    start = findViewById(R.id.start_button);
    // Check if recreating a previously destroyed instance.
    if (savedInstanceState != null) {
        //Restore value of members from saved state.
        devicenames = savedInstanceState.getStringArray("list");
        fillListe();
    } else {

        devicenames = null;

        // Initialize members with default values for a new instance.
        // ...
    }

    manager.discoverPeers(channel2, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            System.out.println("Da draussen ist was los .......");
            //ergebnisSuche.setText("Da ist was los...");

        }

        @Override
        public void onFailure(int reason) {
            System.out.println("Da draussen ist nix los .......");
            //ergebnisSuche.setText("Da ist nix los...");

        }
    });

}


问:
Implementation of ceil() and floor()
Just curious how are these implemented. I can't see where I would start. Do they work directly on the float's/double's bits?

Also where can I find the source code of functions from math.h? All I find are either headers with prototypes or files with functions that call other functions from somewhere else.

EDIT: Part of the message was lost after editing the title. What I meant in particular were the ceil() and floor() functions.

答:
On many platforms (such as any modern x86-compatible), many of the maths functions are implemented directly in the floating-point hardware (see for example http://en.wikipedia.org/wiki/X86_instruction_listings#x87_floating-point_instructions).  Not all of them are used, though (as I learnt through comments to other answers here).  But, for instance, the sqrt library function is often implemented directly in terms of the SSE hardware instruction.

For some ideas on how the underlying algorithms work, you might try reading Numerical Recipes, which is available as PDFs somewhere.

Title: Implementation of ceil() and floor()


问:
const doesn't seem to pass value through functions
I define two DOM selectors as constants but I can't seem to call them through functions. Essentially I should be able to pass two constants as arguments of a function where one gets it's display style set to block and the other set to none.

My JS is:

```<code>const divOne = document.querySelector("#divOne");
const divTwo = document.querySelector("#divTwo");

function showHide(show, hide){
    show.style.display = "block";
    hide.style.display = "none";
}

function changeDisplay(arg) {
    //do some other bits
    showHide(divOne, divTwo);
}
</code>```

But this doesn't seem to change and I get an error

```<code>Uncaught TypeError: Cannot read property 'style' of null
        at showHide
</code>```

Am I not able to pass querySelectors through functions?

答:
You can pass anything with functions in js )
It's difficult to say what is happening here just looking at pieces of puzzle but my suggestion is to check when do you actually call changeDisplay or showHide. I mean is your DOM built and ready?
Maybe at the time of calling those functions your DOM tree is not ready</p>

Body:
I define two DOM selectors as constants but I can't seem to call them through functions. Essentially I should be able to pass two constants as arguments of a function where one gets it's display style set to block and the other set to none.

My JS is:

const divOne = document.querySelector("#divOne");
const divTwo = document.querySelector("#divTwo");

function showHide(show, hide){
    show.style.display = "block";
    hide.style.display = "none";
}

function changeDisplay(arg) {
    //do some other bits
    showHide(divOne, divTwo);
}

But this doesn't seem to change and I get an error

Uncaught TypeError: Cannot read property 'style' of null
        at showHide

Am I not able to pass querySelectors through functions?


问:
Component Re-renders after clicking NavLink & loads same data Multiple times
I have made a sample e-commerce site for practice & I used React, Redux & Router-DOM. For the first time, everything loads perfectly. it has two routes ScreenShot-Link. Home route takes me to the Home page where the problem occurs & the Upload route takes me to the upload page. But when I again go back to HomeRoute the data which was fetched from an API doesn't re-render instead the state gets doubled I mean the existing state remains unchanged but for some reason, the Data gets fetched again and the elements get rendered for 2 times ScreenShot-2-Link.

Body Element which gets doubled if I route back to it from another route...

```<code>const Body = ({getProducts, deleteProduct, productState})=>{
    const {products, loading, error} = productState;

    useEffect(()=>{
        getProducts()
    }, [getProducts])

    const deleteProducts = (id)=>{
        deleteProduct(id)
    }

    return (
        <div className="display-flex width-full flex-wrap justify-content-center">
            {!loading && !error && products?products.map(product=>(
                product.data?product.data.map(d=>(
                    <BodyDiv
                        key={uuid.v4()}
                        imgSrc={d.imgSrc}
                        title={d.title}
                        details={d.details}
                        description={d.description}
                        onClick={()=>deleteProducts(d._id)}
                    />
                )):product.map(d=>(
                    <BodyDiv
                    key={uuid.v4()}
                    imgSrc={d.imgSrc}
                    title={d.title}
                    details={d.details}
                    description={d.description}
                    onClick={()=>deleteProducts(d._id)}
                />
                ))
            ))
            : loading&&!error
            ? <div className="vertical-center-strict horizontal-center-strict">Loading.......</div>
            : <div className="vertical-center-strict horizontal-center-strict">No Internet!</div>
        }
        </div>
    )
}

const BodyDiv = (props)=>{
    return(
        <div className="container-div width-full card tiny-padding align-self-start">
        <img title={props.title} className="img-responsive hover-filter" src={props.imgSrc}/>
        <h2 className="text-align-center">{props.title}</h2>
        <h5>{props.details}</h5>
        <p className="text-align-justify">{props.description}</p>
        <button
        className="btn btn-danger"
        onClick={props.onClick}
        >Delete</button>
        </div>
    )
}

BodyDiv.propTypes = {
    title: PropTypes.string.isRequired,
    img: PropTypes.string,
    details: PropTypes.string.isRequired,
    description: PropTypes.string,
    onClick: PropTypes.func

}
const mapStateToProps = (state)=>({
    productState: state.productState
})
const conn = connect(mapStateToProps, {getProducts, deleteProduct})(Body)

export default conn;
</code>```

Router Component & Nav Component

//Parent Router Comonent
const App = () => {
  return (
    <Router>
      <AppNavBar />
      <Switch>
        <Route path="/" exact>

        </Route>
        <Route path="/upload">
          <Upload />
        </Route>
        <Route path="*">

404

Page doesn't exist

Please give the correct address!

        </Route>
      </Switch>
    </Router>
  );
};

export default App;

//NavLink Components..
const NavBar = ()=>{
return(
<>
 <NavLink activeClassName="link" to="/" exact>
    <NavItem content="Home" /> // element with content as a prop
 <NavLink>
 <NavLink activeClassName="link" to="/upload">
    <NavItem content="Upload"
 </NavLink>
</>
         )
       }
}
```

<h2>My Redux Code: <em>Store & Reducers</em></h2>

```//Store
import {createStore, applyMiddleware} from "redux"
import rootReducer from "./reducers/index"
import thunk from "redux-thunk"

const middleWare = [thunk]

const store = createStore(rootReducer, applyMiddleware(...middleWare))

export default store

//RootReducer
import {
  FETCHED_PRODUCTS,
  FETCHING_PRODUCTS,
  ERROR_GET_PRODUCTS,
  DELETED_PRODUCT,
  ERROR_DELETING_PRODUCT
} from "../actions/productActions";

const initialState = {
  products: [],
  loading: true,
  error: false,
};

const productReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCHING_PRODUCTS:
      return {
        ...state,
        loading: true,
      };
    case FETCHED_PRODUCTS:
      return {
        ...state,
        products: state.products.concat(action.payload),
        loading: false,
        error: false,
      };
    case ERROR_GET_PRODUCTS:
      return {
        ...state,
        loading: false,
      };
    case DELETED_PRODUCT:
      return {
        ...state,
        products: state.products.map((product) =>
          product.data.filter((d) => d._id !== action.payload)
        ),
        error: false,
      };
    case ERROR_DELETING_PRODUCT:
      return {
        ...state,
        error: true,
      };
    default:
      return state;
  }
};

export default productReducer;
```

<h2>ActionCreators</h2>

```export const getProducts = (payload)=>(dispatch)=>{
    return(
     fetch("/api/products")
    .then(res=>{
        dispatch({
            type:FETCHING_PRODUCTS
        })
        if(!res.ok){
            dispatch({
                type: ERROR_GET_PRODUCTS
            })
        }
    return res.json();
    })
    .then(json=>{
        if(json)dispatch({
        type: FETCHED_PRODUCTS,
        payload: json
    })
})
    .catch(err=>{
        console.log("Error!! failed to fetch data: "+ err)
    })
    )
}

export const deleteProduct = (payload)=>dispatch=>{
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var requestOptions = {
  method: 'DELETE',
  headers: myHeaders,
  body: JSON.stringify({"_id": payload}),
  redirect: 'follow'
};
    fetch("/api/product-delete", requestOptions).then(res=>{
        dispatch({
            type: DELETED_PRODUCT,
            payload
        })
        if(res.status === 501 || res.status === 403){
             dispatch({
                 type: ERROR_DELETING_PRODUCT,
             })
         }
    })
    .catch(err=>{
        console.log("Failed to Delete")
    })
}

```

Please help me I have been searching for the solution for 4 hours...It would be great if you help me...Thanks in advance

答:
When using the useEffect hook the second parameter are dependencies.. so it calls the function again if the dependencies change. Now since getProductsis a function, it will never get called again. Instead, you should put products in there

```<code>useEffect(()=>{
        getProducts()
    }, [products])
//will refetch data everytime product state is updated.
</code>```

It is a little bit hard to see, what is going on in the code. But I suspect maybe this is the problem. Otherwise let me know.

Body:
I have made a sample e-commerce site for practice & I used React, Redux & Router-DOM. For the first time, everything loads perfectly. it has two routes ScreenShot-Link. Home route takes me to the Home page where the problem occurs & the Upload route takes me to the upload page. But when I again go back to HomeRoute the data which was fetched from an API doesn't re-render instead the state gets doubled I mean the existing state remains unchanged but for some reason, the Data gets fetched again and the elements get rendered for 2 times ScreenShot-2-Link.

Body Element which gets doubled if I route back to it from another route...

const Body = ({getProducts, deleteProduct, productState})=>{
    const {products, loading, error} = productState;

    useEffect(()=>{
        getProducts()
    }, [getProducts])

    const deleteProducts = (id)=>{
        deleteProduct(id)
    }

    return (

            {!loading && !error && products?products.map(product=>(
                product.data?product.data.map(d=>(
                    <BodyDiv
                        key={uuid.v4()}
                        imgSrc={d.imgSrc}
                        title={d.title}
                        details={d.details}
                        description={d.description}
                        onClick={()=>deleteProducts(d._id)}
                    />
                )):product.map(d=>(
                    <BodyDiv
                    key={uuid.v4()}
                    imgSrc={d.imgSrc}
                    title={d.title}
                    details={d.details}
                    description={d.description}
                    onClick={()=>deleteProducts(d._id)}
                />
                ))
            ))
            : loading&&!error
            ?
Loading.......

            :
No Internet!

        }

    )
}

const BodyDiv = (props)=>{
    return(

{props.title}

{props.details}

{props.description}

        <button
        className="btn btn-danger"
        onClick={props.onClick}
        >Delete</button>

    )
}

BodyDiv.propTypes = {
    title: PropTypes.string.isRequired,
    img: PropTypes.string,
    details: PropTypes.string.isRequired,
    description: PropTypes.string,
    onClick: PropTypes.func

}
const mapStateToProps = (state)=>({
    productState: state.productState
})
const conn = connect(mapStateToProps, {getProducts, deleteProduct})(Body)

export default conn;

Router Component & Nav Component

//Parent Router Comonent
const App = () => {
  return (
    <Router>
      <AppNavBar />
      <Switch>
        <Route path="/" exact>

        </Route>
        <Route path="/upload">
          <Upload />
        </Route>
        <Route path="*">

404

Page doesn't exist

Please give the correct address!

        </Route>
      </Switch>
    </Router>
  );
};

export default App;

//NavLink Components..
const NavBar = ()=>{
return(
<>
 <NavLink activeClassName="link" to="/" exact>
    <NavItem content="Home" /> // element with content as a prop
 <NavLink>
 <NavLink activeClassName="link" to="/upload">
    <NavItem content="Upload"
 </NavLink>
</>
         )
       }
}

My Redux Code: Store & Reducers

//Store
import {createStore, applyMiddleware} from "redux"
import rootReducer from "./reducers/index"
import thunk from "redux-thunk"

const middleWare = [thunk]

const store = createStore(rootReducer, applyMiddleware(...middleWare))

export default store

//RootReducer
import {
  FETCHED_PRODUCTS,
  FETCHING_PRODUCTS,
  ERROR_GET_PRODUCTS,
  DELETED_PRODUCT,
  ERROR_DELETING_PRODUCT
} from "../actions/productActions";

const initialState = {
  products: [],
  loading: true,
  error: false,
};

const productReducer = (state = initialState, action) => {
  switch (action.type) {
    case FETCHING_PRODUCTS:
      return {
        ...state,
        loading: true,
      };
    case FETCHED_PRODUCTS:
      return {
        ...state,
        products: state.products.concat(action.payload),
        loading: false,
        error: false,
      };
    case ERROR_GET_PRODUCTS:
      return {
        ...state,
        loading: false,
      };
    case DELETED_PRODUCT:
      return {
        ...state,
        products: state.products.map((product) =>
          product.data.filter((d) => d._id !== action.payload)
        ),
        error: false,
      };
    case ERROR_DELETING_PRODUCT:
      return {
        ...state,
        error: true,
      };
    default:
      return state;
  }
};

export default productReducer;

ActionCreators

export const getProducts = (payload)=>(dispatch)=>{
    return(
     fetch("/api/products")
    .then(res=>{
        dispatch({
            type:FETCHING_PRODUCTS
        })
        if(!res.ok){
            dispatch({
                type: ERROR_GET_PRODUCTS
            })
        }
    return res.json();
    })
    .then(json=>{
        if(json)dispatch({
        type: FETCHED_PRODUCTS,
        payload: json
    })
})
    .catch(err=>{
        console.log("Error!! failed to fetch data: "+ err)
    })
    )
}

export const deleteProduct = (payload)=>dispatch=>{
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var requestOptions = {
  method: 'DELETE',
  headers: myHeaders,
  body: JSON.stringify({"_id": payload}),
  redirect: 'follow'
};
    fetch("/api/product-delete", requestOptions).then(res=>{
        dispatch({
            type: DELETED_PRODUCT,
            payload
        })
        if(res.status === 501 || res.status === 403){
             dispatch({
                 type: ERROR_DELETING_PRODUCT,
             })
         }
    })
    .catch(err=>{
        console.log("Failed to Delete")
    })
}

Please help me I have been searching for the solution for 4 hours...It would be great if you help me...Thanks in advance

Body:
When using the useEffect hook the second parameter are dependencies.. so it calls the function again if the dependencies change. Now since getProductsis a function, it will never get called again. Instead, you should put products in there

useEffect(()=>{
        getProducts()
    }, [products])
//will refetch data everytime product state is updated.

It is a little bit hard to see, what is going on in the code. But I suspect maybe this is the problem. Otherwise let me know.


问:
Node, Express, 404 error / cannot get route
I am building an Express app and having some issues with routing. All of my routes are working perfectly except for one.

I have a route/admin/products that works:

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

router.get("/admin/products", (req, res) => {
    res.send(productsIndexTemplate({ products }));
});
</code>```

Another route/admin/products/new that also works:

```<code>router.get("/admin/products/new", requireAuth, (req, res) => {
    res.send(productsNewTemplate({}))
});
</code>```

but this route doesn't work:

```<code>router.get('/admin/products/:id/edit'), async (req, res) => {
    const product = await productsRepo.getOne(req.params.id);
    res.send(productsEditTemplate( {product} ));
};
</code>```

I get the proper URL (meaning that I get a proper ID in the url so the req.params.id is not undefined or null but I have this message:

```<code>Cannot GET /admin/products/08a4dc4f/edit
</code>```

I don't think the problem is with my code as the other routes are working except the last one.

答:
You added a parenthesis(closing bracket)  in route.

```<code>router.get('/admin/products/:id/edit'), async (req, res) => { //<---- Your error is in this line. After edit you added closing bracket.
    const product = await productsRepo.getOne(req.params.id);
    res.send(productsEditTemplate( {product} ));
};
</code>```

Replace with below code.

```<code>router.get('/admin/products/:id/edit', async (req, res) => {
    const product = await productsRepo.getOne(req.params.id);
    res.send(productsEditTemplate( {product} ));
});
</code>```

Body:
I am building an Express app and having some issues with routing. All of my routes are working perfectly except for one.

I have a route/admin/products that works:

const router = express.Router();

router.get("/admin/products", (req, res) => {
    res.send(productsIndexTemplate({ products }));
});

Another route/admin/products/new that also works:

router.get("/admin/products/new", requireAuth, (req, res) => {
    res.send(productsNewTemplate({}))
});

but this route doesn't work:

router.get('/admin/products/:id/edit'), async (req, res) => {
    const product = await productsRepo.getOne(req.params.id);
    res.send(productsEditTemplate( {product} ));
};

I get the proper URL (meaning that I get a proper ID in the url so the req.params.id is not undefined or null but I have this message:

Cannot GET /admin/products/08a4dc4f/edit

I don't think the problem is with my code as the other routes are working except the last one.

Body:
You added a parenthesis(closing bracket)  in route.

router.get('/admin/products/:id/edit'), async (req, res) => { //<---- Your error is in this line. After edit you added closing bracket.
    const product = await productsRepo.getOne(req.params.id);
    res.send(productsEditTemplate( {product} ));
};

Replace with below code.

router.get('/admin/products/:id/edit', async (req, res) => {
    const product = await productsRepo.getOne(req.params.id);
    res.send(productsEditTemplate( {product} ));
});