问:
Pset4 (cs50) recover does not work properly. It compiles, but does not recover more than 2 jpegs. Is something wrong with checking for JPEG signature?
I am learning how to code and I have no experience with that at all. I've successful got to PSET4 and stuck on recover. I've read everything online about this problem and i found out that many people have similar code as I do and it works. Does not work for me whatsoever. Please have a look and give me a hint what did I do wrong and how to correct it.
Here is everything about the pset4 recover i downloaded their card.raw from here card.raw</p>

```<code>/** recovering JPEG files from a memory card
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef uint8_t BYTE;

int main(int argc, char* argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr,
            "Usage: ./recover infile (the name of a forensic image from which to recover JPEGs)\n");
        return 1;
    }

    // open input file (forensic image)
    FILE* inptr = fopen(argv[1], "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", argv[1]);
        return 2;
    }

    FILE* outptr = NULL;

    // create a pointer array of 512 elements to store 512 bytes from the memory card
    BYTE* buffer = malloc(sizeof(BYTE) * 512);
    if (buffer == NULL)
    {
        return 3;
    }

    // count amount of jpeg files found
    int jpeg = 0;

    // string for a file name using sprintf
    char filename[8] = { 0 };

    // read memory card untill the end of file
    while (fread(buffer, sizeof(BYTE) * 512, 1, inptr) != 0)
    {
        // check if jpeg is found
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
            && (buffer[3] >= 0xe0 || buffer[3] <= 0xef))
        {
            if (jpeg > 0)
            {
                fclose(outptr);
            }
            sprintf(filename, "%03d.JPEG", jpeg);
            outptr = fopen(filename, "w");
            jpeg++;
        }

        if (jpeg > 0)
        {
            fwrite(buffer, sizeof(BYTE) * 512, 1, outptr);
        }
    }

    // free memory
    free(buffer);

    // close filename
    fclose(outptr);

    // close input file (forensic image)
    fclose(inptr);

    return 0;
}
</code>```

答:
how do you know that an instance of a JPEG image will always end with '\n'?  Or better, how do you know that a JPEG image will be an exact multiple of 512?

You dont know.

So the posted code needs to calculate the actual value OR use some method to have the last call to fread() for any specific JPEG instance, to stop reading at the end of that image,

Then  the check for the ID bytes of the next JPEG image will find the next image.

Otherwise, the start of the next image is already written to the prior output file and the check for a new image will fail.

In general this will result in the last created file containing more than one image.

This link: 'https://en.wikipedia.org/wiki/JPEG_File_Interchange_Format' is a web page that describes the format of a JPEG file.

On every digital camera that I have used, the SD card has a directory of all the files.

Suggest using that directory and the info in the linked web page to find each JPEG image and to determine when the end of that image has been encountered. (I.E. the 0xFF 0xD9)

Body:
I am learning how to code and I have no experience with that at all. I've successful got to PSET4 and stuck on recover. I've read everything online about this problem and i found out that many people have similar code as I do and it works. Does not work for me whatsoever. Please have a look and give me a hint what did I do wrong and how to correct it.
Here is everything about the pset4 recover i downloaded their card.raw from here card.raw

