问:
Root priv can't be dropped in python even after seteuid. A bug?
Root priv can't be dropped in python even after seteuid. A bug?

EDIT Summary: I forgot to drop gid. The accepted answer may help you, though.

Hi. I can't drop the root privilege in python 3.2 on my linux. In fact, even after seteuid(1000), it can read root-owned 400-mode files. The euid is surely set to 1000!

I found after empty os.fork() call, the privileged access is correctly denied. (But it's only in the parent. The child can still read illegitimately.) Is it a bug in python, or is linux so?

Try the code below. Comment out one of the three lines at the bottom, and run as root.

Thanks beforehand.

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

# Python seteuid pitfall example.
# Run this __as__ the root.

# Here, access to root-owned files /etc/sudoers and /etc/group- are tried.
# Simple access to them *succeeds* even after seteuid(1000) which should fail.

# Three functions, stillRoot(), forkCase() and workAround() are defined.
# The first two seem wrong. In the last one, access fails, as desired.

# ***Comment out*** one of three lines at the bottom before execution.

# If your python is < 3.2, comment out the entire def of forkCase()

import os

def stillRoot():
    """Open succeeds, but it should fail."""
    os.seteuid(1000)
    open('/etc/sudoers').close()

def forkCase():
    """Child can still open it. Wow."""
    # setresuid needs python 3.2
    os.setresuid(1000, 1000, 0)
    pid = os.fork()
    if pid == 0:
        # They're surely 1000, not 0!
        print('uid: ', os.getuid(), 'euid: ', os.geteuid())
        open('/etc/sudoers').close()
        print('open succeeded in child.')
        exit()
    else:
        print('child pid: ', pid)
        open('/etc/group-').close()
        print('parent succeeded to open.')

def workAround():
    """So, a dummy fork after seteuid is necessary?"""
    os.seteuid(1000)
    pid = os.fork()
    if pid == 0:
        exit(0)
    else:
        os.wait()

    open('/etc/group-').close()

## Run one of them.

# stillRoot()
# forkCase()
# workAround()
</code>```

答:
Manipulating process credentials on Unix systems is tricky. I highly recommend gaining a thorough understanding of how the Real, Effective, and Saved-Set user ids are interrelated. It's very easy to screw up "dropping privileges".

As to your specific observations... I'm wondering if there's a simple cause you may have overlooked. Your code is preforming a inconsistent tests and you've neglected to specify the exact file permissions on your /etc/sudoers and /etc/group- files. Your could would be expected to behave exactly as you describe if /etc/sudoers has permissions mode=440, uid=root, gid=root (which are the default permissions on my system) and if /etc/group- has mode=400.

You're not modifying the process's GID so if /etc/sudoers is group-readable, that would explain why it's always readable. fork() does not modify process credentials. However, it could appear to do so in your example code since you're checking different files in the parent and child. If /etc/group- does not have group read permissions where /etc/sudoers does, that would explain the apparent problem.

If all you're trying to do is "drop privileges", use the following code:

```<code>os.setgid( NEW_GID )
os.setuid( NEW_UID )
</code>```

Generally speaking, you'll only want to manipulate the effective user id if your process needs to toggle it's root permissions on and off over the life of the process. If you just need to do some setup operations with root permissions but will no longer require them after those setup operations are complete, just use the code above to irrevokably drop them.

Oh, and a useful debugging utility for process credential manipulation on Linux is to print the output of /proc/self/status, the Uid and Gid lines of this file display the real, effective, saved-set, and file ids held by the current process (in that order). The Python APIs can be used to retrieve the same information but you can consider the contents of this file as "truth data" and avoid any potential complications from Python's cross-platform APIs.

Body:
Root priv can't be dropped in python even after seteuid. A bug?

EDIT Summary: I forgot to drop gid. The accepted answer may help you, though.

Hi. I can't drop the root privilege in python 3.2 on my linux. In fact, even after seteuid(1000), it can read root-owned 400-mode files. The euid is surely set to 1000!

I found after empty os.fork() call, the privileged access is correctly denied. (But it's only in the parent. The child can still read illegitimately.) Is it a bug in python, or is linux so?

Try the code below. Comment out one of the three lines at the bottom, and run as root.

Thanks beforehand.

#!/usr/bin/python3

# Python seteuid pitfall example.
# Run this __as__ the root.

# Here, access to root-owned files /etc/sudoers and /etc/group- are tried.
# Simple access to them *succeeds* even after seteuid(1000) which should fail.

# Three functions, stillRoot(), forkCase() and workAround() are defined.
# The first two seem wrong. In the last one, access fails, as desired.

# ***Comment out*** one of three lines at the bottom before execution.

# If your python is < 3.2, comment out the entire def of forkCase()

import os

def stillRoot():
    """Open succeeds, but it should fail."""
    os.seteuid(1000)
    open('/etc/sudoers').close()

def forkCase():
    """Child can still open it. Wow."""
    # setresuid needs python 3.2
    os.setresuid(1000, 1000, 0)
    pid = os.fork()
    if pid == 0:
        # They're surely 1000, not 0!
        print('uid: ', os.getuid(), 'euid: ', os.geteuid())
        open('/etc/sudoers').close()
        print('open succeeded in child.')
        exit()
    else:
        print('child pid: ', pid)
        open('/etc/group-').close()
        print('parent succeeded to open.')

def workAround():
    """So, a dummy fork after seteuid is necessary?"""
    os.seteuid(1000)
    pid = os.fork()
    if pid == 0:
        exit(0)
    else:
        os.wait()

    open('/etc/group-').close()

## Run one of them.

# stillRoot()
# forkCase()
# workAround()

Body:
Manipulating process credentials on Unix systems is tricky. I highly recommend gaining a thorough understanding of how the Real, Effective, and Saved-Set user ids are interrelated. It's very easy to screw up "dropping privileges".

As to your specific observations... I'm wondering if there's a simple cause you may have overlooked. Your code is preforming a inconsistent tests and you've neglected to specify the exact file permissions on your /etc/sudoers and /etc/group- files. Your could would be expected to behave exactly as you describe if /etc/sudoers has permissions mode=440, uid=root, gid=root (which are the default permissions on my system) and if /etc/group- has mode=400.

You're not modifying the process's GID so if /etc/sudoers is group-readable, that would explain why it's always readable. fork() does not modify process credentials. However, it could appear to do so in your example code since you're checking different files in the parent and child. If /etc/group- does not have group read permissions where /etc/sudoers does, that would explain the apparent problem.

If all you're trying to do is "drop privileges", use the following code:

os.setgid( NEW_GID )
os.setuid( NEW_UID )

Generally speaking, you'll only want to manipulate the effective user id if your process needs to toggle it's root permissions on and off over the life of the process. If you just need to do some setup operations with root permissions but will no longer require them after those setup operations are complete, just use the code above to irrevokably drop them.

Oh, and a useful debugging utility for process credential manipulation on Linux is to print the output of /proc/self/status, the Uid and Gid lines of this file display the real, effective, saved-set, and file ids held by the current process (in that order). The Python APIs can be used to retrieve the same information but you can consider the contents of this file as "truth data" and avoid any potential complications from Python's cross-platform APIs.


来源: stackexchange

问:
changing the index according to click
I'm trying to make an image play each time i click it, i have two songs and two images at the moment.
every time i click an image only one of the songs play because the index is 0 right now.
I want a different song to play according to the image i'm clicking (i might add more pictures in the future so i was looking for a solution that doesn't involve changing the JS).
is there anything i can write in the index (instead of 0) that would change according to the image i'm clicking?

HTML:

```<code><section id="imgsound">
<div class="imageCircle">
    <div id="bird">
        <img id="birdImg" class="circle" src="images/bird.jpg">
        <audio id="birdAudio" class="audio"><source src="sounds/bird.mp3" type="audio/mpeg"></audio>
    </div>
</div>
<div class="imageCircle">
    <div id="stream">
        <img id="streamImg" class="circle" src="images/stream.jpg">
        <audio id="birdAudio" class="audio"><source src="sounds/stream.mp3" type="audio/mpeg">   </audio>
    </div>
</div>
</code>```

JS:

```<code>var audio;
function playAudio(){
    if (audio == false){
        $(this).css({"transform":"rotate(-360deg)"});
        $(".audio")[0].play();
        audio = true;
    }else{
        $(this).css({"transform":"rotate(360deg)"});
        $(".audio")[0].pause();
        audio = false;
    }
}
$(".imageCircle").click(playAudio);
</code>```

答:
You need to look for the audio element relative to the clicked image, rather than searching for it via a global selector. We can do this with something like siblings(), filtering on audio elements only.

We can also truncate and simplify the code.

```<code>let audio;
function playAudio() {
    $(this).css({"transform":"rotate("+(!audio ? -360 : 360)+"deg)"});
    $(this).siblings('audio')[!audio ? 'play' : 'pause']();
    audio = !audio;
}
$(".imageCircle").click(playAudio);
</code>```

If you're not confident that the audio element would always be a sibling of the img element, you could go up to the .imageCircle ancestor and look within that.

```<code>    $(this).closest('.imageCircle').find('audio')[!audio ? 'play' : 'pause']();
</code>```

ContentLicense: CC BY-SA 4.0

Title: changing the index according to click

Body:
I'm trying to make an image play each time i click it, i have two songs and two images at the moment.
every time i click an image only one of the songs play because the index is 0 right now.
I want a different song to play according to the image i'm clicking (i might add more pictures in the future so i was looking for a solution that doesn't involve changing the JS).
is there anything i can write in the index (instead of 0) that would change according to the image i'm clicking?

HTML:

        <audio id="birdAudio" class="audio"><source src="sounds/bird.mp3" type="audio/mpeg"></audio>

        <audio id="birdAudio" class="audio"><source src="sounds/stream.mp3" type="audio/mpeg">   </audio>

JS:

var audio;
function playAudio(){
    if (audio == false){
        $(this).css({"transform":"rotate(-360deg)"});
        $(".audio")[0].play();
        audio = true;
    }else{
        $(this).css({"transform":"rotate(360deg)"});
        $(".audio")[0].pause();
        audio = false;
    }
}
$(".imageCircle").click(playAudio);

Body:
You need to look for the audio element relative to the clicked image, rather than searching for it via a global selector. We can do this with something like siblings(), filtering on audio elements only.

We can also truncate and simplify the code.

let audio;
function playAudio() {
    $(this).css({"transform":"rotate("+(!audio ? -360 : 360)+"deg)"});
    $(this).siblings('audio')[!audio ? 'play' : 'pause']();
    audio = !audio;
}
$(".imageCircle").click(playAudio);

If you're not confident that the audio element would always be a sibling of the img element, you could go up to the .imageCircle ancestor and look within that.

    $(this).closest('.imageCircle').find('audio')[!audio ? 'play' : 'pause']();


问:
How to change TextInput cursor position in React Native?
I am trying to achieve this behaviour in React Native: The user type for example 5 then ".000" will be added automatically to the TextInput , but the user can add an other number for example 7, the final result should look like "57.000".

I tried to find a workaround but calculating the length of value and add chars accordingly but it didn't work as expected.

Then I found the selection props of the TextInput.

Here is my take on this:

I added this to state

```<code>selection: {
  start: 0,
  end: 0
}
</code>```

Here is my TextInput

```<code><TextInput
        onFocus={setSelection}
        selection={selection}
        keyboardType="numeric"
        onChangeText={(text) => onChangeText("val", text)}
        value={val}
        editable={true}
        selectTextOnFocus={false}
 />
</code>```

Here is onChangeText method

```<code>onChangeText = async (key, value) => {
  var numDots = value;
  if (value.indexOf(".000") === -1) {
    numDots = value + ".000"
  }
  this.setState({ [key]: numDots });
};
</code>```

And here is the setSelection method

```<code>setSelection = () => {
   this.setState({ select: { start: 1, end: 1 } });
};
</code>```

The problem is whenever I type, the cursor is always focusing on index 0, I think setSelection is not being triggered.

Is there something I'm doing wrong?

I hope someone would help me in this. Thanx in advance.

答: I ended up changing the onFocus prop by onSelectionChange and it's working now.

Body:
I am trying to achieve this behaviour in React Native: The user type for example 5 then ".000" will be added automatically to the TextInput , but the user can add an other number for example 7, the final result should look like "57.000".

I tried to find a workaround but calculating the length of value and add chars accordingly but it didn't work as expected.

Then I found the selection props of the TextInput.

Here is my take on this:

I added this to state

selection: {
  start: 0,
  end: 0
}

Here is my TextInput

<TextInput
        onFocus={setSelection}
        selection={selection}
        keyboardType="numeric"
        onChangeText={(text) => onChangeText("val", text)}
        value={val}
        editable={true}
        selectTextOnFocus={false}
 />

Here is onChangeText method

onChangeText = async (key, value) => {
  var numDots = value;
  if (value.indexOf(".000") === -1) {
    numDots = value + ".000"
  }
  this.setState({ [key]: numDots });
};

And here is the setSelection method

setSelection = () => {
   this.setState({ select: { start: 1, end: 1 } });
};

The problem is whenever I type, the cursor is always focusing on index 0, I think setSelection is not being triggered.

Is there something I'm doing wrong?

I hope someone would help me in this. Thanx in advance.


问:
Converting Spark UDF written in SCALA to JAVA
Below is my spark UD, can anyone help me to convert this into java?</p>

```<code>val customUDF = udf((array: Seq[String]) => {
    val newts = array.filter(_.nonEmpty)
    if  (newts.size == 0) null
    else newts.head
})
</code>```

答:
You can do it in two ways

Inline using Lambda i.e. Scala style

Or you can define a method and register it.

```<code>import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.api.java.UDF0;
import org.apache.spark.sql.api.java.UDF1;
import org.apache.spark.sql.types.DataTypes;

import java.util.List;

public class SimpleUDF {

    public static void main(String[] args) {

        SparkSession spark = SparkSession.builder().master("local[*]").getOrCreate();
        spark.sqlContext()
                .udf()
                .register("sampleUDFLambda", (List<String> array) -> array.stream().filter(element ->
                        !element.isEmpty()).findFirst().orElse(null), DataTypes.StringType);

    }

    //Or you can define a function

    private UDF1< List<String>,String> sampleUdf()
    {
        return ( array ) -> array.stream().filter(element ->
                !element.isEmpty()).findFirst().orElse(null);
    }

}

</code>```

Body:
Below is my spark UD, can anyone help me to convert this into java?

val customUDF = udf((array: Seq[String]) => {
    val newts = array.filter(_.nonEmpty)
    if  (newts.size == 0) null
    else newts.head
})

Body:
You can do it in two ways

Inline using Lambda i.e. Scala style

Or you can define a method and register it.

import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.api.java.UDF0;
import org.apache.spark.sql.api.java.UDF1;
import org.apache.spark.sql.types.DataTypes;

import java.util.List;

public class SimpleUDF {

    public static void main(String[] args) {

        SparkSession spark = SparkSession.builder().master("local[*]").getOrCreate();
        spark.sqlContext()
                .udf()
                .register("sampleUDFLambda", (List<String> array) -> array.stream().filter(element ->
                        !element.isEmpty()).findFirst().orElse(null), DataTypes.StringType);

    }

    //Or you can define a function

    private UDF1< List<String>,String> sampleUdf()
    {
        return ( array ) -> array.stream().filter(element ->
                !element.isEmpty()).findFirst().orElse(null);
    }

}


问:
Padding elements of a fixed width
I'm creating an adaptable row of images that will break on to another row if needed when there are too many images for the size. At the moment there's 4 in a row on desktop and 2 in a row on mobile.

All of the images are set to 25% or 50% in width. I want to have them spaced out slightly and evenly.

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="100%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="100%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="100%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="100%">
  </div>

</div></code>```

This works fine and all of the images are touching. I feel like some space would look better visually. Is the best approach to pad the width of the main container? I've tried making the images smaller, like this;

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="95%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="95%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="95%">
  </div>

  <div class="image-container">
    <img src="https://via.placeholder.com/500x500" width="95%">
  </div>

</div></code>```

Which looks fine on desktop but the bottom of the images still touches the top of the ones below them. Doing something like this:

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
.image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.image-padding {
  padding: 5px
}

.image {
  width: 100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

</div></code>```

Works fine for padding also but runs into the issue that they don't then stack on mobile. I feel like I'm close but I'm not sure how to get this to work.

EDIT

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.image-padding {
  padding: 5px
}

.image {
  width: 100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

  <div class="image-container">
    <div class="image-padding">
      <img class="image" src="https://via.placeholder.com/500x500">
    </div>
  </div>

</div>

<style>

</style></code>```

答:
Your code can really be simplified, you don't need all those containers. By keeping it simple, it will also be clearer to identify problems.

.images-row {
    width: 100%;
    margin-bottom: 15px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    flex-wrap: wrap;
}

img {
    width: calc(25% - 10px);
}

@media only screen and (max-device-width: 500px) {
    img {
        width: calc(50% - 10px);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="images-row">
      <img class="image" src="https://via.placeholder.com/500x500">
      <img class="image" src="https://via.placeholder.com/500x500">
      <img class="image" src="https://via.placeholder.com/500x500">
      <img class="image" src="https://via.placeholder.com/500x500">
</div></code>```

For mobile, the problem may come from @media only screen and (max-device-width: 500px): there are some more adapted to detect mobile, @media (orientation: portrait) for instance.

Title: Padding elements of a fixed width

Body:
I'm creating an adaptable row of images that will break on to another row if needed when there are too many images for the size. At the moment there's 4 in a row on desktop and 2 in a row on mobile.

All of the images are set to 25% or 50% in width. I want to have them spaced out slightly and evenly.

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

This works fine and all of the images are touching. I feel like some space would look better visually. Is the best approach to pad the width of the main container? I've tried making the images smaller, like this;

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

Which looks fine on desktop but the bottom of the images still touches the top of the ones below them. Doing something like this:

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media only screen and (max-device-width: 500px) {
.image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.image-padding {
  padding: 5px
}

.image {
  width: 100%
}

Works fine for padding also but runs into the issue that they don't then stack on mobile. I feel like I'm close but I'm not sure how to get this to work.

EDIT

.images-row {
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  text-align: center;
  justify-content: center;
  justify-content: space-evenly;
}

.image-container {
  width: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

@media only screen and (max-device-width: 500px) {
  .image-container {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.image-padding {
  padding: 5px
}

.image {
  width: 100%
}

Body:
Your code can really be simplified, you don't need all those containers. By keeping it simple, it will also be clearer to identify problems.

.images-row {
    width: 100%;
    margin-bottom: 15px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    flex-wrap: wrap;
}

img {
    width: calc(25% - 10px);
}

@media only screen and (max-device-width: 500px) {
    img {
        width: calc(50% - 10px);
    }
}

<div class="images-row">
      <img class="image" src="https://via.placeholder.com/500x500">
      <img class="image" src="https://via.placeholder.com/500x500">
      <img class="image" src="https://via.placeholder.com/500x500">
      <img class="image" src="https://via.placeholder.com/500x500">
</div>

For mobile, the problem may come from @media only screen and (max-device-width: 500px): there are some more adapted to detect mobile, @media (orientation: portrait) for instance.


问:
Cache library not loading
I have got an error while loading cache library in codeigniter(2.1.3).
What it is saying is this:

An Error Was Encountered

Unable to load the requested class: cache

My Code Looks like this

```<code>if (!$data['foo'] = $this->cache->file->get('details')) {
        $data['foo'] = $this->foo->getdetails();
        $this->cache->file->save('details', $data['foo'], 600);
    }
</code>```

My autoload file is like this:

```<code>$autoload['libraries'] = array('database','form_validation','session','driver','cache');
</code>```

答:
you can actually do this </p>

```<code>$autoload['drivers'] = array('cache');
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cache library not loading

Body:
I have got an error while loading cache library in codeigniter(2.1.3).
What it is saying is this:

An Error Was Encountered

Unable to load the requested class: cache

My Code Looks like this

if (!$data['foo'] = $this->cache->file->get('details')) {
        $data['foo'] = $this->foo->getdetails();
        $this->cache->file->save('details', $data['foo'], 600);
    }

My autoload file is like this:

$autoload['libraries'] = array('database','form_validation','session','driver','cache');

Body:
you can actually do this

$autoload['drivers'] = array('cache');


问:
symfony unit tests: add/modify form action
I have a form, without action (is submitted with javascript) and I'm trying to write a unit test for it, but it fails because "action" attribute is missing:

InvalidArgumentException : Current URI must be an absolute URL ("").

There is a way to do add it in unit tests or modify the html content using the crawler?

```<code><form id="form_search_page">
    <input type="text" name="keyword" value="" />
    <button type="submit" name="searchBtn" id="searchBtn">Search</button>
</form>

$client = $this->makeClient(true);
$url = $this->createRoute("page_index"));
$crawler = $client->request('GET', $url);
$response = $client->getResponse();

$form = $crawler->filter('#form_search_page')->form();
$params = array(
    "form[text]" => "dummy title"
);
$form->setValues($params);
$crawler = $client->submit($form);
$response = $client->getResponse();
$this->assertGreaterThan(0, $crawler->filter('.pages li')->count());
</code>```

答:
Here is the easiest way:

        $client = static::createClient();

        $crawler = $client->request('GET', '/contacts');

        $buttonCrawlerNode = $crawler->selectButton('submit');

        // Select the form that contains this button
        $form = $buttonCrawlerNode->form();

        // Modify the attribute action
        $form->getNode(0)->setAttribute('action', 'new-action-url');

        ...
```

Body:
I have a form, without action (is submitted with javascript) and I'm trying to write a unit test for it, but it fails because "action" attribute is missing:

InvalidArgumentException : Current URI must be an absolute URL ("").

There is a way to do add it in unit tests or modify the html content using the crawler?

<form id="form_search_page">
    <input type="text" name="keyword" value="" />
    <button type="submit" name="searchBtn" id="searchBtn">Search</button>
</form>

$client = $this->makeClient(true);
$url = $this->createRoute("page_index"));
$crawler = $client->request('GET', $url);
$response = $client->getResponse();

$form = $crawler->filter('#form_search_page')->form();
$params = array(
    "form[text]" => "dummy title"
);
$form->setValues($params);
$crawler = $client->submit($form);
$response = $client->getResponse();
$this->assertGreaterThan(0, $crawler->filter('.pages li')->count());


问:
Program doesn't stop running even though executor was shutdown and futures cancelled
I've made a small code for practising with Executors and Threads. It consists of the following:

Create a fixed-thread pool of size 3 with an infinite queue.

Submit 3 tasks with infinite loop (while(true)) to the pool (then
all threads are occupied)

Submit a 4th task, which is going to be waiting in the queue.

executor.shutdown() and doing a println for seeing how make active task and task count do i have.

setting the flag to false in order to stop the infinite while and then doing a
println for seeing how make active task and task count do i have

cancelling all futures with mayInterruptIfRunning=true and then
doing a println for seeing how make active task and task count do i
have

This is the code:

```<code>public class Main {

private static ThreadPoolExecutor fixexThreadPool;

public static void main(String[] args) throws InterruptedException {
    System.out.println("Creating fixed thread pool of size 3 and infinite queue.");
    fixexThreadPool = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
    final Boolean[] flag = new Boolean[1];
    flag[0] = true;
    List<Future> futures = new ArrayList<>();

    System.out.println("Submiting 3 threads");
    for (int i = 0; i < 3; i++) {
        futures.add(fixexThreadPool.submit(() -> {
            int a = 1;
            while (flag[0]) {
                a++;
            }
            System.out.println("Finishing thread execution.");
        }));
    }
    System.out.println("Done submiting 3 threads.");
    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));
    Thread.sleep(3000L);
    System.out.println("Submitting a 4th thread.");

    futures.add(fixexThreadPool.submit(() -> {
        int a = 1;
        while (flag[0]) {
            a++;
        }
        System.out.println("Finishing thread execution");
    }));

    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));

    System.out.println("Executor shutdown");
    fixexThreadPool.shutdown();
    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));
    Thread.sleep(2000L);
    System.out.println("Setting flag to false.");
    flag[0] = false;
    Thread.sleep(2000L);
    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));
    System.out.println("Cancelling all futures.");
    futures.forEach(f -> f.cancel(true));
    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));
}
</code>```

}

This is the output of the execution:

Creating fixed thread pool of size 3 and infinite queue.

Submiting 3 threads

Done submiting 3 threads.

Active count: 3 | Completed task count: 0 | task count: 3

Submitting a 4th thread.

Active count: 3 | Completed task count: 0 | task count: 4

Executor shutdown

Active count: 3 | Completed task count: 0 | task count: 4

Setting flag to false.

Active count: 3 | Completed task count: 0 | task count: 4

Cancelling all futures.

Active count: 3 | Completed task count: 0 | task count: 4

There are a couple of things i don't understand.

Why, after shutting down executor, there still are active threads ?

Why, after changing the flag to false in order to break the infinite loop, the infinite while doesn't break ?

Why, after cancelling every future, there is are active threads ?

No matter if a change the flag to false, shutdown executor or even cancelling all futures, my program doesn't stop running. Why is that?

Thanks in advance!!

答:
Why, after shutting down executor, there still are active threads?

By invoking shutdown, we request a normal shutdown. The thread pool stops accepting new tasks but waits for the already submitted tasks to complete - running or queued. So the shutdown method doesn't try to stop the threads. And conceptually, the ExecutorService implementations separate the task submission from the task execution. In other words, we own the tasks but not the threads.

Why, after changing the flag to false in order to break the infinite
  loop, the infinite while doesn't break?

We're using a cancellation flag here. But according to the Java memory model, for multiple threads to see the changes made to the shared data - flag - we must either employ synchronization or use the volatile keyword. So while synchronization provides both mutual exclusion and memory visibility, the volatile keyword just provides the memory visibility. Since only the main thread modifies the flag variable here, defining flag as a static volatile variable will make it work as expected.

```<code>public class Main {

    private static ThreadPoolExecutor fixexThreadPool;
    private static volatile Boolean[] flag = new Boolean[1];
    // the main method
}
</code>```

Why, after canceling every future, there is are active threads ?

ThreadPoolExecutor uses the FutureTask class as the Future implementation by default. And FutureTask cancels by interrupting the worker thread. So one can expect thread interruption to stop the task and even terminate the thread. But thread interruption is a cooperative mechanism. Firstly the task must be responsive to interrupts. It must check the interruption flag with Thread.isInterrupted and exit if possible. Secondly, the thread owner, in our case the thread pool, must check the interruption status and act accordingly. In this example, the task isn't responsive to interrupts. It uses a flag to cancel its operation. So let's continue with the thread owner. ThreadPoolExecutor doesn't act on the interruption status, so it doesn't terminate the thread.

No matter if a change the flag to false, shutdown executor or even
  canceling all futures, my program doesn't stop running. Why is that?

As mentioned above, the current task uses the cancellation flag approach. So using the volatile keyword must solve the problem. Then the tasks will stop as intended. Cancellation, on the other hand, won't have any effect on the current task. Because it isn't checking the interruption status. We can make it responsive like this:

```<code>while (flag[0] && !Thread.currentThread().isInterrupted())
</code>```

This way, the task also supports the cancellation by a thread interrupt.

Body:
I've made a small code for practising with Executors and Threads. It consists of the following:

Create a fixed-thread pool of size 3 with an infinite queue.

Submit 3 tasks with infinite loop (while(true)) to the pool (then
all threads are occupied)

Submit a 4th task, which is going to be waiting in the queue.

executor.shutdown() and doing a println for seeing how make active task and task count do i have.

setting the flag to false in order to stop the infinite while and then doing a
println for seeing how make active task and task count do i have

cancelling all futures with mayInterruptIfRunning=true and then
doing a println for seeing how make active task and task count do i
have

This is the code:

public class Main {

private static ThreadPoolExecutor fixexThreadPool;

public static void main(String[] args) throws InterruptedException {
    System.out.println("Creating fixed thread pool of size 3 and infinite queue.");
    fixexThreadPool = new ThreadPoolExecutor(3, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
    final Boolean[] flag = new Boolean[1];
    flag[0] = true;
    List<Future> futures = new ArrayList<>();

    System.out.println("Submiting 3 threads");
    for (int i = 0; i < 3; i++) {
        futures.add(fixexThreadPool.submit(() -> {
            int a = 1;
            while (flag[0]) {
                a++;
            }
            System.out.println("Finishing thread execution.");
        }));
    }
    System.out.println("Done submiting 3 threads.");
    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));
    Thread.sleep(3000L);
    System.out.println("Submitting a 4th thread.");

    futures.add(fixexThreadPool.submit(() -> {
        int a = 1;
        while (flag[0]) {
            a++;
        }
        System.out.println("Finishing thread execution");
    }));

    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));

    System.out.println("Executor shutdown");
    fixexThreadPool.shutdown();
    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));
    Thread.sleep(2000L);
    System.out.println("Setting flag to false.");
    flag[0] = false;
    Thread.sleep(2000L);
    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));
    System.out.println("Cancelling all futures.");
    futures.forEach(f -> f.cancel(true));
    System.out.println(String.format("Active count: %s | Completed task count: %s | task count: %s", fixexThreadPool.getActiveCount(), fixexThreadPool.getCompletedTaskCount(), fixexThreadPool.getTaskCount()));
}

}

This is the output of the execution:

Creating fixed thread pool of size 3 and infinite queue.

Submiting 3 threads

Done submiting 3 threads.

Active count: 3 | Completed task count: 0 | task count: 3

Submitting a 4th thread.

Active count: 3 | Completed task count: 0 | task count: 4

Executor shutdown

Active count: 3 | Completed task count: 0 | task count: 4

Setting flag to false.

Active count: 3 | Completed task count: 0 | task count: 4

Cancelling all futures.

Active count: 3 | Completed task count: 0 | task count: 4

There are a couple of things i don't understand.

Why, after shutting down executor, there still are active threads ?

Why, after changing the flag to false in order to break the infinite loop, the infinite while doesn't break ?

Why, after cancelling every future, there is are active threads ?

No matter if a change the flag to false, shutdown executor or even cancelling all futures, my program doesn't stop running. Why is that?

Thanks in advance!!

Body:
Why, after shutting down executor, there still are active threads?

By invoking shutdown, we request a normal shutdown. The thread pool stops accepting new tasks but waits for the already submitted tasks to complete - running or queued. So the shutdown method doesn't try to stop the threads. And conceptually, the ExecutorService implementations separate the task submission from the task execution. In other words, we own the tasks but not the threads.

Why, after changing the flag to false in order to break the infinite
  loop, the infinite while doesn't break?