/** recovering JPEG files from a memory card
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef uint8_t BYTE;

int main(int argc, char* argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        fprintf(stderr,
            "Usage: ./recover infile (the name of a forensic image from which to recover JPEGs)\n");
        return 1;
    }

    // open input file (forensic image)
    FILE* inptr = fopen(argv[1], "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", argv[1]);
        return 2;
    }

    FILE* outptr = NULL;

    // create a pointer array of 512 elements to store 512 bytes from the memory card
    BYTE* buffer = malloc(sizeof(BYTE) * 512);
    if (buffer == NULL)
    {
        return 3;
    }

    // count amount of jpeg files found
    int jpeg = 0;

    // string for a file name using sprintf
    char filename[8] = { 0 };

    // read memory card untill the end of file
    while (fread(buffer, sizeof(BYTE) * 512, 1, inptr) != 0)
    {
        // check if jpeg is found
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
            && (buffer[3] >= 0xe0 || buffer[3] <= 0xef))
        {
            if (jpeg > 0)
            {
                fclose(outptr);
            }
            sprintf(filename, "%03d.JPEG", jpeg);
            outptr = fopen(filename, "w");
            jpeg++;
        }

        if (jpeg > 0)
        {
            fwrite(buffer, sizeof(BYTE) * 512, 1, outptr);
        }
    }

    // free memory
    free(buffer);

    // close filename
    fclose(outptr);

    // close input file (forensic image)
    fclose(inptr);

    return 0;
}


来源: stackexchange

问:
How to retrieve products by tags (SQL question)
I have two MySQL tables:

product has id, title, price and some other product attributes

tag has *product_id* and *tag_name* fields

each product row can have one ore more rows in table tag joined by *product_id* field.
Question: how do I select products by *tag_name* and other attributes?
Example: I need to select all books cheaper than $10 and tagged 'foreign' and 'sci-fi'

I know how to select products with one tag (join product and tag by *product_id* and set where clause)
I know how to select products with more than one tag using a stored procedure, however queries take very long time to run.
Is there a way to avoid stored procedure and still get the result?

Update: StackOverflow does something like this when you click "Related Tags" on the right hand side bar. Now, I don't know what architechture their DB has, but the result is fairly quick selection of all questions tagged with multiple tags.

答:
This will return any product with price less than 10, and with tag foreign or sci-fi

How about something like

```<code>SELECT  p.*
FROM    product p
WHERE   p.price < 10
AND     EXISTS  (
                    SELECT  1
                    FROM    tag t
                    WHERE   p.id = t.product_id
                    AND     t.tag_name IN ('foreign','sci-fi')
                )
</code>```

This will ensure that it has both tags, assuming that tags has primary key product_id and tag_name

```<code>SELECT  p.*
FROM    product p
WHERE   p.price < 10
AND     EXISTS  (
                    SELECT  1
                    FROM    tag t
                    WHERE   p.id = t.product_id
                    AND     t.tag_name IN ('foreign','sci-fi')
                    HAVING COUNT(1) = 2
                )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This will return any product with price less than 10, and with tag foreign or sci-fi

How about something like

SELECT  p.*
FROM    product p
WHERE   p.price < 10
AND     EXISTS  (
                    SELECT  1
                    FROM    tag t
                    WHERE   p.id = t.product_id
                    AND     t.tag_name IN ('foreign','sci-fi')
                )

This will ensure that it has both tags, assuming that tags has primary key product_id and tag_name

SELECT  p.*
FROM    product p
WHERE   p.price < 10
AND     EXISTS  (
                    SELECT  1
                    FROM    tag t
                    WHERE   p.id = t.product_id
                    AND     t.tag_name IN ('foreign','sci-fi')
                    HAVING COUNT(1) = 2
                )


问:
NullPointerException despite specifying
I want to code a personal modloader for minecraft (create files , download files, sort files, etc) and the first window which is created is a JOptionPane which asks for a Version (i do not code in java really long, i don´t use spinner, just a "msg dialog" asking for a version). The code is:

```<code>public JOptionPane version = new JOptionPane();
public String modversion;

public Version()
{
    showVersion();
}

public static void main(String[] args)
{

}

public void showVersion()
{
    //input = version
    String vers = version.showInputDialog("Welche Version soll modifiziert werden?");

    if (vers.equals(null)) {
            return;
    } else {
        if(vers.equals("1.5.2") || vers.equals("1.6.2") || vers.equals("1.6.4") || vers.equals("1.7.2") || vers.equals("1.7.10") || vers.equals("1.8") || vers.equals("1.8.9") || vers.equals("1.9") || vers.equals("1.10.2") || vers.equals("1.11.2"))
        {

          //mod version is saved as String (title for the config list)

            modversion = vers;
            return;
        } else  {
           // with incompatible input the method will be repeated
            JOptionPane.showMessageDialog(null, "Diese Version wird leider nicht supportet");
            showVersion();
        }
    }
}
</code>```

If you just press "Ok", the input would equal "null":

```<code>if (vers.equals(null)) {
            return;
    }
</code>```

but it don´t quit the method, it says NullPointerException. Why doesn´t it just quit the method?

答:
It's correct that you get an exception here.
Here:

if (vers.equals(null)) {

You are trying to call a method on a variable that is null. As you said yourself, vers is null at this point.

To check for null you have to use the == operator.

```<code>if(vers == null) { return;}
</code>```

ContentLicense: CC BY-SA 3.0

Title: NullPointerException despite specifying

Body:
I want to code a personal modloader for minecraft (create files , download files, sort files, etc) and the first window which is created is a JOptionPane which asks for a Version (i do not code in java really long, i don´t use spinner, just a "msg dialog" asking for a version). The code is:

public JOptionPane version = new JOptionPane();
public String modversion;

public Version()
{
    showVersion();
}

public static void main(String[] args)
{

}

public void showVersion()
{
    //input = version
    String vers = version.showInputDialog("Welche Version soll modifiziert werden?");

    if (vers.equals(null)) {
            return;
    } else {
        if(vers.equals("1.5.2") || vers.equals("1.6.2") || vers.equals("1.6.4") || vers.equals("1.7.2") || vers.equals("1.7.10") || vers.equals("1.8") || vers.equals("1.8.9") || vers.equals("1.9") || vers.equals("1.10.2") || vers.equals("1.11.2"))
        {

          //mod version is saved as String (title for the config list)

            modversion = vers;
            return;
        } else  {
           // with incompatible input the method will be repeated
            JOptionPane.showMessageDialog(null, "Diese Version wird leider nicht supportet");
            showVersion();
        }
    }
}

If you just press "Ok", the input would equal "null":

if (vers.equals(null)) {
            return;
    }

but it don´t quit the method, it says NullPointerException. Why doesn´t it just quit the method?

Body:
It's correct that you get an exception here.
Here:

if (vers.equals(null)) {

You are trying to call a method on a variable that is null. As you said yourself, vers is null at this point.

To check for null you have to use the == operator.

if(vers == null) { return;}


问:
How to add up the numbers 1 through "n" and print out the result?
I have written the following code for an exercise I was given, nonetheless, when I try to submit it,  I get an incorrect answer for my code.

So this is my code:

```<code>def problem(n):
    my_sum = 0
    while my_sum < n:
        my_sum = n
        my_sum = my_sum + n
    print (my_sum)
</code>```

What they have asked me to code is the following: Write a function problem(n): that adds up the numbers 1 through n and
prints out the result.  You should use either a 'while' loop or a 'for' loop.
Be sure that you check your answer on several numbers n.

答:
You can try this:

```<code>def problem(n):

   print sum(xrange(1, n+1))
</code>```

If you are not allowed to use the built in sum function, you can try this:

```<code>def problem(n):

   counter = 0
   for i in range(1, n+1):
       counter += i

   print counter
</code>```

The top example uses a for loop in what is called list comprehension, which is a shorter way of utilizing the regular for loop.

Body:
I have written the following code for an exercise I was given, nonetheless, when I try to submit it,  I get an incorrect answer for my code.

So this is my code:

def problem(n):
    my_sum = 0
    while my_sum < n:
        my_sum = n
        my_sum = my_sum + n
    print (my_sum)

What they have asked me to code is the following: Write a function problem(n): that adds up the numbers 1 through n and
prints out the result.  You should use either a 'while' loop or a 'for' loop.
Be sure that you check your answer on several numbers n.

Body:
You can try this:

def problem(n):

   print sum(xrange(1, n+1))

If you are not allowed to use the built in sum function, you can try this:

def problem(n):

   counter = 0
   for i in range(1, n+1):
       counter += i

   print counter

The top example uses a for loop in what is called list comprehension, which is a shorter way of utilizing the regular for loop.


问:
Screeps - Property in Memory resets
I have a problem with Memory. It should to store all my data (not objects) but it resets from time to time.
This is example:

```<code>Memory.creeps_idx = 0;

module.exports.loop = function () {

    console.log("c_idx:", Memory.creeps_idx, Game.time);

    if(Memory.creeps_idx==0)
    {
        Memory.creeps_idx+=1;
    }
}
</code>```

And this is output from console.

```<code>[13:41:01]c_idx: 0 1115
[13:41:03]c_idx: 1 1116
[13:41:05]c_idx: 0 1117
[13:41:07]c_idx: 1 1118
[13:41:09]c_idx: 1 1119
[13:41:11]c_idx: 1 1120
[13:41:13]c_idx: 1 1121
[13:41:15]c_idx: 1 1122
[13:41:17]c_idx: 0 1123
[13:41:19]c_idx: 1 1124
[13:41:21]c_idx: 1 1125
[13:41:23]c_idx: 1 1126
[13:41:25]c_idx: 1 1127
</code>```

Can you tell me why creeps_idx changes value to 0? (This was tested in simulator)

答:
Basically, anything outside of module.exports.loop is run once every few ticks.  This is why creep_idx gets reset to in your original example, and why your solution works.

What is new here is the way you main module is executed. In the old-style architecture, it is executed every tick, and every module required from it is also executed every tick. In the new architecture, your main module should contain the module.exports.loop function which is executed in a game loop, while the rest of the main module contents are executed only after a new global is instantiated.

http://support.screeps.com/hc/en-us/articles/204825672-New-main-loop-architecture

Title: Screeps - Property in Memory resets

Body:
I have a problem with Memory. It should to store all my data (not objects) but it resets from time to time.
This is example:

Memory.creeps_idx = 0;

module.exports.loop = function () {

    console.log("c_idx:", Memory.creeps_idx, Game.time);

    if(Memory.creeps_idx==0)
    {
        Memory.creeps_idx+=1;
    }
}

And this is output from console.

[13:41:01]c_idx: 0 1115
[13:41:03]c_idx: 1 1116
[13:41:05]c_idx: 0 1117
[13:41:07]c_idx: 1 1118
[13:41:09]c_idx: 1 1119
[13:41:11]c_idx: 1 1120
[13:41:13]c_idx: 1 1121
[13:41:15]c_idx: 1 1122
[13:41:17]c_idx: 0 1123
[13:41:19]c_idx: 1 1124
[13:41:21]c_idx: 1 1125
[13:41:23]c_idx: 1 1126
[13:41:25]c_idx: 1 1127

Can you tell me why creeps_idx changes value to 0? (This was tested in simulator)


问:
Android Studio giving UnsatisfiedLinkError when loading a library that I've included in the project
I'm having troubles working out the dependencies for Jzy3d for my Android Studio project. The stack trace leading to the error is:

```<code>at java.lang.Runtime.loadLibrary(Runtime.java:367)
at java.lang.System.loadLibrary(System.java:1076)
at com.jogamp.common.jvm.JNILibLoaderBase.loadLibraryInternal(JNILibLoaderBase.java:454)
at com.jogamp.common.jvm.JNILibLoaderBase.access$000(JNILibLoaderBase.java:59)
at com.jogamp.common.jvm.JNILibLoaderBase$DefaultAction.loadLibrary(JNILibLoaderBase.java:90)
at com.jogamp.common.jvm.JNILibLoaderBase.loadLibrary(JNILibLoaderBase.java:328)
at com.jogamp.common.os.DynamicLibraryBundle$GlueJNILibLoader.loadLibrary(DynamicLibraryBundle.java:390)
at com.jogamp.common.os.Platform$2.run(Platform.java:249)
at java.security.AccessController.doPrivileged(AccessController.java:45)
at com.jogamp.common.os.Platform.loadGlueGenRTImpl(Platform.java:231)
at com.jogamp.common.os.Platform.<clinit>(Platform.java:183)
at com.jogamp.common.os.Platform.initSingleton(Platform.java:258)
at javax.media.opengl.GLProfile.<clinit>(GLProfile.java:99)
at javax.media.opengl.GLProfile.isAvailable(GLProfile.java:284)
at org.jzy3d.chart.Settings.<init>(Settings.java:19)
at org.jzy3d.chart.Settings.getInstance(Settings.java:48)
at org.jzy3d.chart.Chart.<init>(Chart.java:60)
at org.jzy3d.chart.Chart.<init>(Chart.java:48)
</code>```

While crawling through the stack trace, I found the following line in Platform.run:249

```<code>GlueJNILibLoader.loadLibrary("gluegen-rt", false, Platform.class.getClassLoader());
</code>```

So my best guess is that it's trying to load my gluegen-rt.jar, but for some reason is unable to find it.

I've included gluegen-rt in my libs directory

I also attempted to add libgluegen-rt.so to src/main/jniLibs and changed my .grade to include

```<code>compile fileTree(dir: 'libs', include: ['*.jar','*.so'])
</code>```

So basically my question is where is the error? Is it within the inability to load my gluegen-rt.jar, or it's inability to load libgluegen-rt.so? Is the issue caused from me missing a different library?

The code that starts the problem is calling the chart constructor from the Jzy3d libary

```<code>Chart chart = new Chart(Quality.Advanced);
</code>```

Down the line of method calls the following line is executed

```<code>GLProfile.isAvailable("GL2")
</code>```

The lines of code that are used within gluegen-rt are

```<code>protected static synchronized boolean loadLibrary(String var0, boolean var1, ClassLoader var2) {
    return loaderAction != null?loaderAction.loadLibrary(var0, var1, var2):false;
}
</code>```

答:
Follow the instructions in Android Studio: Add jar as a library?

You are missing these steps:

Put the Jzy3d jar into the libs folder.

Right click it and hit 'Add as library'

Add the following line in dependencies:

```<code>compile 'org.jogamp.gluegen:gluegen-rt-android:2.1.3'
</code>```

You can remove *.so from :

```<code>compile fileTree(dir: 'libs', include: ['*.jar','*.so'])
</code>```

Body:
I'm having troubles working out the dependencies for Jzy3d for my Android Studio project. The stack trace leading to the error is:

at java.lang.Runtime.loadLibrary(Runtime.java:367)
at java.lang.System.loadLibrary(System.java:1076)
at com.jogamp.common.jvm.JNILibLoaderBase.loadLibraryInternal(JNILibLoaderBase.java:454)
at com.jogamp.common.jvm.JNILibLoaderBase.access$000(JNILibLoaderBase.java:59)
at com.jogamp.common.jvm.JNILibLoaderBase$DefaultAction.loadLibrary(JNILibLoaderBase.java:90)
at com.jogamp.common.jvm.JNILibLoaderBase.loadLibrary(JNILibLoaderBase.java:328)
at com.jogamp.common.os.DynamicLibraryBundle$GlueJNILibLoader.loadLibrary(DynamicLibraryBundle.java:390)
at com.jogamp.common.os.Platform$2.run(Platform.java:249)
at java.security.AccessController.doPrivileged(AccessController.java:45)
at com.jogamp.common.os.Platform.loadGlueGenRTImpl(Platform.java:231)
at com.jogamp.common.os.Platform.<clinit>(Platform.java:183)
at com.jogamp.common.os.Platform.initSingleton(Platform.java:258)
at javax.media.opengl.GLProfile.<clinit>(GLProfile.java:99)
at javax.media.opengl.GLProfile.isAvailable(GLProfile.java:284)
at org.jzy3d.chart.Settings.<init>(Settings.java:19)
at org.jzy3d.chart.Settings.getInstance(Settings.java:48)
at org.jzy3d.chart.Chart.<init>(Chart.java:60)
at org.jzy3d.chart.Chart.<init>(Chart.java:48)

While crawling through the stack trace, I found the following line in Platform.run:249

GlueJNILibLoader.loadLibrary("gluegen-rt", false, Platform.class.getClassLoader());

So my best guess is that it's trying to load my gluegen-rt.jar, but for some reason is unable to find it.

I've included gluegen-rt in my libs directory

I also attempted to add libgluegen-rt.so to src/main/jniLibs and changed my .grade to include

compile fileTree(dir: 'libs', include: ['*.jar','*.so'])

So basically my question is where is the error? Is it within the inability to load my gluegen-rt.jar, or it's inability to load libgluegen-rt.so? Is the issue caused from me missing a different library?

The code that starts the problem is calling the chart constructor from the Jzy3d libary

Chart chart = new Chart(Quality.Advanced);

Down the line of method calls the following line is executed

GLProfile.isAvailable("GL2")

The lines of code that are used within gluegen-rt are

protected static synchronized boolean loadLibrary(String var0, boolean var1, ClassLoader var2) {
    return loaderAction != null?loaderAction.loadLibrary(var0, var1, var2):false;
}

Body:
Follow the instructions in Android Studio: Add jar as a library?

You are missing these steps:

Put the Jzy3d jar into the libs folder.

Right click it and hit 'Add as library'

Add the following line in dependencies:

compile 'org.jogamp.gluegen:gluegen-rt-android:2.1.3'

You can remove *.so from :

compile fileTree(dir: 'libs', include: ['*.jar','*.so'])


问:
Escape Apostrophe In JQuery .text()
How can I escape the apostrophe in this line of code?

Using ' will only print out ' and not '.

By The way I'm walking about the apostrophe in the We'd.

```<code>$('.ContText-3').text('To find out more about how Lister, Jeter & Lloyd, CPAs can help you grow your business, contact us. We'd be happy to sit down with you, learn about your business, and share how we can help.');
</code>```

答:
```<code>$('.ContText-3').text('To find out more about how Lister, Jeter & Lloyd, CPAs can help you grow your business, contact us. We\'d be happy to sit down with you, learn about your business, and share how we can help.');
</code>```

Title: Escape Apostrophe In JQuery .text()

Body:
How can I escape the apostrophe in this line of code?

Using ' will only print out ' and not '.

By The way I'm walking about the apostrophe in the We'd.

$('.ContText-3').text('To find out more about how Lister, Jeter & Lloyd, CPAs can help you grow your business, contact us. We'd be happy to sit down with you, learn about your business, and share how we can help.');


问:
Padding between Textview border and drawableLeft
This is my TextView layout:

As you can see, there is a padding between the border (the stroke) and the image inside the TextView, which is given using drawableLeft attribute.
I know I could use drawablePadding attribute to adjust the padding between the image and the text, but I want to remove the padding between the stroke and the image. Can I do something like that? And, possibily, from XML?

This is the TextView's layout:

```<code><TextView
            android:id="@+id/txtPlate2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableStart="@mipmap/ic_italian_plate"
            android:textColor="@color/black"
            android:textSize="40sp"
            android:text="text"
            android:textAlignment="center"
            android:paddingStart="0dp"
            android:paddingEnd="5dp"
            android:background="@drawable/plate_textview"/>
</code>```

and this is plate_textview drawable, where I simply add a stroke:

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

    <solid
        android:color="@android:color/white"/>

    <stroke
        android:width="2dip"
        android:color="@color/black"/>
</shape>
</code>```

Thanks in advance!

答:
The problem is your are using image from mipmap folder. mipmap is only used for launcher icons and its added extra padding and elevation when show on view.

Always keep resource icons in drawable folder and use it as
  @drawable/ic_italian_plate.

#. You can add padding and corners to custom drawable using <padding> and <corners>.

Update plate_textview.xml as below:

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

    <solid
        android:color="@android:color/white"/>

    <stroke
        android:width="2dp"
        android:color="@color/black"/>

    <padding
        android:top="2dp"
        android:bottom="2dp"
        android:left="2dp"
        android:right="8dp" />

    <corners
        android:radius="2dp" />
</shape>
</code>```

Update TextView as below:

```<code><TextView
    android:id="@+id/txtPlate2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:gravity="center"
    android:drawableStart="@drawable/ic_italian_plate"
    android:textColor="@color/black"
    android:textSize="40sp"
    android:text="I-123-4568"
    android:textAlignment="center"
    android:background="@drawable/plate_textview"/>
</code>```

OUTPUT:

Hope this will help~

Body:
This is my TextView layout:

As you can see, there is a padding between the border (the stroke) and the image inside the TextView, which is given using drawableLeft attribute.
I know I could use drawablePadding attribute to adjust the padding between the image and the text, but I want to remove the padding between the stroke and the image. Can I do something like that? And, possibily, from XML?

This is the TextView's layout:

<TextView
            android:id="@+id/txtPlate2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableStart="@mipmap/ic_italian_plate"
            android:textColor="@color/black"
            android:textSize="40sp"
            android:text="text"
            android:textAlignment="center"
            android:paddingStart="0dp"
            android:paddingEnd="5dp"
            android:background="@drawable/plate_textview"/>

and this is plate_textview drawable, where I simply add a stroke:

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

    <solid
        android:color="@android:color/white"/>

    <stroke
        android:width="2dip"
        android:color="@color/black"/>
</shape>

Thanks in advance!

Body:
The problem is your are using image from mipmap folder. mipmap is only used for launcher icons and its added extra padding and elevation when show on view.

Always keep resource icons in drawable folder and use it as
  @drawable/ic_italian_plate.

#. You can add padding and corners to custom drawable using <padding> and <corners>.

Update plate_textview.xml as below:

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

    <solid
        android:color="@android:color/white"/>

    <stroke
        android:width="2dp"
        android:color="@color/black"/>

    <padding
        android:top="2dp"
        android:bottom="2dp"
        android:left="2dp"
        android:right="8dp" />

    <corners
        android:radius="2dp" />
</shape>

Update TextView as below:

<TextView
    android:id="@+id/txtPlate2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:gravity="center"
    android:drawableStart="@drawable/ic_italian_plate"
    android:textColor="@color/black"
    android:textSize="40sp"
    android:text="I-123-4568"
    android:textAlignment="center"
    android:background="@drawable/plate_textview"/>

OUTPUT:

Hope this will help~


问:
How to create a Spark or TensorFlow cluster based on containers with mesos or kubernetes?
After reading the discussions about the differences between mesos and kubernetes and kubernetes-vs.-mesos-vs.-swarm, I am still confused about how to create a Spark and TensorFlow cluster with docker containers via some bear metal hosts and AWS like private cloud (OpenNebular).

Currently, I am able to build a static TensorFlow cluster with docker containers manually distributed to different hosts. I only run a stand alone spark on a bear metal host. The way of manually setup a mesos cluster for containers can be found here.

Since my resources are limited, I would like to find a way to deploy docker containers to the current mixed infrastructure to build either a tensorflow or spark cluster, so that I can do data analysis either with tensorflow or spark on the same resources.

Is it possible to create/run/undeploy a spark or tensorflow cluster quickly with docker containers on a mixed infrastructure with mesos or kubernetes? How can I do that?

Any comments and hints are welcome.

答:
Given you have limited resources, I suggest you have a look at using the Spark helm, which gives you:

1 x Spark Master with port 8080 exposed on an external LoadBalancer

3 x Spark Workers with HorizontalPodAutoscaler to scale to max 10 pods when CPU hits 50% of 100m

1 x Zeppelin with port 8080 exposed on an external LoadBalancer

If this configuration doesn't work then you can build your own docker images and deploy those, take a look at this blog series. There is work underway to make Spark more Kubernetes friendly. This issue also gives some insight.

Not looked into Tensorflow, I suggest you look at this blog


问:
How to go from one page to another page using javascript?
From an admin page if the user is valid then the browser should go to another page.

When a user enters his user name and password, then clicks the OK button then another page is displayed and the login page is automatically closed.

How can I do this with JavaScript?

答:
The correct solution that i get is

```<code><html>
      <head>
        <script type="text/javascript" language="JavaScript">
                  function clickedButton()
            {

                window.location = 'new url'

            }
             </script>
      </head>

      <form name="login_form" method="post">
            ..................
            <input type="button" value="Login" onClick="clickedButton()"/>
      </form>
 </html>
</code>```

Here the new url is given inside the single quote.

Body:
The correct solution that i get is

<html>
      <head>
        <script type="text/javascript" language="JavaScript">
                  function clickedButton()
            {

                window.location = 'new url'

            }
             </script>
      </head>

      <form name="login_form" method="post">
            ..................
            <input type="button" value="Login" onClick="clickedButton()"/>
      </form>
 </html>

Here the new url is given inside the single quote.


问:
Eclipse - debugger doesn't stop at breakpoint
I am trying to trouble shoot a JUnit. In the source code, I have set break point in two places: 1) in a line where a static member is initialized 2) the first line of one of the test cases.

The debugger stops in the static field initializing line. But it doesn't stop in the test case. No matter where I set the break point in the test case, the debugger doesn't stop there. I know for sure that the test case is executed as I can see the log messages that I have added appear in the log.

Any help would be greatly appreciated.

I am using Eclipse Galileo and JUnit4 launcher.

答:
In my case the problem was that I hadn't Debug view open in Debug perspective, so:

1 - Be sure you have debug perspective opened:

2 - Be sure you have debug view opened:


问:
How to reach scope from factory function in AngularJS
I have a ng-grid and its options are as following:

```<code>$scope.gridOptions = {
    enableRowSelection: true,
    enableSelectAll: true,
    selectionRowHeaderWidth: 35,
    rowHeight: 35,
    showGridFooter: false,
    enableColumnMenus: false,
    enableSorting: true,
    enableFiltering: true,
    columnDefs: [
        {
            name: "",
            field: "fake",
            cellTemplate: '<div class="ui-grid-cell-contents" >' +
            '<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.deleteRow($event)">Delete</button>' +
            '<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Edit</button>' +
            '<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.saveEdit($event)">Update</button>' +
            '<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.cancelEdit($event)">Cancel</button>' +
            '</div>',
            enableCellEdit: false,
            enableFiltering: false,
            enableSorting: false,
            showSortMenu: false,
            enableColumnMenu: false,
            width: "10%"
        },
        {
            name: 'Id',
            visible: false
        },
        {
            name: 'Key',
            enableCellEdit: true,
            cellTemplate: '<div class="ui-grid-cell-contents"><div ng-class="{\'viewr-dirty\' : row.inlineEdit.entity[col.field].isValueChanged }">{{row.entity[col.field]}}</div></div>',
            width: "30%"
        },

        {
            name: 'Value',
            enableCellEdit: true,
            cellTemplate: '<div class="ui-grid-cell-contents"><div ng-class="{\'viewr-dirty\' : row.inlineEdit.entity[col.field].isValueChanged }">{{row.entity[col.field]}}</div></div>',
            width: "30%"
        }

    ]
}
</code>```

I am using inline edit so there are buttons in cell. One of these buttons is delete. When I click this button, record is deleted from database. However I want the grid to be refreshed after deleting operation is finished. I call functions from factory:

```<code>angular.module('ui.grid').factory('InlineEdit', function ($interval, $rootScope, $mdDialog, LocalizationService, AlertDialogFactory) {
function inlineEdit(entity, index, grid) {
    this.grid = grid;
    this.index = index;
    this.entity = {};
    this.isEditModeOn = false;
    this.init(entity);
}

inlineEdit.prototype = {
    init: function (rawEntity) {
        var self = this;

        for (var prop in rawEntity) {
            self.entity[prop] = {
                value: rawEntity[prop],
                isValueChanged: false,
                isSave: false,
                isCancel: false,
                isEdit: false
            }
        }
    },

    deleteRow: function (event) {
        event && event.stopPropagation();
        var self = this;

        self.isEditModeOn = false;

        for (var prop in self.entity) {
            self.entity[prop].isSave = true;
            self.entity[prop].isEdit = false;
        }
        LocalizationService.deleteRow(self.grid.rows[self.index]).then(function (result) {
            if (result.data.IsOk) {
                // CODE HERE...
            }
            else {
                AlertDialogFactory.ShowAlertDialog(result.data.Message, "ERROR");
            }
        });
    },
}
    return inlineEdit;
})
</code>```

if result.data.IsOk is true, How can i refresh gridOptions.data from factory function? How can i reach to scope from factory?

答:
As a solution you can broadcast an event from $rootScope.
It will be like this:

```<code>$rootScope.$broadcast("rowDeleted");
</code>```

And handle that event in place where you have access to $scope.

```<code>$scope.$on("rowDeleted", deleteHandler);
</code>```

Body:
I have a ng-grid and its options are as following:

$scope.gridOptions = {
    enableRowSelection: true,
    enableSelectAll: true,
    selectionRowHeaderWidth: 35,
    rowHeight: 35,
    showGridFooter: false,
    enableColumnMenus: false,
    enableSorting: true,
    enableFiltering: true,
    columnDefs: [
        {
            name: "",
            field: "fake",
            cellTemplate: '
' +
            '<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.deleteRow($event)">Delete</button>' +
            '<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Edit</button>' +
            '<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.saveEdit($event)">Update</button>' +
            '<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.cancelEdit($event)">Cancel</button>' +
            '
',
            enableCellEdit: false,
            enableFiltering: false,
            enableSorting: false,
            showSortMenu: false,
            enableColumnMenu: false,
            width: "10%"
        },
        {
            name: 'Id',
            visible: false
        },
        {
            name: 'Key',
            enableCellEdit: true,
            cellTemplate: '

{{row.entity[col.field]}}

',
            width: "30%"
        },

        {
            name: 'Value',
            enableCellEdit: true,
            cellTemplate: '

{{row.entity[col.field]}}

',
            width: "30%"
        }

    ]
}

I am using inline edit so there are buttons in cell. One of these buttons is delete. When I click this button, record is deleted from database. However I want the grid to be refreshed after deleting operation is finished. I call functions from factory:

angular.module('ui.grid').factory('InlineEdit', function ($interval, $rootScope, $mdDialog, LocalizationService, AlertDialogFactory) {
function inlineEdit(entity, index, grid) {
    this.grid = grid;
    this.index = index;
    this.entity = {};
    this.isEditModeOn = false;
    this.init(entity);
}

inlineEdit.prototype = {
    init: function (rawEntity) {
        var self = this;

        for (var prop in rawEntity) {
            self.entity[prop] = {
                value: rawEntity[prop],
                isValueChanged: false,
                isSave: false,
                isCancel: false,
                isEdit: false
            }
        }
    },

    deleteRow: function (event) {
        event && event.stopPropagation();
        var self = this;

        self.isEditModeOn = false;

        for (var prop in self.entity) {
            self.entity[prop].isSave = true;
            self.entity[prop].isEdit = false;
        }
        LocalizationService.deleteRow(self.grid.rows[self.index]).then(function (result) {
            if (result.data.IsOk) {
                // CODE HERE...
            }
            else {
                AlertDialogFactory.ShowAlertDialog(result.data.Message, "ERROR");
            }
        });
    },
}
    return inlineEdit;
})

if result.data.IsOk is true, How can i refresh gridOptions.data from factory function? How can i reach to scope from factory?

Body:
As a solution you can broadcast an event from $rootScope.
It will be like this:

$rootScope.$broadcast("rowDeleted");

And handle that event in place where you have access to $scope.

$scope.$on("rowDeleted", deleteHandler);


问:
Creating a situation-dependent dictionary (hashlib)
The following code is part of a bigger project:

```<code># Todo: automatically generate dict based
# on hashlib.algorithms_available
algorithms = {"md5":hashlib.md5,
              "sha1":hashlib.sha1,
              "sha224":hashlib.sha224,
              "sha256":hashlib.sha256,
              "sha384":hashlib.sha384,
              "sha512":hashlib.sha512,
              "sha3_224":hashlib.sha3_224,
              "sha3_256":hashlib.sha3_256,
              "sha3_384":hashlib.sha3_384,
              "sha3_512":hashlib.sha3_512,
            }
self.algo, algorithms = algorithms[self.algo], None
</code>```

I am trying to use hashlib's algorithms_available (hashlib.algorithms_available) to create a custom dictionary, system-dependent. The key:value pair should be like 《algorithm name》: hashlib.《algorithm》, but I can't figure it out.

答:
You can get the algorithm object using hashlib.new and create a dict, iterating over hashlib.algorithms_available.

Something like this -

```<code>In : algorithms = {algo:hashlib.new(algo) for algo in hashlib.algorithms_available}

In : algorithms
Out:
{'DSA': <DSA HASH object @ 0x103e824b0>,
 'DSA-SHA': <DSA-SHA HASH object @ 0x103e8ac70>,
 'MD4': <MD4 HASH object @ 0x102e55470>,
 'MD5': <MD5 HASH object @ 0x103e9ddf0>,
 'MDC2': <MDC2 HASH object @ 0x103eeebb0>,
 'RIPEMD160': <RIPEMD160 HASH object @ 0x104012ef0>,
 'SHA': <SHA HASH object @ 0x103c99af0>,
 'SHA1': <SHA1 HASH object @ 0x103ef32f0>,
 'SHA224': <SHA224 HASH object @ 0x1040123b0>,
 'SHA256': <SHA256 HASH object @ 0x103e9d6f0>,
 'SHA384': <SHA384 HASH object @ 0x103ef02b0>,
 'SHA512': <SHA512 HASH object @ 0x103e9d2b0>,
 'dsaEncryption': <dsaEncryption HASH object @ 0x1040120f0>,
 'dsaWithSHA': <dsaWithSHA HASH object @ 0x103e82a30>,
 'ecdsa-with-SHA1': <ecdsa-with-SHA1 HASH object @ 0x103e9d670>,
 'md4': <md4 HASH object @ 0x102de49f0>,
 'md5': <md5 HASH object @ 0x103e8a570>,
 'mdc2': <mdc2 HASH object @ 0x103ef0db0>,
 'ripemd160': <ripemd160 HASH object @ 0x103ef09b0>,
 'sha': <sha HASH object @ 0x102dfb4b0>,
 'sha1': <sha1 HASH object @ 0x103b532b0>,
 'sha224': <sha224 HASH object @ 0x103e9d7b0>,
 'sha256': <sha256 HASH object @ 0x103eee770>,
 'sha384': <sha384 HASH object @ 0x103ef7bf0>,
 'sha512': <sha512 HASH object @ 0x103e9d6b0>}
</code>```

Body:
The following code is part of a bigger project:

# Todo: automatically generate dict based
# on hashlib.algorithms_available
algorithms = {"md5":hashlib.md5,
              "sha1":hashlib.sha1,
              "sha224":hashlib.sha224,
              "sha256":hashlib.sha256,
              "sha384":hashlib.sha384,
              "sha512":hashlib.sha512,
              "sha3_224":hashlib.sha3_224,
              "sha3_256":hashlib.sha3_256,
              "sha3_384":hashlib.sha3_384,
              "sha3_512":hashlib.sha3_512,
            }
self.algo, algorithms = algorithms[self.algo], None

I am trying to use hashlib's algorithms_available (hashlib.algorithms_available) to create a custom dictionary, system-dependent. The key:value pair should be like 《algorithm name》: hashlib.《algorithm》, but I can't figure it out.

Body:
You can get the algorithm object using hashlib.new and create a dict, iterating over hashlib.algorithms_available.

Something like this -

In : algorithms = {algo:hashlib.new(algo) for algo in hashlib.algorithms_available}

In : algorithms
Out:
{'DSA': <DSA HASH object @ 0x103e824b0>,
 'DSA-SHA': <DSA-SHA HASH object @ 0x103e8ac70>,
 'MD4': <MD4 HASH object @ 0x102e55470>,
 'MD5': <MD5 HASH object @ 0x103e9ddf0>,
 'MDC2': <MDC2 HASH object @ 0x103eeebb0>,
 'RIPEMD160': <RIPEMD160 HASH object @ 0x104012ef0>,
 'SHA': <SHA HASH object @ 0x103c99af0>,
 'SHA1': <SHA1 HASH object @ 0x103ef32f0>,
 'SHA224': <SHA224 HASH object @ 0x1040123b0>,
 'SHA256': <SHA256 HASH object @ 0x103e9d6f0>,
 'SHA384': <SHA384 HASH object @ 0x103ef02b0>,
 'SHA512': <SHA512 HASH object @ 0x103e9d2b0>,
 'dsaEncryption': <dsaEncryption HASH object @ 0x1040120f0>,
 'dsaWithSHA': <dsaWithSHA HASH object @ 0x103e82a30>,
 'ecdsa-with-SHA1': <ecdsa-with-SHA1 HASH object @ 0x103e9d670>,
 'md4': <md4 HASH object @ 0x102de49f0>,
 'md5': <md5 HASH object @ 0x103e8a570>,
 'mdc2': <mdc2 HASH object @ 0x103ef0db0>,
 'ripemd160': <ripemd160 HASH object @ 0x103ef09b0>,
 'sha': <sha HASH object @ 0x102dfb4b0>,
 'sha1': <sha1 HASH object @ 0x103b532b0>,
 'sha224': <sha224 HASH object @ 0x103e9d7b0>,
 'sha256': <sha256 HASH object @ 0x103eee770>,
 'sha384': <sha384 HASH object @ 0x103ef7bf0>,
 'sha512': <sha512 HASH object @ 0x103e9d6b0>}


问:
Font awesome - undefined variable
I am getting the error below when compiling assets in Ruby on Rails.

```<code>Undefined variable: "$fa-css-prefix".
</code>```

The things I have checked:-

font-awesome-sass gem in gemfile

font-awesome and font-awesome-sprockets imported

_variables checked to make sure fa-font-path points to the fonts location

_variables renamed to _aavariables to try and force this to be the first file processed.

In my application.scss file I have:-

```<code> *= require_tree .
 *= require_self
 *= require_tree ../css
 *= require_tree ../plugins
 *= require_tree ../plugins/font-awesome/scss
 *= require_tree ../plugins/font-awesome/fonts
</code>```

and

```<code> @import "bootstrap-sprockets";
 @import "bootstrap";
 @import "font-awesome-sprockets";
 @import "font-awesome";
</code>```

I can get rid of the error temporarily by including an import statement for 'variables' in each of the partials but I would rather fix the cause.

答:
I have now resolved this issue. It boiled down to the fact that my require statement in application.scss wasn't referencing the font-awesome.css file correctly.

Due to the fact that I have imported a website from wrap-bootstrap my assets are in non-standard places and I was incorrectly referencing the font-awesome file.

I corrected the problem by adding this line to application.scss:-

```<code>*= require font-awesome/css/font-awesome
</code>```

Title: Font awesome - undefined variable

Body:
I am getting the error below when compiling assets in Ruby on Rails.

Undefined variable: "$fa-css-prefix".

The things I have checked:-

font-awesome-sass gem in gemfile

font-awesome and font-awesome-sprockets imported

_variables checked to make sure fa-font-path points to the fonts location

_variables renamed to _aavariables to try and force this to be the first file processed.

In my application.scss file I have:-

 *= require_tree .
 *= require_self
 *= require_tree ../css
 *= require_tree ../plugins
 *= require_tree ../plugins/font-awesome/scss
 *= require_tree ../plugins/font-awesome/fonts

and

 @import "bootstrap-sprockets";
 @import "bootstrap";
 @import "font-awesome-sprockets";
 @import "font-awesome";

I can get rid of the error temporarily by including an import statement for 'variables' in each of the partials but I would rather fix the cause.

Body:
I have now resolved this issue. It boiled down to the fact that my require statement in application.scss wasn't referencing the font-awesome.css file correctly.

Due to the fact that I have imported a website from wrap-bootstrap my assets are in non-standard places and I was incorrectly referencing the font-awesome file.

I corrected the problem by adding this line to application.scss:-

*= require font-awesome/css/font-awesome


问:
QT tab widget - tab text behaviour on focus

I am using Qt to create a QT tab widget for a GUI. I cant figure out why the tab currently in focus changes the text to white ? It only happens on the currently selected tab. If I open another window in the same GUI, The text goes back to black.

How can I always force the text to remain black, even when under focus ?

I am using Qt 5.8.0 on a mac OS X running El Capitan 10.11.6.

this is my current style sheet

```<code>tabWidget1->setStyleSheet("QTabBar::tab { background-color: #ACB6B6; }"
                              "QTabBar::tab:focus { color: #000000; }");
</code>```

I've also tried to use this code but it didnt do anything

```<code>tabWidget1->setFocusPolicy(Qt::NoFocus);
</code>```

答:
```<code>tabWidget1->setStyleSheet("QTabBar::tab:selected {color: #000000;}");
</code>```

Resolved using the above stylesheet.

Body:
I am using Qt to create a QT tab widget for a GUI. I cant figure out why the tab currently in focus changes the text to white ? It only happens on the currently selected tab. If I open another window in the same GUI, The text goes back to black.

How can I always force the text to remain black, even when under focus ?

I am using Qt 5.8.0 on a mac OS X running El Capitan 10.11.6.

this is my current style sheet

tabWidget1->setStyleSheet("QTabBar::tab { background-color: #ACB6B6; }"
                              "QTabBar::tab:focus { color: #000000; }");

I've also tried to use this code but it didnt do anything

tabWidget1->setFocusPolicy(Qt::NoFocus);

Body:
tabWidget1->setStyleSheet("QTabBar::tab:selected {color: #000000;}");

Resolved using the above stylesheet.


答:
Your solution will iterate through the while loop only once and when my_sum becomes >= to n it will stop.

What you need is:

```<code>for x in range(1, n+1):
    my_sum += x
</code>```

This will do the job. n+1 is done because the right boundary of range() is non-inclusive.

Title: How to add up the numbers 1 through "n" and print out the result?

Body:
I have written the following code for an exercise I was given, nonetheless, when I try to submit it,  I get an incorrect answer for my code.

So this is my code:

def problem(n):
    my_sum = 0
    while my_sum < n:
        my_sum = n
        my_sum = my_sum + n
    print (my_sum)

What they have asked me to code is the following: Write a function problem(n): that adds up the numbers 1 through n and
prints out the result.  You should use either a 'while' loop or a 'for' loop.
Be sure that you check your answer on several numbers n.

Body:
Your solution will iterate through the while loop only once and when my_sum becomes >= to n it will stop.

What you need is:

for x in range(1, n+1):
    my_sum += x

This will do the job. n+1 is done because the right boundary of range() is non-inclusive.


问:
inputAccessoryView disappears after presenting UIViewController
I have a UICollectionViewController with an inputAccessoryView. Everything works great until I present a UIViewController, and then the accessory view disappears.  Trying to get basic Chat application features.

I have implemented in the collection view:

```<code>override var inputAccessoryView: UIView? {
    get {
        return inputContainerView
    }
}

override var canBecomeFirstResponder: Bool {
    return true
}

override func becomeFirstResponder() -> Bool {
    return true
}
</code>```

As suggested in multiple other threads, I also call (in the collection view),

```<code>view.resignFirstResponder()
view.inputAccessoryView?.reloadInputViews()
view.becomeFirstResponder()
</code>```

after dismissing the UIViewController but to no avail.  print(view.isFirstResponder) still prints false.  I have tried almost every combination of the above three lines in numerous different places in my code.  I think I'm missing something simple.

答:
After a few days I finally figured out something that works... I think I was trying to present the loginController before the collectionView was set as the first responder.  Instead of just calling present I called this function:

```<code>func presentLoginControllerAfterImFirstResponder(fromUser: Bool) {
    // Starts a timer
    Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { (timer) in
        // Is this view the first responder?
        if self.isFirstResponder {
            // Creates the loginController
            let loginController = LoginController()
            // Presents it
            self.present(loginController, animated: fromUser, completion: {
                // Once presented, sets rootViewController = self
                loginController.rootViewController = self
            })
            // Stop the timer
            timer.invalidate()
        }
    }
}
</code>```

This works now.  I guess the collectionView needed some time to set itself as the first responder?  I can present and dismiss the loginController no problem and the inputAccessoryView remains.

Body:
I have a UICollectionViewController with an inputAccessoryView. Everything works great until I present a UIViewController, and then the accessory view disappears.  Trying to get basic Chat application features.

I have implemented in the collection view:

override var inputAccessoryView: UIView? {
    get {
        return inputContainerView
    }
}

override var canBecomeFirstResponder: Bool {
    return true
}

override func becomeFirstResponder() -> Bool {
    return true
}

As suggested in multiple other threads, I also call (in the collection view),

view.resignFirstResponder()
view.inputAccessoryView?.reloadInputViews()
view.becomeFirstResponder()

after dismissing the UIViewController but to no avail.  print(view.isFirstResponder) still prints false.  I have tried almost every combination of the above three lines in numerous different places in my code.  I think I'm missing something simple.

Body:
After a few days I finally figured out something that works... I think I was trying to present the loginController before the collectionView was set as the first responder.  Instead of just calling present I called this function:

func presentLoginControllerAfterImFirstResponder(fromUser: Bool) {
    // Starts a timer
    Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) { (timer) in
        // Is this view the first responder?
        if self.isFirstResponder {
            // Creates the loginController
            let loginController = LoginController()
            // Presents it
            self.present(loginController, animated: fromUser, completion: {
                // Once presented, sets rootViewController = self
                loginController.rootViewController = self
            })
            // Stop the timer
            timer.invalidate()
        }
    }
}

This works now.  I guess the collectionView needed some time to set itself as the first responder?  I can present and dismiss the loginController no problem and the inputAccessoryView remains.


答:
```<code>$('.ContText-3').text("To find out more about how Lister, Jeter & Lloyd, CPAs can help you grow your business, contact us. We'd be happy to sit down with you, learn about your business, and share how we can help.");
</code>```

Title: Escape Apostrophe In JQuery .text()


问:
How to get a particular value from a Url in iOS - Swift 3
I have a url that is reg code attached to it. I just want to retrieve the reg code 7954741093-41547468-3 from the below url </p>

```<code>https://mycode.funny.net/mycode/Registrations/7954741093-41547468-3?api-version=2011-04
</code>```

答:
i think using URLComponents is a little more robust:

```<code>let url = "https://mycode.funny.net/mycode/Registrations/7954741093-41547468-3?api-version=2011-04"
let components = URLComponents(string: url)
components?.path.components(separatedBy: "/").last
</code>```

Body:
I have a url that is reg code attached to it. I just want to retrieve the reg code 7954741093-41547468-3 from the below url

https://mycode.funny.net/mycode/Registrations/7954741093-41547468-3?api-version=2011-04

Body:
i think using URLComponents is a little more robust:

let url = "https://mycode.funny.net/mycode/Registrations/7954741093-41547468-3?api-version=2011-04"
let components = URLComponents(string: url)
components?.path.components(separatedBy: "/").last


问:
SwiftyJSON Alamofire How to return what you got?
How to return what you got?Excuse me, novice, I understand only.enter image description here

enter image description here

答:
Alamofire.request is an asynchronous task, so any code written after this is most likely going to be executed before the task is complete. There are a few ways of doing what you want, but since you haven't provided much information, I have just moved the JSON inside the closure. So you should get something to print out.

```<code>Alamofire.request("https://...").responseJSON { (response) in

    // Inside this closure is where you receive your JSON

    if let value = response.value {

        let json = JSON(value)

        let title = json["posts", 3, "title"].stringValue

        print("Title:", title)
    }
}

// Any code after this request will most likely be executed before
// the request has completed because it is done asynchronously.
</code>```

This is another way that might work better for you.

I understand that you are a beginner and these kinds of operations can be quite complex. You need to understand the order at which code get executed, and how variables work. You are getting that error because swiftyJsonVar is declared in a block that is not accessible to code in the viewDidLoad. I suggest you learn about multi-threading and other asynchronous tasks and probably learn how to declare and use variables properly.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    load { (json) in

        if let json = json {

            let title = json["posts", 3, "title"].stringValue

            print("Title:", title)
        }
    }
}

func load(completion: @escaping (JSON?) -> Void){

    Alamofire.request("https://httpbin.org/get").responseJSON { (response) in //https://...

        var json: JSON?

        if let value = response.value {

            json = JSON(value)
        }

        completion(json)
    }
}
</code>```

Body:
Alamofire.request is an asynchronous task, so any code written after this is most likely going to be executed before the task is complete. There are a few ways of doing what you want, but since you haven't provided much information, I have just moved the JSON inside the closure. So you should get something to print out.

Alamofire.request("https://...").responseJSON { (response) in

    // Inside this closure is where you receive your JSON

    if let value = response.value {

        let json = JSON(value)

        let title = json["posts", 3, "title"].stringValue

        print("Title:", title)
    }
}

// Any code after this request will most likely be executed before
// the request has completed because it is done asynchronously.

This is another way that might work better for you.

I understand that you are a beginner and these kinds of operations can be quite complex. You need to understand the order at which code get executed, and how variables work. You are getting that error because swiftyJsonVar is declared in a block that is not accessible to code in the viewDidLoad. I suggest you learn about multi-threading and other asynchronous tasks and probably learn how to declare and use variables properly.

override func viewDidLoad() {
    super.viewDidLoad()

    load { (json) in

        if let json = json {

            let title = json["posts", 3, "title"].stringValue

            print("Title:", title)
        }
    }
}

func load(completion: @escaping (JSON?) -> Void){

    Alamofire.request("https://httpbin.org/get").responseJSON { (response) in //https://...

        var json: JSON?

        if let value = response.value {

            json = JSON(value)
        }

        completion(json)
    }
}


问:
Plotting dates with matplotlib
I've been attempting to plot data from a comma delimited csv file which contains a date and a float:

```<code>Date,Price (€)
01062017,20.90
02062017,30.90
03062017,40.90
04062017,60.90
05062017,50.90
</code>```

I then attempt to plot this with the following code:

```<code>import matplotlib.pyplot as plt
import numpy as np
import datetime

dates,cost = np.loadtxt('price_check.csv',delimiter=',',skiprows=1,unpack=True)

xdates = [datetime.datetime.strptime(str(int(date)),'%d%m%Y') for date in dates]

fig = plt.figure()
ax = plt.subplot(111)
plt.plot(xdates, cost,'o-',label='Cost')
plt.legend(loc=4)
plt.ylabel('Price (Euro)')
plt.xlabel('date')
plt.gcf().autofmt_xdate()
plt.grid()
plt.savefig('sunglasses_cost.png')
plt.show()
</code>```

However, when the data is plotted, it looks like the leading zero in in the date string is being dropped:

Is there an easy way for the full date to be used in the plot?

答:
The problem are the dates, which are converted to integers and loose their leading zero. Then
 "01062017" becomes 1062017 and is then interpreted as (2017, 6, 10, 0, 0),  so 2 digits as day, one digit month. For 5062017, because there is no 50th of june, it is interpreted differently and correctly as (2017, 6, 5, 0, 0).

The least invasive method to overcome this would be to format the string such that it always has 8 digist before datetime conversion:

```<code>xdates = [datetime.datetime.strptime('{:08}'.format(int(date)),'%d%m%Y') for date in dates]
</code>```

This will then result in the correct plot. However, the xticklabels may show in an inconvenient way. This could be adjusted by choosing some locator and formatter

```<code>import matplotlib.dates as mdates
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
</code>```

As a last comment: If you have the choice to select the format of your input file, it might be worth specifing it in a non-ambiguous way, e.g. 20170601.

Title: Plotting dates with matplotlib

Body:
I've been attempting to plot data from a comma delimited csv file which contains a date and a float:

Date,Price (€)
01062017,20.90
02062017,30.90
03062017,40.90
04062017,60.90
05062017,50.90

I then attempt to plot this with the following code:

import matplotlib.pyplot as plt
import numpy as np
import datetime

dates,cost = np.loadtxt('price_check.csv',delimiter=',',skiprows=1,unpack=True)

xdates = [datetime.datetime.strptime(str(int(date)),'%d%m%Y') for date in dates]

fig = plt.figure()
ax = plt.subplot(111)
plt.plot(xdates, cost,'o-',label='Cost')
plt.legend(loc=4)
plt.ylabel('Price (Euro)')
plt.xlabel('date')
plt.gcf().autofmt_xdate()
plt.grid()
plt.savefig('sunglasses_cost.png')
plt.show()

However, when the data is plotted, it looks like the leading zero in in the date string is being dropped:

Is there an easy way for the full date to be used in the plot?

Body:
The problem are the dates, which are converted to integers and loose their leading zero. Then
 "01062017" becomes 1062017 and is then interpreted as (2017, 6, 10, 0, 0),  so 2 digits as day, one digit month. For 5062017, because there is no 50th of june, it is interpreted differently and correctly as (2017, 6, 5, 0, 0).

The least invasive method to overcome this would be to format the string such that it always has 8 digist before datetime conversion:

xdates = [datetime.datetime.strptime('{:08}'.format(int(date)),'%d%m%Y') for date in dates]

This will then result in the correct plot. However, the xticklabels may show in an inconvenient way. This could be adjusted by choosing some locator and formatter

import matplotlib.dates as mdates
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))

As a last comment: If you have the choice to select the format of your input file, it might be worth specifing it in a non-ambiguous way, e.g. 20170601.


问:
Error: INVALID_STATE_ERR: DOM Exception 11 breaking my AJAX?
Is this error breaking my code? I get it in readystate 1.

Relevant HTML code:

```<code><input type="button" value="Log In" onclick="login()" class="submit" />
</code>```

Relevant Javascript:

```<code>function login() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("headSpan").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", "logIn.php", true);
        xmlhttp.send("usr=bob");
    }
</code>```

logIn.php:

```<code><?php
echo $_POST['usr'];
?>
</code>```

Then, xmlhttp.responseText is "". If it's doing what I think it should be, I would get 'bob';

Thanks in advance.

EDIT: This error is defined as "If an attempt is made to use an object that is not, or is no longer, usable". Just FYI.

答:
Found the solution:

```<code>var params = "usr=bob";
        xmlhttp.open("POST", "logIn.php", true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close");
        xmlhttp.send(params);
</code>```

Apparently the request header doesn't automagically work for PHP always as I had assumed (and found no proof to dissuade me from that belief). Anyways, pretty simple solution, but frustrating nonetheless. Just for an extra bit of info: running WAMP (not the pre-built thingy, the acronym). Apache 2.2, PHP 5.3.3.

Body:
Is this error breaking my code? I get it in readystate 1.

Relevant HTML code:

<input type="button" value="Log In" onclick="login()" class="submit" />

Relevant Javascript:

function login() {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("headSpan").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST", "logIn.php", true);
        xmlhttp.send("usr=bob");
    }

logIn.php:

<?php
echo $_POST['usr'];
?>

Then, xmlhttp.responseText is "". If it's doing what I think it should be, I would get 'bob';

Thanks in advance.

EDIT: This error is defined as "If an attempt is made to use an object that is not, or is no longer, usable". Just FYI.

Body:
Found the solution:

var params = "usr=bob";
        xmlhttp.open("POST", "logIn.php", true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close");
        xmlhttp.send(params);

Apparently the request header doesn't automagically work for PHP always as I had assumed (and found no proof to dissuade me from that belief). Anyways, pretty simple solution, but frustrating nonetheless. Just for an extra bit of info: running WAMP (not the pre-built thingy, the acronym). Apache 2.2, PHP 5.3.3.


问:
UITapGestureRecognizer not changing contents of CollectionViewCell . Swift
I have a collection view with lots of different pictures, and I want that when a picture is tapped, a border comes around it.

I made a custom cell, and a UICollectionViewCell with the imageView embedding in another view (which is the outline) for the pic. So I set up a UITapGestureRecognizer which works to get the index, but when I set the outer view to have a boder it doesn't work.

Here is my Cell:

```<code>import UIKit

class PicViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!

    @IBOutlet weak var imageOutline: UIView!

}
</code>```

This is in my UICollectionViewController:

```<code>override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell

            // Configure the cell

     let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))

            cell.imageOutline.addGestureRecognizer(tapGesture)

        return cell
</code>```

Here is the method for the tapGesture

```<code>func handleTap(sender: UITapGestureRecognizer) {
        print("tap")

        if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) {

            let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell

    cell.imageOutline.layer.borderWidth = 5

        } else {
            print("")
        }

    }
</code>```

答:
In your handleTap routine, you're calling the wrong method to retrieve the cell.  You want cellForItem(at:) which will retrieve the existing cell or return nil if it isn't onscreen:

```<code>let cell = collectionView?.cellForItem(at: indexPath) as! PicViewCell
</code>```

Alternate solution

If you are modifying the view you are tapping, you can access it as the view of the sender:

```<code>func handleTap(sender: UITapGestureRecognizer) {
    if let imageOutline = sender.view as? UIImageView {
        imageOutline.layer.borderWidth = 5
    }
}
</code>```

Note: In both solutions, you should update your model when a cell is outlined so that if that cell scrolls off the screen and then back onto the screen, you can use that model data to set the outline for the cell correctly in your override of collectionView(_:cellForItemAt:).

Body:
I have a collection view with lots of different pictures, and I want that when a picture is tapped, a border comes around it.

I made a custom cell, and a UICollectionViewCell with the imageView embedding in another view (which is the outline) for the pic. So I set up a UITapGestureRecognizer which works to get the index, but when I set the outer view to have a boder it doesn't work.

Here is my Cell:

import UIKit

class PicViewCell: UICollectionViewCell {

    @IBOutlet weak var imageView: UIImageView!

    @IBOutlet weak var imageOutline: UIView!

}

This is in my UICollectionViewController:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell

            // Configure the cell

     let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))

            cell.imageOutline.addGestureRecognizer(tapGesture)

        return cell

Here is the method for the tapGesture

func handleTap(sender: UITapGestureRecognizer) {
        print("tap")

        if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) {

            let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell

    cell.imageOutline.layer.borderWidth = 5

        } else {
            print("")
        }

    }

Body:
In your handleTap routine, you're calling the wrong method to retrieve the cell.  You want cellForItem(at:) which will retrieve the existing cell or return nil if it isn't onscreen:

let cell = collectionView?.cellForItem(at: indexPath) as! PicViewCell

Alternate solution

If you are modifying the view you are tapping, you can access it as the view of the sender:

func handleTap(sender: UITapGestureRecognizer) {
    if let imageOutline = sender.view as? UIImageView {
        imageOutline.layer.borderWidth = 5
    }
}

Note: In both solutions, you should update your model when a cell is outlined so that if that cell scrolls off the screen and then back onto the screen, you can use that model data to set the outline for the cell correctly in your override of collectionView(_:cellForItemAt:).


问:
Form only working when you hit the checkbox
I am making a form and I wish for the form to be able to be submitted when the checkbox is either ticked or checked. I don't get any other errors when I login without checking the box apart from this one

Notice: Undefined index: stayLoggedIn in /home/sites/2a/d/dbcf5d6440/public_html/MySQL/Challenges/Secretdiary.php on line 91

Here is my code!

```<code><?php

session_start();

 $error="";

if (array_key_exists("logout", $_GET)) {

    unset($_SESSION);
    setcookie("id", "", time() - 60*60);
    $_COOKIE["id"] = "";

} else if(array_key_exists("id", $_SESSION) OR array_key_exists("id", $_COOKIE)) {

    header("Location: loggedinpage.php");
}

    if(array_key_exists("submit", $_POST)) {

        $link = mysqli_connect("XXX", "XXX", "XXX", "XXX");

            if (mysqli_connect_error()) {

                die("Database Connection Error");
            }

        if(!$_POST['email']) {

            $error.= "An Email Address is required<br>";
        }

        if(!$_POST['password']) {

            $error.= "A Password is required<br>";
        }

        if($error != "") {

            $error = "<p>There were error(s) in your form</p>".$error;

        } else {

            if($_POST['signUp'] == '1' ) {

            $query = "SELECT id FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."' LIMIT 1";
            $result = mysqli_query($link, $query);
            if (mysqli_num_rows($result) > 0) {

                $error = "That email address is taken.";

            } else {

                $query = "INSERT INTO `users` (`email`, `password`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."', '".mysqli_real_escape_string($link, $_POST['password'])."')";

                if (!mysqli_query($link, $query)) {

                    $error="<p>Could not sign you up, please try again</p>";

                } else {

                    $query = "UPDATE `users` SET password = '".md5(md5(mysqli_insert_id($link)).$_POST['password']). "' WHERE id = ".mysqli_insert_id($link)." LIMIT 1";

                    mysqli_query($link, $query);
                    $_SESSION['id'] = mysqli_insert_id($link);
                    if ($_POST['stayLoggedIn'] == '1') {

                        setcookie("id", mysqli_insert_id($link), time() +  60*60*24*365);
                    }

                } header("Location: loggedinpage.php");

            }

        } else {

                $query = "SELECT * FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."'";

                $result = mysqli_query($link, $query);
                $row = mysqli_fetch_array($result);
                if (array_key_exists("id", $row)) {

                    $hashedPassword = md5(md5($row['id']).$_POST['password']);
                    if ($hashedPassword == $row['password']) {

                        $_SESSION['id'] = $row['id'];
                        if ($_POST['stayLoggedIn'] == '1') {

                            setcookie("id", $row ($link), time() +  60*60*24*365);
                    }
                    }
                }

                }

    }

    }

?>

<div id="error"><?php echo $error; ?></div>
<form method="post">
    <input type="email" name="email" placeholder="Your Email Eg. JoBloggs@me.co.uk">
    <input type="password" name="password" placeholder="Password">
    <input type="checkbox" name="stayLoggedIn" value=1>
    <input type="hidden" name="signUp" value="1">
    <input type="submit" name="submit" value="Sign Up!">
</form>

<form method="post">
    <input type="email" name="email" placeholder="Your Email Eg. JoBloggs@me.co.uk">
    <input type="password" name="password" placeholder="Password">
    <input type="checkbox" name="stayLoggedIn" value=1>
    <input type="hidden" name="signUp" value="0">
    <input type="submit" name="submit" value="Log In!">
</form>
</code>```

答:
Checkboxes only get submitted as parameters when they're checkecd. So you need to use isset() to test whether the checkbox was set, not check the value. So change

```<code>if ($_POST['stayLoggedIn'] == '1')
</code>```

to

```<code>if (isset($_POST['stayLoggedIn'])
</code>```

Body:
I am making a form and I wish for the form to be able to be submitted when the checkbox is either ticked or checked. I don't get any other errors when I login without checking the box apart from this one

Notice: Undefined index: stayLoggedIn in /home/sites/2a/d/dbcf5d6440/public_html/MySQL/Challenges/Secretdiary.php on line 91

Here is my code!

<?php

session_start();

 $error="";

if (array_key_exists("logout", $_GET)) {

    unset($_SESSION);
    setcookie("id", "", time() - 60*60);
    $_COOKIE["id"] = "";

} else if(array_key_exists("id", $_SESSION) OR array_key_exists("id", $_COOKIE)) {

    header("Location: loggedinpage.php");
}

    if(array_key_exists("submit", $_POST)) {

        $link = mysqli_connect("XXX", "XXX", "XXX", "XXX");

            if (mysqli_connect_error()) {

                die("Database Connection Error");
            }

        if(!$_POST['email']) {

            $error.= "An Email Address is required
";
        }

        if(!$_POST['password']) {

            $error.= "A Password is required
";
        }

        if($error != "") {

            $error = "
There were error(s) in your form
".$error;

        } else {

            if($_POST['signUp'] == '1' ) {

            $query = "SELECT id FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."' LIMIT 1";
            $result = mysqli_query($link, $query);
            if (mysqli_num_rows($result) > 0) {

                $error = "That email address is taken.";

            } else {

                $query = "INSERT INTO `users` (`email`, `password`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."', '".mysqli_real_escape_string($link, $_POST['password'])."')";

                if (!mysqli_query($link, $query)) {

                    $error="
Could not sign you up, please try again
";

                } else {

                    $query = "UPDATE `users` SET password = '".md5(md5(mysqli_insert_id($link)).$_POST['password']). "' WHERE id = ".mysqli_insert_id($link)." LIMIT 1";

                    mysqli_query($link, $query);
                    $_SESSION['id'] = mysqli_insert_id($link);
                    if ($_POST['stayLoggedIn'] == '1') {

                        setcookie("id", mysqli_insert_id($link), time() +  60*60*24*365);
                    }

                } header("Location: loggedinpage.php");

            }

        } else {

                $query = "SELECT * FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."'";

                $result = mysqli_query($link, $query);
                $row = mysqli_fetch_array($result);
                if (array_key_exists("id", $row)) {

                    $hashedPassword = md5(md5($row['id']).$_POST['password']);
                    if ($hashedPassword == $row['password']) {

                        $_SESSION['id'] = $row['id'];
                        if ($_POST['stayLoggedIn'] == '1') {

                            setcookie("id", $row ($link), time() +  60*60*24*365);
                    }
                    }
                }

                }

    }

    }

?>

<?php echo $error; ?>

<form method="post">
    <input type="email" name="email" placeholder="Your Email Eg. JoBloggs@me.co.uk">
    <input type="password" name="password" placeholder="Password">
    <input type="checkbox" name="stayLoggedIn" value=1>
    <input type="hidden" name="signUp" value="1">
    <input type="submit" name="submit" value="Sign Up!">
</form>

<form method="post">
    <input type="email" name="email" placeholder="Your Email Eg. JoBloggs@me.co.uk">
    <input type="password" name="password" placeholder="Password">
    <input type="checkbox" name="stayLoggedIn" value=1>
    <input type="hidden" name="signUp" value="0">
    <input type="submit" name="submit" value="Log In!">
</form>

Body:
Checkboxes only get submitted as parameters when they're checkecd. So you need to use isset() to test whether the checkbox was set, not check the value. So change

if ($_POST['stayLoggedIn'] == '1')

to

if (isset($_POST['stayLoggedIn'])


问:
Is BCrypt a good hashing algorithm to use in C#? Where can I find it?
I have read that when hashing a password, many programmers recommend using the BCrypt algorithm.

I am programming in C# and is wondering if anyone knows of a good implementation for BCrypt? I found this page, but I don't really know if it is bogus or not.

What should I be aware of when choosing a password hashing scheme? Is BCrypt a 'good' implementation?

答:
First, some terms that are important:

Hashing - The act of taking a string and producing a sequence of characters that cannot be reverted to the original string.

Symmetric Encryption - (Usually just referred to as 'encryption') - The act of taking a string and producing a sequence of characters that can  be decrypted to the original string through the use of the same encryption key that encrypted it.

Rainbow Table - a lookup table that contains all variations of characters hashed in a specific hashing algorithm.

Salt - a known random string appended to the original string before it is hashed.

For the .NET Framework, Bcrypt does not yet have a verified reference implementation. This is important because there's no way to know if there are serious flaws in an existing implementation. You can get an implementation of BCrypt for .NET here. I don't know enough about cryptography to say whether it's a good or bad implementation. Cryptography is a very deep field.  Do not attempt to build your own encryption algorithm. Seriously.

If you are going to implement your own password security (sigh), then you need to do several things:

Use a relatively secure hash algorithm.

Salt each password before it's hashed.

Use a unique and long salt for each password, and store the salt with the password.

Require strong passwords.

Unfortunately, even if you do all this, a determined hacker still could potentially figure out the passwords, it would just take him a really long time. That's your chief enemy: Time.

The bcrypt algorithm works because it takes five orders of magnitude longer to hash a password than MD5; (and still much longer than AES or SHA-512).  It forces the hacker to spend a lot more time to create a rainbow table to lookup your passwords, making it far less likely that your passwords will be in jeopardy of being hacked.

If you're salting and hashing your passwords, and each salt is different, then a potential hacker would have to create a rainbow table for each variation of salt, just to have a rainbow table for one salted+hashed password.  That means if you have 1 million users, a hacker has to generate 1 million rainbow tables.  If you're using the same salt for every user, then the hacker only has to generate 1 rainbow table to successfully hack your system.

If you're not salting your passwords, then all an attacker has to do is to pull up an existing Rainbow table for every implementation out there (AES, SHA-512, MD5) and just see if one matches the hash.  This has already been done, an attacker does not need to calculate these Rainbow tables themselves.

Even with all this, you've got to be using good security practices.  If they can successfully use another attack vector (XSS, SQL Injection, CSRF, et. al.) on your site, good password security doesn't matter.  That sounds like a controversial statement, but think about it: If I can get all your user information through a SQL injection attack, or I can get your users to give me their cookies through XSS, then it doesn't matter how good your password security is.

Other resources:

Jeff Atwood: .NET Encryption Simplified (great for an overview of hashing)

Jeff Atwood: I just logged in as you

Jeff Atwood: You're probably storing passwords incorrectly

Jeff Atwood: Speed Hashing

Note: Please recommend other good resources. I've must have read a dozen articles by dozens of authors, but few write as plainly on the subject as Jeff does.  Please edit in articles as you find them.

OwnerDisplayName: Svish


答: Checkboxes only send the value WHEN CHECKED.  So you have to do an isset($_POST['stayLoggedIn']) to see if the value was selected, otherwise that index will not exist in the PHP POST value.

Title: Form only working when you hit the checkbox


问:
How to insert elements into the list at arbitrary positions?
I have this

```<code>>>> a = [1, 4, 7, 11, 17]
</code>```

Is there any way to add 4 characters '-' randomly between the other elements to achieve, for example

```<code>['-', 1, '-', 4, 7, '-', '-', 11, 17]
</code>```

答:
You could simply do:

```<code>import random
for _ in range(4):
    a.insert(random.randint(0, len(a)), '-')
</code>```

The loop body inserts a '-' at a random index between 0 and len(a)(inclusive). However, since inserting into a list is O(N), you might be better off performance-wise constructing a new list depending on the number of inserts and the length of the list:

```<code>it = iter(a)
indeces = list(range(len(a) + 4))
dash_indeces = set(random.sample(indeces, 4))  # four random indeces from the available slots
a = ['-' if i in dash_indeces else next(it) for i in indeces]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this

>>> a = [1, 4, 7, 11, 17]

Is there any way to add 4 characters '-' randomly between the other elements to achieve, for example

['-', 1, '-', 4, 7, '-', '-', 11, 17]

Body:
You could simply do:

import random
for _ in range(4):
    a.insert(random.randint(0, len(a)), '-')

The loop body inserts a '-' at a random index between 0 and len(a)(inclusive). However, since inserting into a list is O(N), you might be better off performance-wise constructing a new list depending on the number of inserts and the length of the list:

it = iter(a)
indeces = list(range(len(a) + 4))
dash_indeces = set(random.sample(indeces, 4))  # four random indeces from the available slots
a = ['-' if i in dash_indeces else next(it) for i in indeces]


问:
gulp-clean-css cannot set the right relative path for url() for assets such as fonts and images
I use NPM and Gulp for my package manager and build system.
I have installed "gulp-sass" to support sass, and "gulp-clean-css" so that I can @import css files inline.
I capture my SCSS files in "_frontend/scss/**/*", and compiles that into a single file as "assets/frontend/css/styles.css".
In the output location, I have other important resources folders that are siblings of "css": "fonts", "img", and "js".