We're using a cancellation flag here. But according to the Java memory model, for multiple threads to see the changes made to the shared data - flag - we must either employ synchronization or use the volatile keyword. So while synchronization provides both mutual exclusion and memory visibility, the volatile keyword just provides the memory visibility. Since only the main thread modifies the flag variable here, defining flag as a static volatile variable will make it work as expected.

public class Main {

    private static ThreadPoolExecutor fixexThreadPool;
    private static volatile Boolean[] flag = new Boolean[1];
    // the main method
}

Why, after canceling every future, there is are active threads ?

ThreadPoolExecutor uses the FutureTask class as the Future implementation by default. And FutureTask cancels by interrupting the worker thread. So one can expect thread interruption to stop the task and even terminate the thread. But thread interruption is a cooperative mechanism. Firstly the task must be responsive to interrupts. It must check the interruption flag with Thread.isInterrupted and exit if possible. Secondly, the thread owner, in our case the thread pool, must check the interruption status and act accordingly. In this example, the task isn't responsive to interrupts. It uses a flag to cancel its operation. So let's continue with the thread owner. ThreadPoolExecutor doesn't act on the interruption status, so it doesn't terminate the thread.

No matter if a change the flag to false, shutdown executor or even
  canceling all futures, my program doesn't stop running. Why is that?