My problem is I cannot get the url() relative paths to target correctly when I'm importing a "*.css" file.
However, it is okay when I'm importing ".scss" files.

Here is my code (I took out sourcemaps, error log etc to simplify the question):

GULPFILE.JS

```<code>gulp.task('styles', function() {
    gulp.src(styles.src)
        .pipe(sassGlob())                                   // Support for bundle requires for Sass
        .pipe(cleanCSS({
            // relativeTo: './node_modules',    <-- I tried with different variations here, no luck
            // root: './node_modules',          <-- I tried with different variations here, no luck
            processImport: true
        }))
        .pipe(rename('styles.css'))                      // Name output CSS file
        .pipe(gulp.dest('../assets/frontend/css/'));
});
</code>```

MAIN.SCSS

The following is OK

```<code>@import "font-awesome/scss/font-awesome.scss";
</code>```

Output seems to come out with the correct relative paths
Sample output: url(../fonts/FontAwesome/fontawesome-webfont.eot?v=4.6.1)

The following is NOT

```<code>@import '../node_modules/jquery-ui/themes/base/jquery-ui.css';
</code>```

Sample output: url(../node_modules/jquery-ui/themes/base/images/animated-overlay.gif)
^^ The above somehow appends the "../node_modules".
I want it to somehow set this to "../img/vendor/jquery-ui/what/ever/i/like/here"