As mentioned above, the current task uses the cancellation flag approach. So using the volatile keyword must solve the problem. Then the tasks will stop as intended. Cancellation, on the other hand, won't have any effect on the current task. Because it isn't checking the interruption status. We can make it responsive like this:

while (flag[0] && !Thread.currentThread().isInterrupted())

This way, the task also supports the cancellation by a thread interrupt.


问:
Reducing size of sharethis.com reaction buttons
I recently figured out sharethis.com offers free reaction buttons that can be embedded into any site. The size of the reaction buttons is too large. Good for blog posts but not good for discussion forums as there are too many replies/posts in each topic. I embedded the buttons into my forum. I want to reduce the size of the buttons from 45x45 to 16x16. I tried modifying CSS but unfortunately, it doesn't help. Is there anybody who can help to reduce the size of the reaction emojis? I'd really appreciate the help.

I tried looking for the support of sharethis.com. But there is no support/ticket/contact system there.

This is the code I'm using:

Javascript

```<code>    <script type="text/javascript" src="https://platform-api.sharethis.com/js/sharethis.js#property=5ed622e4c2a2080012eb58e8&product=inline-reaction-buttons" async="async"></script>`
</code>```

HTML

```<code><div class="sharethis-inline-reaction-buttons" stlye="font-size: 10px;"></div>
</code>```

I tried adding CSS modifying the button's class.

```<code>.st-btn {
font-size: 16px;
line-height: 16px;
}
</code>```

Also tried

```<code>.st-btn {
height: 16px;
width: 16px;
}
</code>```

But it's having no effect. Any solution to this will be appreciated.

You can test it out at my website testing website in case you need to inspect the element and modifying CSS. http://tvpsite.ml/forum/index.php?topic=1

答:
Just found how the size can be reduced via CSS.

.st-btn > svg {
    height: 20px !important;
    width: 20px !important;
}
```

Above code does the job of changing size of a reaction emoji.

Body:
I recently figured out sharethis.com offers free reaction buttons that can be embedded into any site. The size of the reaction buttons is too large. Good for blog posts but not good for discussion forums as there are too many replies/posts in each topic. I embedded the buttons into my forum. I want to reduce the size of the buttons from 45x45 to 16x16. I tried modifying CSS but unfortunately, it doesn't help. Is there anybody who can help to reduce the size of the reaction emojis? I'd really appreciate the help.

I tried looking for the support of sharethis.com. But there is no support/ticket/contact system there.

This is the code I'm using:

Javascript

    `

HTML

I tried adding CSS modifying the button's class.

.st-btn {
font-size: 16px;
line-height: 16px;
}

Also tried

.st-btn {
height: 16px;
width: 16px;
}

But it's having no effect. Any solution to this will be appreciated.

You can test it out at my website testing website in case you need to inspect the element and modifying CSS. http://tvpsite.ml/forum/index.php?topic=1

Body:
Just found how the size can be reduced via CSS.

.st-btn > svg {
    height: 20px !important;
    width: 20px !important;
}

Above code does the job of changing size of a reaction emoji.


问:
Is it possible to `continue` a foreach loop while in a for loop?
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

```<code>public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}
</code>```

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.

答:
You can do this by breaking the internal loop, this means the internal loop will be escaped as if the iterations ended. After this, you can use a boolean to control with continue if the rest of the underlying logic processes:</p>

```<code>    public static string Function(String s)
    {
        int error = 0;
        foreach (char c in s)
        {
            bool skip = false;

            for (int i = 97; i <= 109; i++)
            {
                if ('a' == (char)i)
                {
                    skip = true;
                    break;
                }
            }

            if (skip) continue;
            error++;
        }
        string length = Convert.ToString(s.Length);
        return error + "/" + length;
    }