Here's my directory structure.

```<code>_frontend
 ├─fonts
 │  ├─Beamstyle-Icons
 │  └─Gotham-Light-Regular
 ├─node_modules
 │  ├─jquery-ui
 │  │  ├─scripts
 │  │  └─themes
 │  │      ├─base
 │  │         ├─images
 │  │         └─minified
 │  │             └─images
 │  └─ (other stuff...)
 │
 ├─scripts
 │  ├─app
 │  └─vendor
 └─scss
     ├─config
     ├─helpers
     │  ├─classes
     │  ├─functions
     │  ├─mixins
     │  └─placeholders
     └─src
         ├─blocks
         └─components
assets
 └─frontend
    ├─css
    ├─fonts
    ├─img
    │  ├─Beamstyle-Icons
    │  ├─FontAwesome
    │  └─Gotham-Light-Regular
    └─js
</code>```

Would be great if anyone can help on this.

答:
For version < 2.4

use relativeTo, root and target and if you don't want to rebase you can use rebase: false configuration options.

For version >= 2.4

gulp-clean-css has been upgraded to use clean-css 4.x so none of the options above work and they only provide rebaseTo option which will rebase all of your paths.

Body:
I use NPM and Gulp for my package manager and build system.
I have installed "gulp-sass" to support sass, and "gulp-clean-css" so that I can @import css files inline.
I capture my SCSS files in "_frontend/scss/**/*", and compiles that into a single file as "assets/frontend/css/styles.css".
In the output location, I have other important resources folders that are siblings of "css": "fonts", "img", and "js".

My problem is I cannot get the url() relative paths to target correctly when I'm importing a "*.css" file.
However, it is okay when I'm importing ".scss" files.

Here is my code (I took out sourcemaps, error log etc to simplify the question):

GULPFILE.JS

gulp.task('styles', function() {
    gulp.src(styles.src)
        .pipe(sassGlob())                                   // Support for bundle requires for Sass
        .pipe(cleanCSS({
            // relativeTo: './node_modules',    <-- I tried with different variations here, no luck
            // root: './node_modules',          <-- I tried with different variations here, no luck
            processImport: true
        }))
        .pipe(rename('styles.css'))                      // Name output CSS file
        .pipe(gulp.dest('../assets/frontend/css/'));
});

MAIN.SCSS

The following is OK

@import "font-awesome/scss/font-awesome.scss";

Output seems to come out with the correct relative paths
Sample output: url(../fonts/FontAwesome/fontawesome-webfont.eot?v=4.6.1)

The following is NOT

@import '../node_modules/jquery-ui/themes/base/jquery-ui.css';

Sample output: url(../node_modules/jquery-ui/themes/base/images/animated-overlay.gif)
^^ The above somehow appends the "../node_modules".
I want it to somehow set this to "../img/vendor/jquery-ui/what/ever/i/like/here"