</code>```

Body:
Okay, so what I want to do should sound pretty simple. I have a method that checks every character in a string if it's a letter from a to m. I now have to continue a foreach loop, while in a for loop. Is there a possible way to do what I want to do?

public static string Function(String s)
{
    int error = 0;
    foreach (char c in s)
    {
        for (int i = 97; i <= 109; i++)
        {
            if (c == (char)i)
            {
                // Here immediately continue the upper foreach loop, not the for loop
                continue;
            }
        }
        error++;
    }

    int length = s.Length;
    return error + "/" + length;
}

If there's a character that's not in the range of  a to m, there should be 1 added to error. In the end, the function should return the number of errors and the number of total characters in the string, f.E: "3/17".

Edit

What I wanted to achieve is not possible. There are workarounds, demonstrated in BsdDaemon's answer, by using a temporary variable.

The other answers fix my issue directly, by simply improving my code.

Body:
You can do this by breaking the internal loop, this means the internal loop will be escaped as if the iterations ended. After this, you can use a boolean to control with continue if the rest of the underlying logic processes:

    public static string Function(String s)
    {
        int error = 0;
        foreach (char c in s)
        {
            bool skip = false;

            for (int i = 97; i <= 109; i++)
            {
                if ('a' == (char)i)
                {
                    skip = true;
                    break;
                }
            }

            if (skip) continue;
            error++;
        }
        string length = Convert.ToString(s.Length);
        return error + "/" + length;
    }


问:
Does ReactTags work with React 16.12 applications?
I wanted to use ReactTags with my React 16.12 application following the instructions here -- https://www.npmjs.com/package/react-tag-input .  I installed react-dnd 11.1.1 .  Below is my package.json file

```<code>{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.4.1",
    "jquery": "^1.9.1",
    "react": "^16.12.0",
    "react-bootstrap": "^1.0.0-beta.17",
    "react-device-detect": "^1.12.1",
    "react-dnd": "^11.1.1",
    "react-dnd-html5-backend": "^11.1.1",
    "react-dom": "^16.12.0",
    "react-hamburger-menu": "^1.2.1",
    "react-native-flash-message": "^0.1.15",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.3.1",
    "react-tag-input": "^6.4.3",
    "typescript": "^3.8.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "NODE_ENV=development react-scripts build",
    "build:prod": "NODE_ENV=production react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "proxy": "http://localhost:8000",
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

I'm trying to implement the tags like so

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { WithContext as ReactTags } from 'react-tag-input';

const KeyCodes = {
  comma: 188,
  enter: 13,
};

const delimiters = [KeyCodes.comma, KeyCodes.enter];

class CoopTypes extends React.Component {
    constructor(props) {
        super(props);

        const tags = props.values.map(result => (
            {
                id: result.id,
                text: result.name
            }));
        this.state = {
            tags: tags,
            suggestions: props.values.map(result => ({
                id: result.id,
                text: result.name
            }))
        };
        this.handleDelete = props.handleDelete;
        this.handleAddition = props.handleAddition;
        this.handleDrag = this.handleDrag.bind(this);
    }

    handleDelete(i) {
        const { tags } = this.state;
        this.setState({
         tags: tags.filter((tag, index) => index !== i),
        });
    }

    handleAddition(tag) {
        this.setState(state => ({ tags: [...state.tags, tag] }));
    }

    handleDrag(tag, currPos, newPos) {
        const tags = [...this.state.tags];
        const newTags = tags.slice();

        newTags.splice(currPos, 1);
        newTags.splice(newPos, 0, tag);

        // re-render
        this.setState({ tags: newTags });
    }

    render() {
        const { tags, suggestions } = this.state;
        return (
            <div>
                <ReactTags tags={tags}
                    suggestions={suggestions}
                    handleDelete={this.handleDelete}
                    handleAddition={this.handleAddition}
                    handleDrag={this.handleDrag}
                    delimiters={delimiters} />
            </div>
        )
    }
};

export default CoopTypes;
</code>```

but I'm running into the below error when I start up my app

```<code>TypeError: (0 , _reactDnd.DragDropContext) is not a function
./node_modules/react-tag-input/dist-modules/components/ReactTags.js
node_modules/react-tag-input/dist-modules/components/ReactTags.js:538
  535 | };
  536 |
  537 | module.exports = {
> 538 |   WithContext: (0, _reactDnd.DragDropContext)(_reactDndHtml5Backend2.default)(ReactTags),
  539 |   WithOutContext: ReactTags,
  540 |   KEYS: _constants.KEYS
  541 | };
View compiled
</code>```

Any thoughts on how to address this?  Maybe the component doesn't work anymore with newer React versions?

答:
react-tag-input using DragDropContext from react-dnd which is deprecated in v8 of react-dnd and hence you need to use a lower version on react-dnd in your App to make it work

You can install v7.6.2 of react-dnd and react-dnd-html5-backend

```<code>"react-dnd": "^7.6.2",
"react-dnd-html5-backend": "^7.6.2",
</code>```

Working Demo

Body:
I wanted to use ReactTags with my React 16.12 application following the instructions here -- https://www.npmjs.com/package/react-tag-input .  I installed react-dnd 11.1.1 .  Below is my package.json file

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.4.1",
    "jquery": "^1.9.1",
    "react": "^16.12.0",
    "react-bootstrap": "^1.0.0-beta.17",
    "react-device-detect": "^1.12.1",
    "react-dnd": "^11.1.1",
    "react-dnd-html5-backend": "^11.1.1",
    "react-dom": "^16.12.0",
    "react-hamburger-menu": "^1.2.1",
    "react-native-flash-message": "^0.1.15",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.3.1",
    "react-tag-input": "^6.4.3",
    "typescript": "^3.8.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "NODE_ENV=development react-scripts build",
    "build:prod": "NODE_ENV=production react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "proxy": "http://localhost:8000",
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I'm trying to implement the tags like so

import React from 'react';
import ReactDOM from 'react-dom';
import { WithContext as ReactTags } from 'react-tag-input';

const KeyCodes = {
  comma: 188,
  enter: 13,
};

const delimiters = [KeyCodes.comma, KeyCodes.enter];

class CoopTypes extends React.Component {
    constructor(props) {
        super(props);

        const tags = props.values.map(result => (
            {
                id: result.id,
                text: result.name
            }));
        this.state = {
            tags: tags,
            suggestions: props.values.map(result => ({
                id: result.id,
                text: result.name
            }))
        };
        this.handleDelete = props.handleDelete;
        this.handleAddition = props.handleAddition;
        this.handleDrag = this.handleDrag.bind(this);
    }

    handleDelete(i) {
        const { tags } = this.state;
        this.setState({
         tags: tags.filter((tag, index) => index !== i),
        });
    }

    handleAddition(tag) {
        this.setState(state => ({ tags: [...state.tags, tag] }));
    }

    handleDrag(tag, currPos, newPos) {
        const tags = [...this.state.tags];
        const newTags = tags.slice();

        newTags.splice(currPos, 1);
        newTags.splice(newPos, 0, tag);

        // re-render
        this.setState({ tags: newTags });
    }

    render() {
        const { tags, suggestions } = this.state;
        return (

                <ReactTags tags={tags}
                    suggestions={suggestions}
                    handleDelete={this.handleDelete}
                    handleAddition={this.handleAddition}
                    handleDrag={this.handleDrag}
                    delimiters={delimiters} />

        )
    }
};

export default CoopTypes;

but I'm running into the below error when I start up my app

TypeError: (0 , _reactDnd.DragDropContext) is not a function
./node_modules/react-tag-input/dist-modules/components/ReactTags.js
node_modules/react-tag-input/dist-modules/components/ReactTags.js:538
  535 | };
  536 |
  537 | module.exports = {
> 538 |   WithContext: (0, _reactDnd.DragDropContext)(_reactDndHtml5Backend2.default)(ReactTags),
  539 |   WithOutContext: ReactTags,
  540 |   KEYS: _constants.KEYS
  541 | };
View compiled

Any thoughts on how to address this?  Maybe the component doesn't work anymore with newer React versions?

Body:
react-tag-input using DragDropContext from react-dnd which is deprecated in v8 of react-dnd and hence you need to use a lower version on react-dnd in your App to make it work

You can install v7.6.2 of react-dnd and react-dnd-html5-backend

"react-dnd": "^7.6.2",
"react-dnd-html5-backend": "^7.6.2",

Working Demo


问:
divide sum by count using postgresql
I am trying to divide sum by count but I get syntax error</p>

```<code>    COALESCE(SUM(f_revenue),0)/COUNT(DISTINCT(CASE WHEN b_entry_das_tag = true THEN s_dedup_hash ` +
  `ELSE NULL END))::decimal
</code>```

答:
The code in your question seems incomplete, but to do a partial count, it's usually easier to use the filter() operator:

```<code>COALESCE(SUM(f_revenue),0)
/
(COUNT(DISTINCT s_dedup_hash) filter (where b_entry_das_tag = true))::decimal
</code>```

Title: divide sum by count using postgresql

Body:
I am trying to divide sum by count but I get syntax error

    COALESCE(SUM(f_revenue),0)/COUNT(DISTINCT(CASE WHEN b_entry_das_tag = true THEN s_dedup_hash ` +
  `ELSE NULL END))::decimal

Body:
The code in your question seems incomplete, but to do a partial count, it's usually easier to use the filter() operator:

COALESCE(SUM(f_revenue),0)
/
(COUNT(DISTINCT s_dedup_hash) filter (where b_entry_das_tag = true))::decimal


问:
During less than or equal to comparison what comparison is evaluated first?
When we have simple condition (a<=b), what is actually happening? Will it firstly compare a<b, and if it's false will compare a==b (a<b || a==b)?

答:
a <= b evaluates to true (1) if and only if a is less than or equal to b. In typical C implementations, this determination is performed via a single machine instruction. If, for some reason, multiple instructions are needed, the C standard does not specify any ordering for them, just that the result is correct.

If a and b are expressions beyond simple identifiers, the C standard does not specify any ordering for evaluation of them, their parts, or their side effects due to the <= operator, although there may be ordering constraints within the expressions.


问:
javascript merge to array with name
I am new in JS. It is a simple task but find it is hard to solve. I tried many methods includingconcat,push,$.merge
Here is an example

```<code>var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"
</code>```

I want to get a result like [a:"b", c:"d", e:"f", g:"h"],
Here is some method I have tried

a.concat(b)get []

a.push(b) get 1

$.merge(a,b) get [0:[e:"f", g:"h"],a:"b",c:"d"]

I don't know where to go, Please help

答:
You cant get an array with key-value pairs its an invalid syntax, but you can create an object. Just spread both of your objects into an single object:

var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"

let result = {...a,...b};

console.log(result);```

Title: javascript merge to array with name

Body:
I am new in JS. It is a simple task but find it is hard to solve. I tried many methods includingconcat,push,$.merge
Here is an example

var a=[]
var b=[]
a["a"]="b"
a["c"]="d"
b["e"]="f"
b["g"]="h"

I want to get a result like [a:"b", c:"d", e:"f", g:"h"],
Here is some method I have tried

a.concat(b)get []

a.push(b) get 1

$.merge(a,b) get [0:[e:"f", g:"h"],a:"b",c:"d"]