Here's my directory structure.

_frontend
 ├─fonts
 │  ├─Beamstyle-Icons
 │  └─Gotham-Light-Regular
 ├─node_modules
 │  ├─jquery-ui
 │  │  ├─scripts
 │  │  └─themes
 │  │      ├─base
 │  │         ├─images
 │  │         └─minified
 │  │             └─images
 │  └─ (other stuff...)
 │
 ├─scripts
 │  ├─app
 │  └─vendor
 └─scss
     ├─config
     ├─helpers
     │  ├─classes
     │  ├─functions
     │  ├─mixins
     │  └─placeholders
     └─src
         ├─blocks
         └─components
assets
 └─frontend
    ├─css
    ├─fonts
    ├─img
    │  ├─Beamstyle-Icons
    │  ├─FontAwesome
    │  └─Gotham-Light-Regular
    └─js

Would be great if anyone can help on this.


答:
If checkbox not selected, value of checkbox not send. You can check stayLoggedIn index exist or not by isset function:

```<code>if (isset($_POST['stayLoggedIn']) && $_POST['stayLoggedIn'] == '1') {
</code>```

Body:
If checkbox not selected, value of checkbox not send. You can check stayLoggedIn index exist or not by isset function:

if (isset($_POST['stayLoggedIn']) && $_POST['stayLoggedIn'] == '1') {