I don't know where to go, Please help


问:
Getting corresponding eNum key for the value passed
```<code>var StateValue = {
    Unknown: 0,
    AL: 1,
    AK: 2,
    AZ: 3,
    AR: 4,
    CA: 5,
    CO: 6,
    CT: 7,
    DE: 8,
},
</code>```

<p>Now i need to get the enumValues. </p>

```<code>function getKeyValue(stateVal) {
      For example 'AK'
    I need to get the corresponding value...
}
</code>```

答:
It is simply:

```<code>var val = StateValue[stateVal];
</code>```

You can access object properties with bracket notation.

I suggest to read MDC - Working with Objects.

Body:
var StateValue = {
    Unknown: 0,
    AL: 1,
    AK: 2,
    AZ: 3,
    AR: 4,
    CA: 5,
    CO: 6,
    CT: 7,
    DE: 8,
},

Now i need to get the enumValues.

function getKeyValue(stateVal) {
      For example 'AK'
    I need to get the corresponding value...
}

Body:
It is simply:

var val = StateValue[stateVal];

You can access object properties with bracket notation.

I suggest to read MDC - Working with Objects.


问:
How to open a port on google compute engine
On google compute engine, I can access a port on a server through 'localhost',  but I can not access the same port using IP address from the same server or from external client machines. I tried to create a new firewall rule on web console page, and can see it from Linux command, but port 8888 still can't be accessed</p>

```<code>$ gcloud compute firewall-rules list
NAME                    NETWORK  SRC_RANGES    RULES                         SRC_TAGS  TARGET_TAGS
allow8888               default  0.0.0.0/0     tcp:8888,udp:8888
default-allow-http      default  0.0.0.0/0     tcp:80                                  http-server
default-allow-https     default  0.0.0.0/0     tcp:443                                 https-server
</code>```

答:
Problem solved by changing local tcp server setting files from 'localhost' to '0.0.0.0'

goto etc/hosts and update your host entries it should work

Body:
On google compute engine, I can access a port on a server through 'localhost',  but I can not access the same port using IP address from the same server or from external client machines. I tried to create a new firewall rule on web console page, and can see it from Linux command, but port 8888 still can't be accessed

$ gcloud compute firewall-rules list
NAME                    NETWORK  SRC_RANGES    RULES                         SRC_TAGS  TARGET_TAGS
allow8888               default  0.0.0.0/0     tcp:8888,udp:8888
default-allow-http      default  0.0.0.0/0     tcp:80                                  http-server
default-allow-https     default  0.0.0.0/0     tcp:443                                 https-server


问:
how to set select value after redirecting in Laravel
I am new to Laravel and I was trying to set the value of select to the value returned from my controller. I cannot figure out why it won't change the value

show.blade.php

```<code><div class="container d-flex justify-content-center">
    <form action="{{ action('ReportController@show', ['id' => 'month']) }}" class="month-form" method="GET">
        <select name="month" id="month" class="custom-select form-input month-select">
            <option value="01">January</option>
            <option value="02">February</option>
            <option value="03">March</option>
            <option value="04">April</option>
            <option value="05">May</option>
            <option value="06">June</option>
            <option value="07">July</option>
            <option value="08">August</option>
            <option value="09">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
        </select>
        <button class="btn btn-secondary">Generate Report</button>
    </form>
</div>
</code>```

controller
function show ()

```<code>$month_number = request('month');
$month_name = date("M", mktime(0, 0, 0, $month_number, 1));
return view('reports.show', compact('month_number', 'month_name'));
</code>```

This is my form
When I click the generate button, it goes back to this page and the value would be the one I selected from before. So, if I select May then the generate button, the new page would be May within the select instead of the  default value.

edit: I also tried using jQuery but it would only make my form blank and not give it any value at all

```<code>$(document).ready(function(){
   var month = @json($month_name ?? '');
   $('#month').val(month);
});
</code>```

答:
If I understand your problem clearly, then I think you want something like this

```<code><div class="container d-flex justify-content-center">
<form action="{{ action('ReportController@show', ['id' => 'month']) }}" class="month-form" method="GET">
    <select name="month" id="month" class="custom-select form-input month-select">
        <option value="01" @isset($month_number) {{ $month_number == 01 ? 'selected' : '' }} @endisset>January</option>
        <option value="02" @isset($month_number) {{ $month_number == 02 ? 'selected' : '' }} @endisset>February</option>
        <option value="03" @isset($month_number) {{ $month_number == 03 ? 'selected' : '' }} @endisset>March</option>
        <option value="04" @isset($month_number) {{ $month_number == 04 ? 'selected' : '' }} @endisset>April</option>
        <option value="05" @isset($month_number) {{ $month_number == 05 ? 'selected' : '' }} @endisset>May</option>
        <option value="06" @isset($month_number) {{ $month_number == 06 ? 'selected' : '' }} @endisset>June</option>
        <option value="07" @isset($month_number) {{ $month_number == 07 ? 'selected' : '' }} @endisset>July</option>
        <option value="08" @isset($month_number) {{ $month_number == 08 ? 'selected' : '' }} @endisset>August</option>
        <option value="09" @isset($month_number) {{ $month_number == 09 ? 'selected' : '' }} @endisset>September</option>
        <option value="10" @isset($month_number) {{ $month_number == 10 ? 'selected' : '' }} @endisset>October</option>
        <option value="11" @isset($month_number) {{ $month_number == 11 ? 'selected' : '' }} @endisset>November</option>
        <option value="12" @isset($month_number) {{ $month_number == 12 ? 'selected' : '' }} @endisset>December</option>
    </select>
    <button class="btn btn-secondary">Generate Report</button>
</form>
</code>```

If it doesn't work then try to change 01 to "01" and so on...

Body:
I am new to Laravel and I was trying to set the value of select to the value returned from my controller. I cannot figure out why it won't change the value

show.blade.php

    <form action="{{ action('ReportController@show', ['id' => 'month']) }}" class="month-form" method="GET">
        <select name="month" id="month" class="custom-select form-input month-select">
            <option value="01">January</option>
            <option value="02">February</option>
            <option value="03">March</option>
            <option value="04">April</option>
            <option value="05">May</option>
            <option value="06">June</option>
            <option value="07">July</option>
            <option value="08">August</option>
            <option value="09">September</option>
            <option value="10">October</option>
            <option value="11">November</option>
            <option value="12">December</option>
        </select>
        <button class="btn btn-secondary">Generate Report</button>
    </form>

controller
function show ()

$month_number = request('month');
$month_name = date("M", mktime(0, 0, 0, $month_number, 1));
return view('reports.show', compact('month_number', 'month_name'));

This is my form
When I click the generate button, it goes back to this page and the value would be the one I selected from before. So, if I select May then the generate button, the new page would be May within the select instead of the  default value.

edit: I also tried using jQuery but it would only make my form blank and not give it any value at all

$(document).ready(function(){
   var month = @json($month_name ?? '');
   $('#month').val(month);
});

Body:
If I understand your problem clearly, then I think you want something like this

<div class="container d-flex justify-content-center">
<form action="{{ action('ReportController@show', ['id' => 'month']) }}" class="month-form" method="GET">
    <select name="month" id="month" class="custom-select form-input month-select">
        <option value="01" @isset($month_number) {{ $month_number == 01 ? 'selected' : '' }} @endisset>January</option>
        <option value="02" @isset($month_number) {{ $month_number == 02 ? 'selected' : '' }} @endisset>February</option>
        <option value="03" @isset($month_number) {{ $month_number == 03 ? 'selected' : '' }} @endisset>March</option>
        <option value="04" @isset($month_number) {{ $month_number == 04 ? 'selected' : '' }} @endisset>April</option>
        <option value="05" @isset($month_number) {{ $month_number == 05 ? 'selected' : '' }} @endisset>May</option>
        <option value="06" @isset($month_number) {{ $month_number == 06 ? 'selected' : '' }} @endisset>June</option>
        <option value="07" @isset($month_number) {{ $month_number == 07 ? 'selected' : '' }} @endisset>July</option>
        <option value="08" @isset($month_number) {{ $month_number == 08 ? 'selected' : '' }} @endisset>August</option>
        <option value="09" @isset($month_number) {{ $month_number == 09 ? 'selected' : '' }} @endisset>September</option>
        <option value="10" @isset($month_number) {{ $month_number == 10 ? 'selected' : '' }} @endisset>October</option>
        <option value="11" @isset($month_number) {{ $month_number == 11 ? 'selected' : '' }} @endisset>November</option>
        <option value="12" @isset($month_number) {{ $month_number == 12 ? 'selected' : '' }} @endisset>December</option>
    </select>
    <button class="btn btn-secondary">Generate Report</button>
</form>

If it doesn't work then try to change 01 to "01" and so on...


问:
Show message when radio button selected
I am trying to get the following to work without much success

```<code>$(document).ready(function()
{
    $('#shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a').click(function()
    {
        alert("Please ensure you have selected the correct option");
    });
});
</script>
</code>```

Using inspect on Chrome, I looked for the ID for the radio button and found shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a but even so, when I save the javascript and load the page and click the radio button, no message is displayed.

The code I used to find the ID in inspect was as follows:

```<code><input name="shippingOptionIds.5ed62ea40135a" class="form-checklist-checkbox optimizedCheckout-form-checklist-checkbox" id="shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a" type="radio" value="7dac01c2c834210be865275f0700a45a">
</code>```

答:
you have to add an event (type input not click) to the radio and then add condition if the input.checked === true then show message

// select radio input
const input = document.getElementById('input');

// add event on input
input.addEventListener('input', () => {
    if (input.checked) {
        alert('this is a message!');
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="input"></code>```

Title: Show message when radio button selected

Body:
I am trying to get the following to work without much success

$(document).ready(function()
{
    $('#shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a').click(function()
    {
        alert("Please ensure you have selected the correct option");
    });
});
</script>

Using inspect on Chrome, I looked for the ID for the radio button and found shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a but even so, when I save the javascript and load the page and click the radio button, no message is displayed.

The code I used to find the ID in inspect was as follows:

<input name="shippingOptionIds.5ed62ea40135a" class="form-checklist-checkbox optimizedCheckout-form-checklist-checkbox" id="shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a" type="radio" value="7dac01c2c834210be865275f0700a45a">

Body:
you have to add an event (type input not click) to the radio and then add condition if the input.checked === true then show message

// select radio input
const input = document.getElementById('input');

// add event on input
input.addEventListener('input', () => {
    if (input.checked) {
        alert('this is a message!');
    }
});

<input type="radio" id="input">


问:
Ocaml: Is using the wildcard more efficient than using a variable in a pattern matching?
When using pattern matching with Ocaml, I sometimes hesitate to use the wildcard (_) and instead use a variable that I can name for clarity. I was wondering if it's (although slightly I presume) less efficient than using it, because using the wildcard the compiler knows the value won't be reachable, and no pointer is created.

Consider the three functions below:

No 1

let compare = function
        [], [] -> true
         |h::t, h2::t2 when h > h2 -> compare t t2
         |h::t, h2::t2 -> false

```

<p>No 2</p>

<pre class="lang-ml prettyprint-override"><code>let compare = function
        [], [] -> true
         |h::t, h2::t2 when h > h2 -> compare t t2
         |_::_, _::_ -> false
</code>```

No 3

let compare = function
        [], [] -> true
         |h::t, h2::t2 when h > h2 -> compare t t2
         |_ -> false
```

No3 should be faster, but is 2faster and/or use less memory than the first one?
I dogged into the caml documentation and couldn't find information on the wildcard implementation.

答:
The compiler does not really care whether unused variables appear in patterns or not. However, it does care which branches are present and their order.

For example, your first two examples use non-exhaustive pattern matching, so the compilers will add some extra branches that raise an exception at runtime. Obviously, these branches increase the size of the executable.

Even if your pattern matching is exhaustive, there might still be a difference. In your third example, your catch-all branch causes the compiler to create all the underlying cases and to make them jump to this common code. If you had explicitly written all the branches, then each case would have been responsible to returning its own result.

So, depending on whether the compiler decides to perform jump/epilogue threading and block tail merging, your code might be more or less large, more or less fast. That said, there should be no difference on the memory consumption. But even that is not guaranteed, because code changes might in turn cause the inlining heuristics to diverge, and thus increase or decrease optimization opportunities.

To summarize, short of looking at the generated assembly code, it is hard to predict the decisions of the compiler, even on such simple functions.

Body:
When using pattern matching with Ocaml, I sometimes hesitate to use the wildcard (_) and instead use a variable that I can name for clarity. I was wondering if it's (although slightly I presume) less efficient than using it, because using the wildcard the compiler knows the value won't be reachable, and no pointer is created.

Consider the three functions below:

No 1

let compare = function
        [], [] -> true
         |h::t, h2::t2 when h > h2 -> compare t t2
         |h::t, h2::t2 -> false

No 2

let compare = function
        [], [] -> true
         |h::t, h2::t2 when h > h2 -> compare t t2
         |_::_, _::_ -> false

No 3

let compare = function
        [], [] -> true
         |h::t, h2::t2 when h > h2 -> compare t t2
         |_ -> false

No3 should be faster, but is 2faster and/or use less memory than the first one?
I dogged into the caml documentation and couldn't find information on the wildcard implementation.


问:
Classification using categorical input data and image input data
I have a tiny dataset of around 300 rows. Each row has:
Column A: An image,
Column B: Categorical text input,
Column C: Categorical text input,
Column D: Categorical text output

I am able to use a sequential Keras model on the image input data alone (Column A) to predict the output (Column D), but the accuracy is pretty abysmal (around 40%). How can I combine the image data with the categorical input data(s) to obtain better accuracy?

Following is the code I'm using. I get the error on model.fit:
ValueError: could not convert string to float: 'item1'

There are no numbers in the data I am using, everything is categorical text. I think there is something I need to change in the models for the 'y' so it knows that the prediction is to be categorical and not numeric. I'm not sure what to change though.

```<code>drive.mount('/content/gdrive/')
train = pd.read_csv(r'gdrive/My Drive/Colab Notebooks/Fast AI/testfilled.csv')
df = pd.DataFrame(train)
df = df[['Column A', 'Column B', 'Column C', 'Column D']]

def process_categorical_attributes(df, train, test):
  zipBinarizer = LabelBinarizer().fit(df["Column B"])
  trainCategorical = zipBinarizer.transform(train["Column B"])
  testCategorical = zipBinarizer.transform(test["Column B"])

  zipBinarizer2 = LabelBinarizer().fit(df["Column C"])
  trainCategorical2 = zipBinarizer.transform(train["Column C"])
  testCategorical2 = zipBinarizer.transform(test["Column C"])

  trainX = np.hstack([trainCategorical, trainCategorical2])
  testX = np.hstack([testCategorical, testCategorical2])
  return (trainX, testX)

def load_piece_images(df):
  train_image = []
  for i in tqdm(range(train.shape[0])):
    img = image.load_img('gdrive/My Drive/Colab Notebooks/OutputDir/' + train['FileName'][i] + '.bmp',target_size=(400,400,3))
    img = image.img_to_array(img)
    img = img/255
    train_image.append(img)
  return np.array(train_image)

def create_mlp(dim, regress=False):
  model = Sequential()
  model.add(Dense(8, input_dim=dim, activation="relu"))
  model.add(Dense(4, activation="relu"))
  if regress:
    model.add(Dense(1, activation="linear"))
  return model

def create_cnn(width, height, depth, filters=(16, 32, 64), regress=False):
    inputShape = (height, width, depth)
    chanDim = -1
    inputs = Input(shape=inputShape)
    for (i, f) in enumerate(filters):
        if i == 0:
            x = inputs
        x = Conv2D(f, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(2, 2))(x)
    x = Flatten()(x)
    x = Dense(16)(x)
    x = Activation("relu")(x)
    x = BatchNormalization(axis=chanDim)(x)
    x = Dropout(0.5)(x)
    x = Dense(4)(x)
    x = Activation("relu")(x)
    if regress:
        x = Dense(1, activation="linear")(x)
    model = Model(inputs, x)
    return model

images = load_piece_images(df)
split = train_test_split(df, images, test_size=0.25, random_state=42)
(trainAttrX, testAttrX, trainImagesX, testImagesX) = split

trainY = trainAttrX["Column D"]
testY = testAttrX["Column D"]
(trainAttrX, testAttrX) = process_categorical_attributes(df, trainAttrX, testAttrX)

mlp = create_mlp(trainAttrX.shape[1], regress=False)
cnn = create_cnn(400, 400, 3, regress=False)
combinedInput = concatenate([mlp.output, cnn.output])
x = Dense(4, activation="relu")(combinedInput)
x = Dense(1, activation="linear")(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(inputs=[mlp.input, cnn.input], outputs=x)

opt = Adam(lr=1e-3, decay=1e-3 / 200)
model.compile(loss="mean_absolute_percentage_error", optimizer=opt)
model.fit(
    [trainAttrX, trainImagesX], trainY,
    validation_data=([testAttrX, testImagesX], testY),
    epochs=20, batch_size=2)
</code>```

答:
This tutorial does a great thing at explaining how to use multiple input sources (text + image data): https://www.pyimagesearch.com/2019/02/04/keras-multiple-inputs-and-mixed-data/

Essentially this is exactly what you are looking for.

Body:
I have a tiny dataset of around 300 rows. Each row has:
Column A: An image,
Column B: Categorical text input,
Column C: Categorical text input,
Column D: Categorical text output

I am able to use a sequential Keras model on the image input data alone (Column A) to predict the output (Column D), but the accuracy is pretty abysmal (around 40%). How can I combine the image data with the categorical input data(s) to obtain better accuracy?

Following is the code I'm using. I get the error on model.fit:
ValueError: could not convert string to float: 'item1'

There are no numbers in the data I am using, everything is categorical text. I think there is something I need to change in the models for the 'y' so it knows that the prediction is to be categorical and not numeric. I'm not sure what to change though.

drive.mount('/content/gdrive/')
train = pd.read_csv(r'gdrive/My Drive/Colab Notebooks/Fast AI/testfilled.csv')
df = pd.DataFrame(train)
df = df[['Column A', 'Column B', 'Column C', 'Column D']]

def process_categorical_attributes(df, train, test):
  zipBinarizer = LabelBinarizer().fit(df["Column B"])
  trainCategorical = zipBinarizer.transform(train["Column B"])
  testCategorical = zipBinarizer.transform(test["Column B"])

  zipBinarizer2 = LabelBinarizer().fit(df["Column C"])
  trainCategorical2 = zipBinarizer.transform(train["Column C"])
  testCategorical2 = zipBinarizer.transform(test["Column C"])

  trainX = np.hstack([trainCategorical, trainCategorical2])
  testX = np.hstack([testCategorical, testCategorical2])
  return (trainX, testX)

def load_piece_images(df):
  train_image = []
  for i in tqdm(range(train.shape[0])):
    img = image.load_img('gdrive/My Drive/Colab Notebooks/OutputDir/' + train['FileName'][i] + '.bmp',target_size=(400,400,3))
    img = image.img_to_array(img)
    img = img/255
    train_image.append(img)
  return np.array(train_image)

def create_mlp(dim, regress=False):
  model = Sequential()
  model.add(Dense(8, input_dim=dim, activation="relu"))
  model.add(Dense(4, activation="relu"))
  if regress:
    model.add(Dense(1, activation="linear"))
  return model

def create_cnn(width, height, depth, filters=(16, 32, 64), regress=False):
    inputShape = (height, width, depth)
    chanDim = -1
    inputs = Input(shape=inputShape)
    for (i, f) in enumerate(filters):
        if i == 0:
            x = inputs
        x = Conv2D(f, (3, 3), padding="same")(x)
        x = Activation("relu")(x)
        x = BatchNormalization(axis=chanDim)(x)
        x = MaxPooling2D(pool_size=(2, 2))(x)
    x = Flatten()(x)
    x = Dense(16)(x)
    x = Activation("relu")(x)
    x = BatchNormalization(axis=chanDim)(x)
    x = Dropout(0.5)(x)
    x = Dense(4)(x)
    x = Activation("relu")(x)
    if regress:
        x = Dense(1, activation="linear")(x)
    model = Model(inputs, x)
    return model

images = load_piece_images(df)
split = train_test_split(df, images, test_size=0.25, random_state=42)
(trainAttrX, testAttrX, trainImagesX, testImagesX) = split

trainY = trainAttrX["Column D"]
testY = testAttrX["Column D"]
(trainAttrX, testAttrX) = process_categorical_attributes(df, trainAttrX, testAttrX)

mlp = create_mlp(trainAttrX.shape[1], regress=False)
cnn = create_cnn(400, 400, 3, regress=False)
combinedInput = concatenate([mlp.output, cnn.output])
x = Dense(4, activation="relu")(combinedInput)
x = Dense(1, activation="linear")(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(inputs=[mlp.input, cnn.input], outputs=x)

opt = Adam(lr=1e-3, decay=1e-3 / 200)
model.compile(loss="mean_absolute_percentage_error", optimizer=opt)
model.fit(
    [trainAttrX, trainImagesX], trainY,
    validation_data=([testAttrX, testImagesX], testY),
    epochs=20, batch_size=2)


问:
Set up a scheduled job?
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically.

Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this.

Does anyone know how to set this up?

To clarify:  I know I can set up a cron job to do this, but I'm curious if there is some feature in Django that provides this functionality.   I'd like people to be able to deploy this app themselves without having to do much config (preferably zero).

I've considered triggering these actions "retroactively" by simply checking if a job should have been run since the last time a request was sent to the site, but I'm hoping for something a bit cleaner.

答:
Interesting new pluggable Django app: django-chronograph

You only have to add one cron entry which acts as a timer, and you have a very nice Django admin interface into the scripts to run.

OwnerDisplayName: TM

Title: Set up a scheduled job?

LastEditorDisplayName: TM

OwnerDisplayName: Van Gale


问:
Swift: UISearchController bug content behind navigation bar after pushing view controller
There is a very weird bug when I push a control to navigation controller and when I return back, look at the gif below.

Before push the detail view controller

After click on back button from detail view controller

My code:

```<code>searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = Localizations.searching
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.showsScopeBar = true

viewController.navigationItem.searchController = searchController
viewController.navigationItem.hidesSearchBarWhenScrolling = false
viewController.definesPresentationContext = true
</code>```

答:
Had the same Problem and found a feasible solution:

After you add the TableView to your ViewController, pinn all directions to the safeAreaLayout(or superview)

```<code>self.view.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
</code>```

And activate Extend Edges - Unter Opaque Bars

Body:
There is a very weird bug when I push a control to navigation controller and when I return back, look at the gif below.

Before push the detail view controller

After click on back button from detail view controller

My code:

searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = Localizations.searching
searchController.hidesNavigationBarDuringPresentation = false
searchController.searchBar.showsScopeBar = true

viewController.navigationItem.searchController = searchController
viewController.navigationItem.hidesSearchBarWhenScrolling = false
viewController.definesPresentationContext = true

Body:
Had the same Problem and found a feasible solution:

After you add the TableView to your ViewController, pinn all directions to the safeAreaLayout(or superview)

self.view.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true

And activate Extend Edges - Unter Opaque Bars


问:
Flink: Wrap executable non-flink jar to run it in a flink cluster
Assume that I have an executable jar file that doesn't have any flink code inside and my job is to make it distributed with flink. I have already done this once by creating and executing the StreamExecutionEnvironment somewhere in the code and placing the code of the jar that can be distributed inside flink operators (i.e., map functions).

Yesterday, I was asked to do a similar job but with minimal effort. They told me to find a way to wrap this flink-less jar in a way that it can be executed by a flink cluster (without injecting code and altering the jar like i did above). Is there a way to do this? The docs state that to support execution from a packaged jar "a program must use the environment obtained by StreamExecutionEnvironment.getExecutionEnvironment()". Is there no other way?

My only guess right now is to wrap the entry point of the jar. To place it inside flink operators but unfortunately I don't know that this jar does

答:
You could write a map only program and package it in jar. In the map, you execute the main through reflection of the provided jar.

Your small wrapper could be put into Flink lib to be reusable for other jars or you add the other jar in the distributed cache.

Btw, I haven't fully understood the use case or I find weird, since it's unclear to me how the parallelism is supposed to work. So sorry if the answer does not help.


问:
Opposite code behind in Flex
Why in Flex the code behind pattern is using the Actionscript class as a base class instead of using the MXML component for that?

I mean, instead of extending our AS3 code behind class, why we don't extend our MXML in a new AS3 class?

Using that approach seems more natural, because is a real extension, we are adding code and functionalities to our MXML base.

Using the code behind pattern is a hack to OOP, every time we add a component to our MXML we need to modify our AS3 class, that is, if we modify the child (MXML) we need to modify the parent (AS3) too.

What's wrong with the opposite code behind ("code in front"?) ?

答:
"Code in front" is a more natural extension and OOP design, because we are extending our MXML with functionalities in AS3 and we don't need to change our parent every time we change our child.

But it has a proble, we can't use binding in MXML because now our MXML is our base class and we have our vars/functions in the AS3 child class.

EDIT: another problem with code in front is that you can't see your "AS3 componente" in Design Mode (not tested in FB4+ maybe it's working now). For more about this read Marc Hughes's reply.

Title: Opposite code behind in Flex


问:
Why does this VBA code get a type mismatch error?
I have this VBA code that is supposed to check the equality of two strings, but for some reason, I am still getting a type mismatch error.

```<code>If CStr(pf.PivotItems(q).Name) = CStr(Sheets("Dev Purposes").Range("A" + i).Value)
</code>```

The PivotItems.Name is supposed to already be a string, and when I take out the CStr of that one it still gives me a type mismatch error. The Range.Value is supposed to yield a Variant, so that is why I added the CStr. The values are supposed to match exactly.

My issue was using the + instead of & for concat, thanks @BigBen

答: Not sure here, but very often in excel I add + 0 to quantities I want to compare to a number or add & "", adding a zero length string, to quantities I want to compare to text.  These operations are not the identity operation, they are conversion to the desired type.  Perhaps if you used the & "" after both of them?</p>

Body:
I have this VBA code that is supposed to check the equality of two strings, but for some reason, I am still getting a type mismatch error.

If CStr(pf.PivotItems(q).Name) = CStr(Sheets("Dev Purposes").Range("A" + i).Value)

The PivotItems.Name is supposed to already be a string, and when I take out the CStr of that one it still gives me a type mismatch error. The Range.Value is supposed to yield a Variant, so that is why I added the CStr. The values are supposed to match exactly.

My issue was using the + instead of & for concat, thanks @BigBen


问:
Calling a function periodically in C
I want to call a function which creates files periodically on every 5 seconds in C.
The function code is below which creates files.

```<code>void file_create(int time) {
        snprintf(filename, sizeof(filename),"%s_%d", "data", index);
        FILE *fp = fopen (filename, "w");
        index++;
}
</code>```

file name will be data_0, data_1, data_2 and goes on on every call.

how to call the above function periodically every 5 seconds from main function if i put an infinite loop like below

```<code>while(1){
    file_create();
    Sleep(5000);
}
</code>```

this is not allowing to execute the lines below the while loop.

How to achieve this by calling above function periodically without holding execution of rest of the program ?

答: You are looking for a multithread system. You have to create one task which executes the mentioned while loop and another one which executes the other parts of your current programm.</p>

Title: Calling a function periodically in C

Body:
I want to call a function which creates files periodically on every 5 seconds in C.
The function code is below which creates files.

void file_create(int time) {
        snprintf(filename, sizeof(filename),"%s_%d", "data", index);
        FILE *fp = fopen (filename, "w");
        index++;
}

file name will be data_0, data_1, data_2 and goes on on every call.

how to call the above function periodically every 5 seconds from main function if i put an infinite loop like below

while(1){
    file_create();
    Sleep(5000);
}

this is not allowing to execute the lines below the while loop.

How to achieve this by calling above function periodically without holding execution of rest of the program ?