问:
Validate that exposed primary/foreign keys in a form are intact
I have a Survey form. Every question has 3-4 pre-defined answers as radio buttons. The value of a radio button is the primary key of the answer in the database.

As all answers to all questions are stored in one table, if a user increments the value, the ID may still be a valid foreign key, but it does not belong to that question.

What's the best practice to be sure the value of the radio button is not manipulated?

答:
As David has already mentioned, you gonna need to validate your business logic.

The most "laravelish" way, as you mentioned, is to perform validations within your request classes and develop extra validator extensions if needed. Littering your controllers with validation logic, as Erin has mentioned, is not a good practice at all; it works though.

I assume you're having two separate models: Question and Answer. Also, a full 1-N relationship set between them in a way that a question can have many answers and each answer belongs to a question:

class Question extends Model
{
    public function answers()
    {
        return $this->hasMany(Answer::class);
    }
}

class Answer extends Model
{
    public function question()
    {
        return $this->belongsTo(Question::class);
    }
}
```

<p>Let's say you also have a <code>SurveyController</code>:</p>

<pre class="lang-php prettyprint-override"><code>class SurveyController extends Controller
{
    public function store(CreateSurveyRequest $request)
    {
        // Request is validated by now and you can be sure that the
        // answer belongs to the question. Go on and create/store
        // the Survey entity.
    }
}
</code>```

And the request class which does the actual data validation:

class CreateSurveyRequest extends FormRequest
{
    public function rules()
    {
        // Assuming the request contains `answer_id` and `question_id` fields:

        return [
            'answer_id' => 'exists:answers,id,question_id,' . request('question_id'),
            // e.g.
            // 8 => 'exists:answers,id,question_id,10'
            // Which loosly translates to "answer ID 8 should belong to question ID 10"
        ];
    }
}
```

Such exists rule definition makes sure that the answer record has a foreign key on the questions table and thus it's a valid answer to the question.

The point is that Laravel's exists rule supports additional conditions. Interesting, the guy filing the proposal was feeling the exact same need you're having here.

Body:
As David has already mentioned, you gonna need to validate your business logic.

The most "laravelish" way, as you mentioned, is to perform validations within your request classes and develop extra validator extensions if needed. Littering your controllers with validation logic, as Erin has mentioned, is not a good practice at all; it works though.

I assume you're having two separate models: Question and Answer. Also, a full 1-N relationship set between them in a way that a question can have many answers and each answer belongs to a question:

class Question extends Model
{
    public function answers()
    {
        return $this->hasMany(Answer::class);
    }
}

class Answer extends Model
{
    public function question()
    {
        return $this->belongsTo(Question::class);
    }
}

Let's say you also have a SurveyController:

class SurveyController extends Controller
{
    public function store(CreateSurveyRequest $request)
    {
        // Request is validated by now and you can be sure that the
        // answer belongs to the question. Go on and create/store
        // the Survey entity.
    }
}

And the request class which does the actual data validation:

class CreateSurveyRequest extends FormRequest
{
    public function rules()
    {
        // Assuming the request contains `answer_id` and `question_id` fields:

        return [
            'answer_id' => 'exists:answers,id,question_id,' . request('question_id'),
            // e.g.
            // 8 => 'exists:answers,id,question_id,10'
            // Which loosly translates to "answer ID 8 should belong to question ID 10"
        ];
    }
}

Such exists rule definition makes sure that the answer record has a foreign key on the questions table and thus it's a valid answer to the question.

The point is that Laravel's exists rule supports additional conditions. Interesting, the guy filing the proposal was feeling the exact same need you're having here.


来源: stackexchange

问:
JS split regex by two different character
I have 2 strings:

```<code>"test:header_footer"
"test_3142"
</code>```

I want to get array:

```<code>array = "test:header_footer".split(":") // ['test', 'header_footer']
array2 = "test_3142".split("_") // ['test', '3142']
</code>```

Can I combine this with a regex expression to get the same result?

```<code>function(s) {
 retutn s.split(/:|_/) // return bad value
}
</code>```

So if string contain ':' - not separate by second '_'

答:
You could write a one line method to check for : and split based on that condition.

```<code>var text = "your:string";
var array = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'string']

var text2 = "your_string";
var array2 = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'string']

var text3 = "your:other_string";
var array3 = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'other_string']
</code>```

This will check for :, if that is found then split by :, otherwise split by _.

ContentLicense: CC BY-SA 3.0

Body:
I have 2 strings:

"test:header_footer"
"test_3142"

I want to get array:

array = "test:header_footer".split(":") // ['test', 'header_footer']
array2 = "test_3142".split("_") // ['test', '3142']

Can I combine this with a regex expression to get the same result?

function(s) {
 retutn s.split(/:|_/) // return bad value
}

So if string contain ':' - not separate by second '_'

Body:
You could write a one line method to check for : and split based on that condition.

var text = "your:string";
var array = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'string']

var text2 = "your_string";
var array2 = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'string']

var text3 = "your:other_string";
var array3 = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'other_string']

This will check for :, if that is found then split by :, otherwise split by _.


问:
Display incoming xml request in Rails
Hey guys,
Is there an easy way to display the complete xml request I'm getting posted to one of my methods?
Thanks a lot</p>

答:
If you want to see the actual XML that is being posted rather than a params hash try

xml_data = request.raw_post

Then to get a hash out of that you could do

hash_from_xml_data = Hash.from_xml(xml_data)

ContentLicense: CC BY-SA 2.5

Title: Display incoming xml request in Rails


问:
Elasticsearch "StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath."
I upgraded elasticsearch java client from 2.3 to 5.1.

And this error log continues to appear.

```<code>ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
</code>```

I'm using log4j2

```<code><dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>
</code>```

答:
very late answer, however :) if you don't want to upgrade ES, just add following dependency to pom :

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-to-slf4j</artifactId>
    <version>2.8.2</version>
</dependency>
```

that should fix it

Body:
I upgraded elasticsearch java client from 2.3 to 5.1.

And this error log continues to appear.

ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...

I'm using log4j2

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
</dependency>

Body:
very late answer, however :) if you don't want to upgrade ES, just add following dependency to pom :

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-to-slf4j</artifactId>
    <version>2.8.2</version>
</dependency>

that should fix it

ContentLicense: CC BY-SA 4.0


问:
Button is not redirecting me to the next "page"
I am currently making an app. I would like to redirect the user to the next page but it is mainly just pressing the button and you would be brought over to the next set of details. It should still remain on the same html link. However, when I press the button, nothing seems to be working.

```<code><div data-role="page" id="mainpage">
    <h1>
        <b>Converter App</b>
    </h1>
</div>
<div class="app">
    <a href="#convertingpage" class="ui-btn">Convert</a>
    <div data-role="page" id="convertingpage">
        <p> stuff on my second page</p>
    </div>
</div>
</code>```

I am sorry if this sounds rather complex or hard to comprehend.

答:
Assuming convertingpage is an HTML page which is in the same location of Main page. ( if different than hmtl change the html suffix accordingly)

When you specify  href="#convertingpage" it means to look on the same page for an element with  an ID of convertingpage.

If you want to be redirected to other page use:

```<code> <a href="convertingpage.html" class="ui-btn">Convert</a>
</code>```

Body:
I am currently making an app. I would like to redirect the user to the next page but it is mainly just pressing the button and you would be brought over to the next set of details. It should still remain on the same html link. However, when I press the button, nothing seems to be working.

        Converter App

    Convert

 stuff on my second page

I am sorry if this sounds rather complex or hard to comprehend.

Body:
Assuming convertingpage is an HTML page which is in the same location of Main page. ( if different than hmtl change the html suffix accordingly)

When you specify  href="#convertingpage" it means to look on the same page for an element with  an ID of convertingpage.

If you want to be redirected to other page use:

 <a href="convertingpage.html" class="ui-btn">Convert</a>


问:
multiple int[][] array to single[] String array in java
So, I'm new to programming and I have this exercise where I have to read an int[][] array with the age and a handicap level of people trying to start a membership in a Club, with two categories, Senior and Open.
My job is to read the array for example [[45, 12],[55,21],[19, -2]] where the first int is the age and the second the handicap level. If the age is at least 55 and the handicap level is higher than 7 then the person gets a Senior membership if not he gets an Open one. My idea was to see the int[][] as a matrix and add both numbers (age and level) and if the number is higher than 62 I would classify it as a Senior otherwise as open.
My method looks like this:

```<code>public class montecarlo {
    static String[] openOrSenior(int[][] a) {
        int i, j, sum;
        String[] abo = new String[a[0].length];
        for (i = 0; i < a.length; i++)
            for (j = 0; j < a[0].length; j++ ) {
                sum = 0;
                int x = a[i][j];
                sum = sum + x;
                if (sum > 62)
                   abo[i] = "Senior";
                else
                   abo[i] = "Open"; //this would be line 12
            }
        return abo;
}

    public static void main(String[] args) {
        int [][] a = {{42, 12},{55, 21},{19,-2}};
        String[] x = openOrSenior(a);    //this would be line 20
        Out.print(x);    //here was to see what i'd get if i let it run

    }
}
</code>```

This is the error i get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
     at montecarlo.openOrSenior(montecarlo.java:12)      at
  montecarlo.main(montecarlo.java:20)

I would really appreciate some help.

答:
Try something like</p>

```<code>public class montecarlo {
public static void main(String[] args) {
        int [][] a = {{42, 12},{55, 21},{19,-2}};
        String[] x = openOrSenior(a);    //this would be line 20
        System.out.println(Arrays.asList(x));    //here was to see what i'd get if i let it run

    }

    static String[] openOrSenior(int[][] a) {
        int i, j, sum;
        String[] abo = new String[a.length];
        System.out.println(abo.length);
        for (i = 0; i < a.length; i++)
            for (j = 0; j < a[0].length; j++) {
                sum = 0;
                int x = a[i][j];
                sum = sum + x;
                if (sum > 62)
                    abo[i] = "Senior";
                else abo[i] = "Open";
            }   //this would be line 12
        return abo;
    }
}
</code>```

Body:
So, I'm new to programming and I have this exercise where I have to read an int[][] array with the age and a handicap level of people trying to start a membership in a Club, with two categories, Senior and Open.
My job is to read the array for example [[45, 12],[55,21],[19, -2]] where the first int is the age and the second the handicap level. If the age is at least 55 and the handicap level is higher than 7 then the person gets a Senior membership if not he gets an Open one. My idea was to see the int[][] as a matrix and add both numbers (age and level) and if the number is higher than 62 I would classify it as a Senior otherwise as open.
My method looks like this:

public class montecarlo {
    static String[] openOrSenior(int[][] a) {
        int i, j, sum;
        String[] abo = new String[a[0].length];
        for (i = 0; i < a.length; i++)
            for (j = 0; j  62)
                   abo[i] = "Senior";
                else
                   abo[i] = "Open"; //this would be line 12
            }
        return abo;
}

    public static void main(String[] args) {
        int [][] a = {{42, 12},{55, 21},{19,-2}};
        String[] x = openOrSenior(a);    //this would be line 20
        Out.print(x);    //here was to see what i'd get if i let it run

    }
}

This is the error i get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
     at montecarlo.openOrSenior(montecarlo.java:12)      at
  montecarlo.main(montecarlo.java:20)

I would really appreciate some help.

Body:
Try something like

public class montecarlo {
public static void main(String[] args) {
        int [][] a = {{42, 12},{55, 21},{19,-2}};
        String[] x = openOrSenior(a);    //this would be line 20
        System.out.println(Arrays.asList(x));    //here was to see what i'd get if i let it run

    }

    static String[] openOrSenior(int[][] a) {
        int i, j, sum;
        String[] abo = new String[a.length];
        System.out.println(abo.length);
        for (i = 0; i < a.length; i++)
            for (j = 0; j < a[0].length; j++) {
                sum = 0;
                int x = a[i][j];
                sum = sum + x;
                if (sum > 62)
                    abo[i] = "Senior";
                else abo[i] = "Open";
            }   //this would be line 12
        return abo;
    }
}


问:
Angular2 Component variable being modified by multiple promises
I have a searchbox which is querying the server on keydown event, as long as the query string is longer then 2 characters. Code below is typescript and from my search component. entries.items is directly used in the template html for this component. The code is stripped down from other stuff focusing on the problem area.

```<code>public Search(query: string)
{
        if (query && query.length > 2)
        {
            var ref = this;
            ref.entries.items = [];

            this.SearchService.Search(query).then(response => {
                let list = JSON.parse(response._body).items;
                list.forEach(element => {
                    ref.entries.items.push(element.details);
                });
            });
        }
 }
</code>```

When the user keeps on typing to get the final work (ex: s - st - sta- stac - stack) we keep on querying and end up in a state where the items are modified multiple times and I'm seeing the same result appended multiple times (ex: if there's one result for stack - it's displayed for sta, stac and stack search queries) - so we're in a state of promises returning and simultaneously modifying the items. It kind of feels like I need a lock, but I'm guessing there's a better way of doing this. Any recommendations?

答:
Or even better solution:</p>

```<code>this.form.get('searchbox')
        .valueChanges
        .debounceTime(400)
        .distinctUntilChanged()
        .switchMap(query => Observable.fromPromise(SearchService.Search(query)))
        .subscribe(value => console.log(value));
</code>```

Body:
I have a searchbox which is querying the server on keydown event, as long as the query string is longer then 2 characters. Code below is typescript and from my search component. entries.items is directly used in the template html for this component. The code is stripped down from other stuff focusing on the problem area.

public Search(query: string)
{
        if (query && query.length > 2)
        {
            var ref = this;
            ref.entries.items = [];

            this.SearchService.Search(query).then(response => {
                let list = JSON.parse(response._body).items;
                list.forEach(element => {
                    ref.entries.items.push(element.details);
                });
            });
        }
 }

When the user keeps on typing to get the final work (ex: s - st - sta- stac - stack) we keep on querying and end up in a state where the items are modified multiple times and I'm seeing the same result appended multiple times (ex: if there's one result for stack - it's displayed for sta, stac and stack search queries) - so we're in a state of promises returning and simultaneously modifying the items. It kind of feels like I need a lock, but I'm guessing there's a better way of doing this. Any recommendations?

Body:
Or even better solution:

this.form.get('searchbox')
        .valueChanges
        .debounceTime(400)
        .distinctUntilChanged()
        .switchMap(query => Observable.fromPromise(SearchService.Search(query)))
        .subscribe(value => console.log(value));


问:
Replacing string with Regex with start and end tags with Java replace function
I have a mathematical formulas string like this.

```<code>(##type## * 2) + 5 + ##component## + ##param##
</code>```

After replacing, I want to get like this.

```<code>((value.type) * 2) + 5 + (value.component) + (value.param)
</code>```

I will always add the "value." string to the begining of the parameters and add both side (). How can i do this?

答:
You can do it by chaining replaceAll methods, e.g.:

```<code>class Value {
    String type;
    String component;
    String param;
    //Getters and setters
}

public static void main(String[] args) {
    String s = "(##type## * 2) + 5 + ##component## + ##param##";
    Value value = new Value();
    value.type = "a";
    value.component = "b";
    value.param = "c";
    s = s.replace("##type##", value.type).replaceAll("##component##", value.component).replaceAll("##param##",
            value.param);
    System.out.println(s);
}
</code>```

Body:
I have a mathematical formulas string like this.

(##type## * 2) + 5 + ##component## + ##param##

After replacing, I want to get like this.

((value.type) * 2) + 5 + (value.component) + (value.param)

I will always add the "value." string to the begining of the parameters and add both side (). How can i do this?

Body:
You can do it by chaining replaceAll methods, e.g.:

class Value {
    String type;
    String component;
    String param;
    //Getters and setters
}

public static void main(String[] args) {
    String s = "(##type## * 2) + 5 + ##component## + ##param##";
    Value value = new Value();
    value.type = "a";
    value.component = "b";
    value.param = "c";
    s = s.replace("##type##", value.type).replaceAll("##component##", value.component).replaceAll("##param##",
            value.param);
    System.out.println(s);
}


问:
Rendering JFreeChart to PDF and Rectangle2D Import Confusion
I am trying to render a timeline chart to a PDF file. Following various examples I need to create a Rectangle2D object.

```<code>import com.itextpdf.awt.geom.Rectangle2D;

PdfTemplate tp=cb.createTemplate(width,height);
Graphics2D g2D=new PdfGraphics2D(cb,width,height);
Rectangle2D r2D=new Rectangle2D.Double(0,0,width,height);
Chart.getInstance().getChart().draw(g2D,r2D);
</code>```

My IDE (Eclipse Oxygen) does not like that and wants Rectangle2D from java.awt.geom.Rectangle2D instead. The 'draw' method is flagged with the error:

The method draw(java.awt.Graphics2D, java.awt.geom.Rectangle2D) in the type JFreeChart is not applicable for the arguments (java.awt.Graphics2D, com.itextpdf.awt.geom.Rectangle2D)

How do I resolve this? TIA.

答: This turned out to be an IDE issue. When I let Eclipse automatically add the import to use java.awt rather than com.itextpdf it resulted in an error when I tried to create the Rectangle2D object. This was why I thought the problem was with the chart.draw method. However, when I added the import for java.awt manually the error on Rectangle went away. The result was a error free compile but now I have an exception that I do not understand so I will create a new thread for that.</p>

Body:
I am trying to render a timeline chart to a PDF file. Following various examples I need to create a Rectangle2D object.

import com.itextpdf.awt.geom.Rectangle2D;

PdfTemplate tp=cb.createTemplate(width,height);
Graphics2D g2D=new PdfGraphics2D(cb,width,height);
Rectangle2D r2D=new Rectangle2D.Double(0,0,width,height);
Chart.getInstance().getChart().draw(g2D,r2D);

My IDE (Eclipse Oxygen) does not like that and wants Rectangle2D from java.awt.geom.Rectangle2D instead. The 'draw' method is flagged with the error:

The method draw(java.awt.Graphics2D, java.awt.geom.Rectangle2D) in the type JFreeChart is not applicable for the arguments (java.awt.Graphics2D, com.itextpdf.awt.geom.Rectangle2D)

How do I resolve this? TIA.


问:
HTML table - Change the width of a single cell in a column
Is there a more elegant solution to achieve the same effect as this?

The code I've got so far is this:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Table Test</title>
    <style type="text/css">
      table { border-collapse: collapse; }
      td { border: solid 1px; }
      td.nest { padding: 0px; }
      td.nest table td { border-width: 0px 1px; }
      td.nest table td:first-child { border-left: none; }
      td.nest table td:last-child { border-right: none; }
    </style>
  </head>
  <body>
    <table>
      <colgroup>
        <col style="width: 3em;"/>
        <col style="width: 6em;"/>
        <col style="width: 9em;"/>
      </colgroup>
      <tr><td>1</td><td>2</td><td>3</td></tr>
      <tr><!-- Somehow get rid of the nested table and keep just the tds -->
        <td class="nest" colspan="3">
          <table>
            <tr>
              <td style="width: 4em;">1</td>
              <td style="width: 6em;">2</td>
              <td style="width: 8em;">3</td>
            </tr>
          </table>
        </td>
      </tr>
      <tr><td>1</td><td>2</td><td>3</td></tr>
    </table>
  </body>
</html>
</code>```

The only way I can get this working so far is to nest another table inside the first. I don't like it much because ideally I only want one table and there's a lot of extra CSS to match the borders of the first table without adding to the cell (colspan="3") size. I want to be able to replace the nested table with just a normal
 with three s in it.

The only other way I've found to change the width of one cell without affecting the other cells in the column is with position: absolute; but then the next cell in the row is shifted to the left by the width of the adjusted cell, so that doesn't work fully. It's also too hard to get the widths just right.

So, is there any way to get the same effect using just one table, no extra
s, etc. and just simple CSS? This example should have only one
, nine s and no colspan=s. I'm looking for a pure CSS solution if one exists. It should be able to cope with any arbitrary widths as long as they add up to the original width.

答:
You can use next html for example :</p>

```<code><table style="width: 300px;">
    <colgroup>
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
    </colgroup>
    <tbody>
        <tr>
            <td></td>
            <td colspan="3"></td>
            <td colspan="2"></td>
        </tr>
        <tr>
            <td colspan="3"></td>
            <td colspan="2"></td>
            <td></td>
        </tr>
        <tr>
            <td colspan="2"></td>
            <td colspan="2"></td>
            <td colspan="2"></td>
        </tr>
    </tbody>
</table>
</code>```

Body:
Is there a more elegant solution to achieve the same effect as this?

The code I've got so far is this:

<!DOCTYPE html>

    <title>Table Test</title>

      <colgroup>
        <col style="width: 3em;"/>
        <col style="width: 6em;"/>
        <col style="width: 9em;"/>
      </colgroup>

1	2	3

              1
              2
              3

1	2	3

The only way I can get this working so far is to nest another table inside the first. I don't like it much because ideally I only want one table and there's a lot of extra CSS to match the borders of the first table without adding to the cell (colspan="3") size. I want to be able to replace the nested table with just a normal
 with three s in it.

The only other way I've found to change the width of one cell without affecting the other cells in the column is with position: absolute; but then the next cell in the row is shifted to the left by the width of the adjusted cell, so that doesn't work fully. It's also too hard to get the widths just right.

So, is there any way to get the same effect using just one table, no extra
s, etc. and just simple CSS? This example should have only one
, nine s and no colspan=s. I'm looking for a pure CSS solution if one exists. It should be able to cope with any arbitrary widths as long as they add up to the original width.

Body:
You can use next html for example :

<table style="width: 300px;">
    <colgroup>
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
        <col span="1" style="width: auto;">
    </colgroup>
    <tbody>
        <tr>
            <td></td>
            <td colspan="3"></td>
            <td colspan="2"></td>
        </tr>
        <tr>
            <td colspan="3"></td>
            <td colspan="2"></td>
            <td></td>
        </tr>
        <tr>
            <td colspan="2"></td>
            <td colspan="2"></td>
            <td colspan="2"></td>
        </tr>
    </tbody>
</table>


问:
Return Code on failure. Positive or negative?
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;
</code>```

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

```<code>char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;
</code>```

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.

答:
The convention for a not further specified error code from your program is to use EXIT_FAILURE. It will be defined to a value your OS recognizes as a failure exit code.

The macros defined in errno.h are not meant as return codes for processes but only for errors during program execution. The standard library will put them in the global errno, you could also use them as return codes from functions if you like. Three of them are specified by the C standard: EDOM, EILSEQ and ERANGE. A lot more are specified by POSIX. Do not use these as return codes from main() (or as argument to exit()).

Body:
a C-programm can fail to execute under special circumstances in Linux.
Example: You allocate some space and the OS denies it.

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return ENOMEM;

This failure is marked by the return code which is delivered to the OS.

A return code of 0 (EXIT_SUCCESS) is marked as a successful execution.

A return code which is not 0, is marked as a failure.

So my question is, what is the convention, when a program detects an error.
Should it return a positive or a negative return code ?

My professor told me in UNIX/Linux allways to return a negative error code. But the errno-Codes are all positive integers. Also the define-Statement of EXIT_FAILURE in  is 1, a positive integer.
So should my code look like this:

char *buffer = (char *) malloc(1024);
if (buffer == NULL)
    return -ENOMEM;

or like the code above? I know from Linux-Kernel-Modules that in most cases they return a negative error code on failure.

Thanks for helping.


问:
jenkins behind nginx reverse proxy
I'm trying to keep a jenkins container(docker) behind nginx reverse proxy. It works fine with this path, https://example.com/ but it returns 502 Bad Gateway when I add parameter to the path, https://example.com/jenkins.

The docker container for jenkins is run like this
docker container run -d -p 127.0.0.1:8080:8080 jenkins/jenkins

Here is my code,

```<code>server {
        listen 80;
        root /var/www/html;

        server_name schoolcloudy.com www.schoolcloudy.com;

        location / {
             proxy_pass http://localhost:8000;
        }

}

# Virtual Host configuration for example.com
upstream jenkins {
    server 127.0.0.1:8080;
}
server {
    listen 80;
    server_name jenkins;
    location /jenkins {
        proxy_pass http://jenkins;
        proxy_redirect  127.0.0.1:8080 https://schoolcloudy.com/jenkins;

    }
}
</code>```

答: Specify the Jenkins container's network with --network=host flag when you run the container. This way the container will be able to interact with host network or use the container's IP explicitly in the Nginx conf.

Title: jenkins behind nginx reverse proxy

Body:
I'm trying to keep a jenkins container(docker) behind nginx reverse proxy. It works fine with this path, https://example.com/ but it returns 502 Bad Gateway when I add parameter to the path, https://example.com/jenkins.

The docker container for jenkins is run like this
docker container run -d -p 127.0.0.1:8080:8080 jenkins/jenkins

Here is my code,

server {
        listen 80;
        root /var/www/html;

        server_name schoolcloudy.com www.schoolcloudy.com;

        location / {
             proxy_pass http://localhost:8000;
        }

}

# Virtual Host configuration for example.com
upstream jenkins {
    server 127.0.0.1:8080;
}
server {
    listen 80;
    server_name jenkins;
    location /jenkins {
        proxy_pass http://jenkins;
        proxy_redirect  127.0.0.1:8080 https://schoolcloudy.com/jenkins;

    }
}


问:
Perl Parsing CSV Efficient with Embedded Commas and Adding To Database
How do you apply regular expressions to an array. While reading in my csv file I applied this...

```<code>        s/, /- /g;
        s/1,000/1000/g;
</code>```

But after I put the data in my multidimensional array I don't know how to insert the commas back to my fields.

答: For parsing CSV, use a CPAN module like Text::CSV. You can the use the regex on the values returned.

Body:
How do you apply regular expressions to an array. While reading in my csv file I applied this...

        s/, /- /g;
        s/1,000/1000/g;

But after I put the data in my multidimensional array I don't know how to insert the commas back to my fields.


问:
How to get the user to auto fill framework setting screen pro-grammatically in android 8.0
I want to get the user to auto-fill framework settings screen to enable the AutoFill framework to auto-fill the login form in third-party apps.

So, how can I get the user programmatically to the auto-fill settings screen in Oreo devices?

答:
Prerequistes:

User must to Enable the Autofill service.
Settings > System > Languages & input > Advanced > Input assistance > Autofill service.

1.Providing hints for autofill

autofill service classify the data correctly by providing the meaning of each view that could be autofillable, such as views representing usernames and passwords.

xml :

```<code>android:autofillHints="AUTOFILL_HINT_USERNAME"
</code>```

or

Java    :

```<code>editText.setAutofillHints(View.AUTOFILL_HINT_USERNAME);
</code>```

2. Force an autofill request

```<code>AutofillManager afm = getSystemService(AutofillManager.class);
if (afm != null) {
    if (afm.isEnabled()) {   //for afmanager is enabled or not
        afm.requestAutofill(editText);
    }
}
</code>```

Body:
Prerequistes:

User must to Enable the Autofill service.
Settings > System > Languages & input > Advanced > Input assistance > Autofill service.

1.Providing hints for autofill

autofill service classify the data correctly by providing the meaning of each view that could be autofillable, such as views representing usernames and passwords.

xml :

android:autofillHints="AUTOFILL_HINT_USERNAME"

or

Java    :

editText.setAutofillHints(View.AUTOFILL_HINT_USERNAME);

2. Force an autofill request

AutofillManager afm = getSystemService(AutofillManager.class);
if (afm != null) {
    if (afm.isEnabled()) {   //for afmanager is enabled or not
        afm.requestAutofill(editText);
    }
}


问:
Programmatically add arguments to a Promise
I need to create a function that receives a Promise as a first parameter and an array of its parameters (if it has at least one) or null if none.

My function looks this way:

```<code>var executeMappingStep = (promiseStatus, myPromise, myPromiseParams) => {
    return new Promise((resolve, reject) => {
        //if the execution was success, there's no need to invoke myPromise again
        if(promiseStatus.success == true)
           return resolve(promiseStatus.previousResponseSaved);

        if (myPromiseParams!= null) {
            //how I resolve this logic is my doubt
            myPromise.addArrayOfParameters(myPromiseParams);
        }

        myPromise().then(result => resolve(result)).catch(err => reject(err));
    });
};
</code>```

I was reading about the .bind() function which works for functions but not for promises according to this question. I also saw something about the .apply() function, but this doesn't seems to be what I need.

Edit

My function is invoked like myFirstPromise when there aren't parameters, and like mySecondPromise when I have at least one:

```<code>var executePromises = (myFirstPromise, mySecondPromisePromise) => {
    return new Promise((resolve, reject) => {
        //retrieve an array of every promise status
        var promisesStatus = getPromisesStatus();

        executeMappingStep(promisesStatus[0], myFirstPromise, null).then(result => {
                return convertToXml(result);
        }).then(result => {

            var parameters = {
                value1 : result,
                value2: [1,2,3],
                value3: "some string",
                value4: 10
            };

            return executeMappingStep(promisesStatus[1], mySecondPromisePromise, parameters);
        }).then(result => resolve(result)).catch(err => reject(err));
    });
};

var myFirstPromise = function() {
    return new Promise(function (resolve, reject) {
        //some logic for first promise
    });
}

var mySecondPromise = function(firstParam, secondParam, thirdParam, fourthParam) {
    return new Promise(function (resolve, reject) {
        //some logic for second promise with its params
    });
}
</code>```

Probably, in the function addArrayOfParameters I need to loop into every property on the object (I realized that an array would not work), like this

Is there a way to programmatically add parameters from an array before its resolved?

Edit 2

The reason behind this logic is much complex, but this is pretty much what I need to solve. Basically, in my code, every promise can be executed with errors and there's a logic involved in the executePromises function which returns the status of every promise whether was successfully executed or not. This logic involves more than 10 promises chained, and if some of them fail e.g: promise number 5, then 6,7 etc, will have to be invoked again in some admin backend.

I don't what to replicate the logic for each promise, so that's why I wanted to create the executeMappingStep function to encapsulate that logic.
Probably is hard to explain, I tried to simplify the most as I could. I made a few more changes to explain what I just said.

答:
Probably use async library may resolve your issue. Try to run code on your console and look into that.

With async library:

```<code>var async = require("async");
async.waterfall([
    function (callback) {
        var methodParam = [1, 2, 3];
        console.log("first method called");
        callback(null, methodParam);
    },
    function (methodParams, callback) {
        var newParams = [4, 5, 6];
        newParams = methodParams.concat(newParams);
        console.log("second method called", methodParams);
        callback(null, newParams);
    }
], function (err, res) {
    if (err) {
        console.log("error occured");
    } else {
        console.log("final result", res);
    }
});
</code>```

With promise:

```<code>var promise1 = (() => {
    return new Promise((resolve, reject) => {
        var methodParam = [1, 2, 3];
        console.log("first promise called");
        resolve(methodParam);
    });
});

var promise2 = ((methodParams) => {
    return new Promise((resolve, reject) => {
        var newParams = [4, 5, 6];
        newParams = methodParams.concat(newParams);
        console.log("second promise called", methodParams);
        resolve(newParams);
    });
});

promise1()
    .then((resPromise1) => {
        return promise2(resPromise1);
    }).then((resPromise2) => {
        console.log("final result", resPromise2);
    });
</code>```

Body:
I need to create a function that receives a Promise as a first parameter and an array of its parameters (if it has at least one) or null if none.

My function looks this way:

var executeMappingStep = (promiseStatus, myPromise, myPromiseParams) => {
    return new Promise((resolve, reject) => {
        //if the execution was success, there's no need to invoke myPromise again
        if(promiseStatus.success == true)
           return resolve(promiseStatus.previousResponseSaved);

        if (myPromiseParams!= null) {
            //how I resolve this logic is my doubt
            myPromise.addArrayOfParameters(myPromiseParams);
        }

        myPromise().then(result => resolve(result)).catch(err => reject(err));
    });
};

I was reading about the .bind() function which works for functions but not for promises according to this question. I also saw something about the .apply() function, but this doesn't seems to be what I need.

Edit

My function is invoked like myFirstPromise when there aren't parameters, and like mySecondPromise when I have at least one:

var executePromises = (myFirstPromise, mySecondPromisePromise) => {
    return new Promise((resolve, reject) => {
        //retrieve an array of every promise status
        var promisesStatus = getPromisesStatus();

        executeMappingStep(promisesStatus[0], myFirstPromise, null).then(result => {
                return convertToXml(result);
        }).then(result => {

            var parameters = {
                value1 : result,
                value2: [1,2,3],
                value3: "some string",
                value4: 10
            };

            return executeMappingStep(promisesStatus[1], mySecondPromisePromise, parameters);
        }).then(result => resolve(result)).catch(err => reject(err));
    });
};

var myFirstPromise = function() {
    return new Promise(function (resolve, reject) {
        //some logic for first promise
    });
}

var mySecondPromise = function(firstParam, secondParam, thirdParam, fourthParam) {
    return new Promise(function (resolve, reject) {
        //some logic for second promise with its params
    });
}

Probably, in the function addArrayOfParameters I need to loop into every property on the object (I realized that an array would not work), like this

Is there a way to programmatically add parameters from an array before its resolved?

Edit 2

The reason behind this logic is much complex, but this is pretty much what I need to solve. Basically, in my code, every promise can be executed with errors and there's a logic involved in the executePromises function which returns the status of every promise whether was successfully executed or not. This logic involves more than 10 promises chained, and if some of them fail e.g: promise number 5, then 6,7 etc, will have to be invoked again in some admin backend.

I don't what to replicate the logic for each promise, so that's why I wanted to create the executeMappingStep function to encapsulate that logic.
Probably is hard to explain, I tried to simplify the most as I could. I made a few more changes to explain what I just said.

Body:
Probably use async library may resolve your issue. Try to run code on your console and look into that.

With async library:

var async = require("async");
async.waterfall([
    function (callback) {
        var methodParam = [1, 2, 3];
        console.log("first method called");
        callback(null, methodParam);
    },
    function (methodParams, callback) {
        var newParams = [4, 5, 6];
        newParams = methodParams.concat(newParams);
        console.log("second method called", methodParams);
        callback(null, newParams);
    }
], function (err, res) {
    if (err) {
        console.log("error occured");
    } else {
        console.log("final result", res);
    }
});

With promise:

var promise1 = (() => {
    return new Promise((resolve, reject) => {
        var methodParam = [1, 2, 3];
        console.log("first promise called");
        resolve(methodParam);
    });
});

var promise2 = ((methodParams) => {
    return new Promise((resolve, reject) => {
        var newParams = [4, 5, 6];
        newParams = methodParams.concat(newParams);
        console.log("second promise called", methodParams);
        resolve(newParams);
    });
});

promise1()
    .then((resPromise1) => {
        return promise2(resPromise1);
    }).then((resPromise2) => {
        console.log("final result", resPromise2);
    });


问:
Antd Menu.SubMenu keeps collapsing on hover
I am having trouble with the Antd submenu. If I use the code below, the submenu opens on hover, but it will close again if the mouse is not exactly hovering the link in the first item.

Any idea what I can do about this? I'm using v3.0.0-beta.5

Here is a screen recording:

https://www.dropbox.com/s/jdxakivocf5atgs/antd-submenu-bug.mov?dl=0

Maybe it's just a bug in the beta version, but submitting an issue to the antd repo requires a lot of effort unfortunately and doesn't even include 3.0 in their app and fork boilerplate.

```<code>import React from 'react';
import { Link } from 'react-router-dom';
import { Menu, Avatar } from 'antd';
const { SubMenu, Item, Divider } = Menu;
import styled from 'styled-components';

const Box = styled.span`
  position: relative;
  display: flex;
  align-items: center;
  height: 64px;
`;

interface INavigationProps {
  onLogout: () => any;
  isAuthed: boolean;
  avatar?: string;
}

export const Navigation: React.SFC<INavigationProps> = ({
  isAuthed,
  onLogout,
  avatar,
}) =>
  isAuthed && (
    <Menu mode="horizontal" style={{ lineHeight: '64px' }}>
      <Item key="admin">
        <Link to="/admin">admin</Link>
      </Item>
      <SubMenu
        key="user"
        mode="inline"
        title={
          <Box>
            <Avatar src={avatar} icon="user" />
          </Box>
        }
      >
        <Item key="user.profile">
          <Link to="/profile">profile</Link>
        </Item>
        <Divider />
        <Item key="user.logout">
          <Link to="/" onClick={onLogout}>
            logout
          </Link>
        </Item>
      </SubMenu>
    </Menu>
  );

export default Navigation;
</code>```

答: The problem has since disappeared after upgrading (now beta.6)</p>

Body:
I am having trouble with the Antd submenu. If I use the code below, the submenu opens on hover, but it will close again if the mouse is not exactly hovering the link in the first item.

Any idea what I can do about this? I'm using v3.0.0-beta.5

Here is a screen recording:

https://www.dropbox.com/s/jdxakivocf5atgs/antd-submenu-bug.mov?dl=0

Maybe it's just a bug in the beta version, but submitting an issue to the antd repo requires a lot of effort unfortunately and doesn't even include 3.0 in their app and fork boilerplate.

import React from 'react';
import { Link } from 'react-router-dom';
import { Menu, Avatar } from 'antd';
const { SubMenu, Item, Divider } = Menu;
import styled from 'styled-components';

const Box = styled.span`
  position: relative;
  display: flex;
  align-items: center;
  height: 64px;
`;

interface INavigationProps {
  onLogout: () => any;
  isAuthed: boolean;
  avatar?: string;
}

export const Navigation: React.SFC<INavigationProps> = ({
  isAuthed,
  onLogout,
  avatar,
}) =>
  isAuthed && (
    <Menu mode="horizontal" style={{ lineHeight: '64px' }}>
      <Item key="admin">
        <Link to="/admin">admin</Link>
      </Item>
      <SubMenu
        key="user"
        mode="inline"
        title={
          <Box>
            <Avatar src={avatar} icon="user" />
          </Box>
        }
      >
        <Item key="user.profile">
          <Link to="/profile">profile</Link>
        </Item>
        <Divider />
        <Item key="user.logout">
          <Link to="/" onClick={onLogout}>
            logout
          </Link>
        </Item>
      </SubMenu>
    </Menu>
  );

export default Navigation;


答:
This fixes all the array bounds problems, but as others mentioned, not the flaws in the semantics. It makes no sense to completely rewrite this answer, so I keep it as it is.

I noticed two major problems in your code that could cause said exception.

On line 12, your problem is, you define the array size wrong.

```<code>String[] abo = new String[a.length];
</code>```

But there is one more problem like that, as the second cycle takes incorrect length, you need:

```<code>for (j = 0; j < a[i].length; j++ )
</code>```

OK, this problem should never happen as all your arrays have same length. But should there be someone with no handicap as just {31} alongside someone with handicap, it crashes in the cycle.

For next practice - create a new class that has two int variables, age and handicap. That is how you do it in Java. An array of integers makes no difference what is age and what is handicap.

Title: multiple int[][] array to single[] String array in java

Body:
This fixes all the array bounds problems, but as others mentioned, not the flaws in the semantics. It makes no sense to completely rewrite this answer, so I keep it as it is.

I noticed two major problems in your code that could cause said exception.

On line 12, your problem is, you define the array size wrong.

String[] abo = new String[a.length];

But there is one more problem like that, as the second cycle takes incorrect length, you need:

for (j = 0; j < a[i].length; j++ )

OK, this problem should never happen as all your arrays have same length. But should there be someone with no handicap as just {31} alongside someone with handicap, it crashes in the cycle.

For next practice - create a new class that has two int variables, age and handicap. That is how you do it in Java. An array of integers makes no difference what is age and what is handicap.


问:
Equivalent function to stringr::word in stringi package
I went through the stringi package manual to find an equivalent to the function word() in the package stringr, but I could not find it. The reason I am looking for it is because I want to set collation options for my locale  and stringr doesn't give me all the options that stringi does. Is there a function in the stringi package that does the same as the word() function in the stringr package? See the example below, where I want the next three words after the word "José", that is written in different ways. In the stringi package, the function stri_opts_collatorallows to set the argument strength=1 for a permissive collation strength, so all forms of "José" would have been taken into consideration.

```<code>sentencas<-c("josé é um trabalhador responsável","José é um trabalhador
responsável","jose é um trabalhador responsável","Jose é um trabalhador
responsável")

sentencas %>% word(2,sep=coll("jose ",ignore_case=T)) %>% word(1,3)
</code>```

With stringi, I can extract all forms of "José":

```<code>stri_extract_first_coll(sentencas,"jose",strength=1).
</code>```

I would like to do something like this:

```<code>sentencas %>% word(2,sep=coll("jose ",strength=1)) %>% word(1,3)
</code>```

答:
word() is a pretty complex function with no single function equivalent in stringi. This is another way to achieve your desired results:

```<code>library(stringi)
library(purrr)

sentencas <- c("josé é um trabalhador responsável",
               "José é um trabalhador responsável",
               "jose é um trabalhador responsável",
               "Jose é um trabalhador responsável")

sentencas %>%
  map(stri_extract_all_words) %>%
  map(~{
    .x <- flatten_chr(.x)
    map(.x, stri_detect_coll, "jose", ignore.case=TRUE, strength=1L) %>%
      flatten_lgl() %>%
      which() -> pos
    .x[(pos+1):(pos+1+3)]
  })
## [[1]]
## [1] "é"           "um"          "trabalhador"
##
## [[2]]
## [1] "é"           "um"          "trabalhador"
##
## [[3]]
## [1] "é"           "um"          "trabalhador"
##
## [[4]]
## [1] "é"           "um"          "trabalhador"
</code>```

Body:
I went through the stringi package manual to find an equivalent to the function word() in the package stringr, but I could not find it. The reason I am looking for it is because I want to set collation options for my locale  and stringr doesn't give me all the options that stringi does. Is there a function in the stringi package that does the same as the word() function in the stringr package? See the example below, where I want the next three words after the word "José", that is written in different ways. In the stringi package, the function stri_opts_collatorallows to set the argument strength=1 for a permissive collation strength, so all forms of "José" would have been taken into consideration.

sentencas<-c("josé é um trabalhador responsável","José é um trabalhador
responsável","jose é um trabalhador responsável","Jose é um trabalhador
responsável")

sentencas %>% word(2,sep=coll("jose ",ignore_case=T)) %>% word(1,3)

With stringi, I can extract all forms of "José":

stri_extract_first_coll(sentencas,"jose",strength=1).

I would like to do something like this:

sentencas %>% word(2,sep=coll("jose ",strength=1)) %>% word(1,3)

Body:
word() is a pretty complex function with no single function equivalent in stringi. This is another way to achieve your desired results:

library(stringi)
library(purrr)

sentencas <- c("josé é um trabalhador responsável",
               "José é um trabalhador responsável",
               "jose é um trabalhador responsável",
               "Jose é um trabalhador responsável")

sentencas %>%
  map(stri_extract_all_words) %>%
  map(~{
    .x <- flatten_chr(.x)
    map(.x, stri_detect_coll, "jose", ignore.case=TRUE, strength=1L) %>%
      flatten_lgl() %>%
      which() -> pos
    .x[(pos+1):(pos+1+3)]
  })
## [[1]]
## [1] "é"           "um"          "trabalhador"
##
## [[2]]
## [1] "é"           "um"          "trabalhador"
##
## [[3]]
## [1] "é"           "um"          "trabalhador"
##
## [[4]]
## [1] "é"           "um"          "trabalhador"


问:
jQuery IF statement not working
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".

All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/

```<code>function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);
  }
 });

 var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }

}
</code>```

答:
Any code that relies on the response from the AJAX request, must be called inside a callback to the request.

```<code>function check_name() {
    $.ajax({
        type: "POST",
        url: "http://localhost/Framework/library/php_files/check_car_name.php",
        data: "carName=" + document.getElementById("carName").value,
        success: function (html) {
            $("#checkname").html(html);

             // I placed your code here instead.
             // Of course you wouldn't need to set and then get the HTML,
             //    since you could just do a direct comparison.
            var currentHtml = $("#checkname").html();
            var compareString = "Car name unavailable";
            if (currentHtml == compareString) {
                $("#submit").hide();
            } else {
                $("#submit").show();
            }
        }
    });
}
</code>```

The reason is that by default, an AJAX request is asynchronous, which means that the code that comes after the request will execute immediately instead of waiting for the response to return.

Another possible issue when comparing HTML to keep in mind is white space. If you're doing a string comparison, it must be exactly the same, so if there's whitespace, you'll need to trim it first. You can use jQuery.trim()(docs) to do this.

Title: jQuery IF statement not working

Body:
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".

All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/

function check_name(){

 $.ajax({
  type: "POST",
  url: "http://localhost/Framework/library/php_files/check_car_name.php",
  data:  "carName=" + document.getElementById("carName").value,
  success: function(html){
   $("#checkname").html(html);
  }
 });

 var currentHtml = $("#checkname").html();
 var compareString = "Car name unavailable";

 if (currentHtml==compareString) {
  $("#submit").hide();
 } else {
  $("#submit").show();
 }

}

Body:
Any code that relies on the response from the AJAX request, must be called inside a callback to the request.

function check_name() {
    $.ajax({
        type: "POST",
        url: "http://localhost/Framework/library/php_files/check_car_name.php",
        data: "carName=" + document.getElementById("carName").value,
        success: function (html) {
            $("#checkname").html(html);

             // I placed your code here instead.
             // Of course you wouldn't need to set and then get the HTML,
             //    since you could just do a direct comparison.
            var currentHtml = $("#checkname").html();
            var compareString = "Car name unavailable";
            if (currentHtml == compareString) {
                $("#submit").hide();
            } else {
                $("#submit").show();
            }
        }
    });
}

The reason is that by default, an AJAX request is asynchronous, which means that the code that comes after the request will execute immediately instead of waiting for the response to return.

Another possible issue when comparing HTML to keep in mind is white space. If you're doing a string comparison, it must be exactly the same, so if there's whitespace, you'll need to trim it first. You can use jQuery.trim()(docs) to do this.


问:
Why is Travis not recognising installed CMake in script?
I'm trying to put together a Travis CI script for my application, which requires CMake 3.5 or greater. The entire Travis script can be found here. Following advice I found elsewhere, I use the following to install CMake:

```<code> install:
    - DEPS_DIR="${TRAVIS_BUILD_DIR}/deps"
    - mkdir -p ${DEPS_DIR} && cd ${DEPS_DIR}

    - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
        CMAKE_URL="https://cmake.org/files/v3.7/cmake-3.7.2-Linux-x86_64.tar.gz";
        mkdir cmake && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake;
        export PATH=${DEPS_DIR}/cmake/bin:${PATH};
      else
        brew outdated cmake || brew upgrade cmake;
      fi
    - cmake --version
</code>```

Then I fill out the build matrix with various OS/compiler combinations, and finally I run a Python installation script (see here):

```<code>before_script:
    - cd "${TRAVIS_BUILD_DIR}"

script:
    - ./install.py --compiler=$COMPILER
</code>```

The Python script essentially just calls cmake and make, the first CMakeLists.txt can be found here.

The OSX builds which install CMake using Homebrew works perfectly. However, all of the Linux builds fail at the script stage due to CMake not meeting the minimum requirement:

```<code>CMake Error at CMakeLists.txt:1 (cmake_minimum_required):
  CMake 3.5 or higher is required.  You are running version 3.2.2
</code>```

Even though CMake 3.7 was successfully installed during install:

```<code>$ cmake --version
cmake version 3.7.2
</code>```

What am I doing wrong?

答:
This is strange, the preinstalled version of CMake (= v3.2 on Travis) is used instead of the newer one – but only when called from Python.

You can try these:

Solution 1: Remove the CMake shipped by Travis

This will prevent the usage of the older version. If this doesn't work (eg. maybe because "Cmake isn't found"), this will show the actual reason of the problem.

You can add this to your linux branch of the install  step:

```<code>sudo apt-get purge cmake
</code>```

Or:

```<code>sudo apt-get remove cmake
</code>```

(Possible you need to add -y for confirmation, so it becomes remove -y).

Solution 2: Use the CMake installer

Installation through the CMake Installer is a much cleaner way. It turned out the be the faster one on Travis btw.

```<code>...
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
    CMAKE_INSTALLER=install-cmake.sh
    curl -sSL https://cmake.org/files/v3.7/cmake-3.7.2-Linux-x86_64.sh -o ${CMAKE_INSTALLER}
    chmod +x ${CMAKE_INSTALLER}
    sudo ./${CMAKE_INSTALLER} --prefix=/usr/local --skip-license
  else
    ...
</code>```

I'm using curl instead of wget + travis_retry, but this doesn't matter. You can still use them as before.

If both don't work, you should check where the Python script looks for executables.

Body:
I'm trying to put together a Travis CI script for my application, which requires CMake 3.5 or greater. The entire Travis script can be found here. Following advice I found elsewhere, I use the following to install CMake:

 install:
    - DEPS_DIR="${TRAVIS_BUILD_DIR}/deps"
    - mkdir -p ${DEPS_DIR} && cd ${DEPS_DIR}

    - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
        CMAKE_URL="https://cmake.org/files/v3.7/cmake-3.7.2-Linux-x86_64.tar.gz";
        mkdir cmake && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake;
        export PATH=${DEPS_DIR}/cmake/bin:${PATH};
      else
        brew outdated cmake || brew upgrade cmake;
      fi
    - cmake --version

Then I fill out the build matrix with various OS/compiler combinations, and finally I run a Python installation script (see here):

before_script:
    - cd "${TRAVIS_BUILD_DIR}"

script:
    - ./install.py --compiler=$COMPILER

The Python script essentially just calls cmake and make, the first CMakeLists.txt can be found here.

The OSX builds which install CMake using Homebrew works perfectly. However, all of the Linux builds fail at the script stage due to CMake not meeting the minimum requirement:

CMake Error at CMakeLists.txt:1 (cmake_minimum_required):
  CMake 3.5 or higher is required.  You are running version 3.2.2

Even though CMake 3.7 was successfully installed during install:

$ cmake --version
cmake version 3.7.2

What am I doing wrong?

Body:
This is strange, the preinstalled version of CMake (= v3.2 on Travis) is used instead of the newer one – but only when called from Python.

You can try these:

Solution 1: Remove the CMake shipped by Travis

This will prevent the usage of the older version. If this doesn't work (eg. maybe because "Cmake isn't found"), this will show the actual reason of the problem.

You can add this to your linux branch of the install  step:

sudo apt-get purge cmake

Or:

sudo apt-get remove cmake

(Possible you need to add -y for confirmation, so it becomes remove -y).

Solution 2: Use the CMake installer

Installation through the CMake Installer is a much cleaner way. It turned out the be the faster one on Travis btw.

...
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
    CMAKE_INSTALLER=install-cmake.sh
    curl -sSL https://cmake.org/files/v3.7/cmake-3.7.2-Linux-x86_64.sh -o ${CMAKE_INSTALLER}
    chmod +x ${CMAKE_INSTALLER}
    sudo ./${CMAKE_INSTALLER} --prefix=/usr/local --skip-license
  else
    ...

I'm using curl instead of wget + travis_retry, but this doesn't matter. You can still use them as before.

If both don't work, you should check where the Python script looks for executables.


问:
Getting session from another Servlet
I'm trying to store a User object in session in Servlet1. In Servlet2 I'm trying to get the values from the same logged in session from Servlet1.

Servlet1:

```<code>private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("UTF-8");

    String emailFromForm = request.getParameter("email").toLowerCase();
    String passwordFromForm = request.getParameter("passWord");

    try {
        User userThatLogsIn = manager.getUser(emailFromForm);
        String passwordFromDB = userThatLogsIn.getPassword();

        if (passwordFromDB.equals(passwordFromForm)) {
            request.getSession().setAttribute("TheLoggedInUser", userThatLogsIn);
            response.sendRedirect("/Slit/welcome.jsp");
        } else {
            request.setAttribute("error", "Unknown login, try again");
            response.sendRedirect("/Slit/LoginFailed.jsp");
        }
    } catch (NullPointerException nullPointer) {
        System.err.println("NullPointerException: " + nullPointer.getMessage());
        response.sendRedirect("/Slit/LoginFailed.jsp");
    }
}
</code>```

Servlet2:  Im getting a nullpointer sessionaccept fnavn
at Mypage.MyPageServlet.sessionAccept(MyPageServlet.java:40)

```<code>private void sessionAccept(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession();
    session.setMaxInactiveInterval(30 * 60);
    User loggedInUser = (User) request.getAttribute("TheLoggedInUser");
    String fnavn = loggedInUser.getfName();
    String enavn = loggedInUser.getlName();
    String epost = loggedInUser.getEmail();

    request.getSession().setAttribute("messageJSP", "Velkommen" + epost);
    response.sendRedirect("Innstillinger.jsp");

}
</code>```

答:
This line

```<code>User loggedInUser = (User) request.getAttribute("TheLoggedInUser");
</code>```

has to replaced with

```<code>User loggedInUser = (User)
request.getSession().getAttribute("TheLoggedInUser");
</code>```

Title: Getting session from another Servlet

Body:
I'm trying to store a User object in session in Servlet1. In Servlet2 I'm trying to get the values from the same logged in session from Servlet1.

Servlet1:

private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("UTF-8");

    String emailFromForm = request.getParameter("email").toLowerCase();
    String passwordFromForm = request.getParameter("passWord");

    try {
        User userThatLogsIn = manager.getUser(emailFromForm);
        String passwordFromDB = userThatLogsIn.getPassword();

        if (passwordFromDB.equals(passwordFromForm)) {
            request.getSession().setAttribute("TheLoggedInUser", userThatLogsIn);
            response.sendRedirect("/Slit/welcome.jsp");
        } else {
            request.setAttribute("error", "Unknown login, try again");
            response.sendRedirect("/Slit/LoginFailed.jsp");
        }
    } catch (NullPointerException nullPointer) {
        System.err.println("NullPointerException: " + nullPointer.getMessage());
        response.sendRedirect("/Slit/LoginFailed.jsp");
    }
}

Servlet2:  Im getting a nullpointer sessionaccept fnavn
at Mypage.MyPageServlet.sessionAccept(MyPageServlet.java:40)

private void sessionAccept(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession();
    session.setMaxInactiveInterval(30 * 60);
    User loggedInUser = (User) request.getAttribute("TheLoggedInUser");
    String fnavn = loggedInUser.getfName();
    String enavn = loggedInUser.getlName();
    String epost = loggedInUser.getEmail();

    request.getSession().setAttribute("messageJSP", "Velkommen" + epost);
    response.sendRedirect("Innstillinger.jsp");

}

Body:
This line

User loggedInUser = (User) request.getAttribute("TheLoggedInUser");

has to replaced with

User loggedInUser = (User)
request.getSession().getAttribute("TheLoggedInUser");


问:
How to query data from MYSQLdb with Python2.7 if I want query "date-1"?
So, I need to query data from MYSQLdb in every day, that's why I prefer to use a query which one I can query the actual date - 1 data. For example if I run my script today at Nov 13, I need the all information from Nov 12 (from the ACTUAL_DATE - on the picture).

I have got a column in the MYSQLdb, which looks like this :

Is this any query, is this any chance to query data with this "DATE - 1" logic? So I have to analyse the last 6 character in the ACTUAL_DATE columns, because the last 2 show the day, the last 4 show the months (year is not important!)

This MYSQLdb refresh in every day, that's why I need to find a way which one I can query the REAL DATE - 1 day from this table.

I know the code has to looking like this :

```<code>connection = MySQLdb.connect(host='localhost',
        user='user1',
        passwd='',
        db='database1',
        use_unicode=True,
        charset="utf8")
cursor = connection.cursor()
query = """ select #I NEED SOMETHING HERE..
    from OSSZES
    into outfile '/tmp/test.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
    """
cursor.execute(query)
connection.commit()
cursor.close()
</code>```

But how can I write this select query if it is exist in mysqldb?

答:
You can make use off the function STR_TO_DATE to format the VARCHAR format into a DATETIME format.

Query

```<code>SELECT
 *
FROM (
  # test data replace this with your table name
  SELECT
   'Sunday, Nov 12' AS A

  UNION ALL

  SELECT
    'Saturday, Nov 11'
)
 AS records
WHERE
   MONTH(STR_TO_DATE(A, '%W, %b %d')) = MONTH(NOW())
 AND
   DAY(STR_TO_DATE(A, '%W, %b %d')) = DAY(NOW()) - 1
</code>```

Result

```<code>A
----------------
Sunday, Nov 12
</code>```

Body:
So, I need to query data from MYSQLdb in every day, that's why I prefer to use a query which one I can query the actual date - 1 data. For example if I run my script today at Nov 13, I need the all information from Nov 12 (from the ACTUAL_DATE - on the picture).

I have got a column in the MYSQLdb, which looks like this :

Is this any query, is this any chance to query data with this "DATE - 1" logic? So I have to analyse the last 6 character in the ACTUAL_DATE columns, because the last 2 show the day, the last 4 show the months (year is not important!)

This MYSQLdb refresh in every day, that's why I need to find a way which one I can query the REAL DATE - 1 day from this table.

I know the code has to looking like this :

connection = MySQLdb.connect(host='localhost',
        user='user1',
        passwd='',
        db='database1',
        use_unicode=True,
        charset="utf8")
cursor = connection.cursor()
query = """ select #I NEED SOMETHING HERE..
    from OSSZES
    into outfile '/tmp/test.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
    """
cursor.execute(query)
connection.commit()
cursor.close()

But how can I write this select query if it is exist in mysqldb?

Body:
You can make use off the function STR_TO_DATE to format the VARCHAR format into a DATETIME format.

Query

SELECT
 *
FROM (
  # test data replace this with your table name
  SELECT
   'Sunday, Nov 12' AS A

  UNION ALL

  SELECT
    'Saturday, Nov 11'
)
 AS records
WHERE
   MONTH(STR_TO_DATE(A, '%W, %b %d')) = MONTH(NOW())
 AND
   DAY(STR_TO_DATE(A, '%W, %b %d')) = DAY(NOW()) - 1

Result

A
----------------
Sunday, Nov 12


问:
Weird push message received on app start
I'm getting a weird push message captured by my push service:

```<code>Bundle[{CMD=RST_FULL, from=google.com/iid, android.support.content.wakelockid=1}]
</code>```

Just started to happen yesterday and I can't really spot which code change is to blame for this. Has anyone seen this message before and maybe knows where is it coming from and why?

答:
I had this problem during migrating GCM->FCM with receiving only wakelockid element from:

firebase console

reproduced request by postman with request like this:

{
   "to": "<your token from FirebaseInstanceId.getInstance().getToken()>",
   "notification": {
    "body": "Hello",
    "title": "This is test message."
   }
}

Also I copied also all code from google quickstart firebase messaging.
Everything should be fine. However, after all tests I decided to double check my gradle libs versions. So I incremented them to the latest numbers. Since then I started receiving messages correctly.

The fastest solution I would recommend to download project from GitHub and try if this is working for You. Next step would be copy this code to Your project. If in one project everything is working fine, You have at least one standing/working point where to start.

There are rumors about android studio is causing this issue - but it is not true. I checked it.

It can be true that You could use the same old token (from gcm) and not receiving messages but If You had the same case like me which is migrating, then token should be refreshed to new one and You should handle it..

Body:
I'm getting a weird push message captured by my push service:

Bundle[{CMD=RST_FULL, from=google.com/iid, android.support.content.wakelockid=1}]

Just started to happen yesterday and I can't really spot which code change is to blame for this. Has anyone seen this message before and maybe knows where is it coming from and why?


问:
asp.net core 2 multiple web.config files (different environments)
This issue is not related to application configurations (custom), but more to do with IIS settings.

So I need the following to be in the web.config when i create a publish for my app.

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Redirect to https" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
        </rule>
      </rules>
    </rewrite>
    <security>
      <requestFiltering allowDoubleEscaping="true" />
    </security>
  </system.webServer>
</configuration>
</code>```

However, when debugging i only want the  part and not the http redirect (If i try to debug my app with the rewrite in the web.config it does not start)

in previous asp.net, we could have multiple web.configs for debug and release and it would transform when published.

I simply want to the all of the above code to be in the web.config when published, and only  part to be in applied in web.config when i am debugging

答:
This isn't a true answer to your question, but I've got what I think is a much better solution overall. For some time, I've found the fact that URL Rewrites have to go into the Web.config to be frustrating. As careful as you are, it's almost inevitable that you're going to overwrite the Web.config at some point, removing rewrites that have been added to it. This is especially the case if a developer doesn't know better and adds a rewrite directly through IIS, but never copies it over to the project's Web.config in source control (which happens more often than not).

As a result, I started creating a site in IIS just for redirects like this. It has nothing but a Web.config, and then I add the bindings that I'm redirecting from to it. For example, for a rewrite like this, you'd add the binding for the HTTP version of your domain to the redirect site and the HTTPS binding to the actual web application site. Then, you can create the rewrite rule on the the redirect "site", and never ever worry about accidentally overwriting it, because you never publish anything there. This would effectively side-step your issue here, entirely.

Body:
This issue is not related to application configurations (custom), but more to do with IIS settings.

So I need the following to be in the web.config when i create a publish for my app.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <clear />
        <rule name="Redirect to https" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
        </rule>
      </rules>
    </rewrite>
    <security>
      <requestFiltering allowDoubleEscaping="true" />
    </security>
  </system.webServer>
</configuration>

However, when debugging i only want the  part and not the http redirect (If i try to debug my app with the rewrite in the web.config it does not start)

in previous asp.net, we could have multiple web.configs for debug and release and it would transform when published.

I simply want to the all of the above code to be in the web.config when published, and only  part to be in applied in web.config when i am debugging


问:
AssertionError: all exprs should be Column
I join two PySpark DataFrames as follows:

```<code>exprs = [max(x) for x in ["col1","col2"]]
df = df1.union(df2).groupBy(['campk', 'ppk']).agg(*exprs)
</code>```

But I get this error:

```<code>AssertionError: all exprs should be Column
</code>```

What is wrong?

答:
```<code>exprs = [max(x) for x in ["col1","col2"]]
</code>```

will return character with max ASCII value ie ['o', 'o']

Refering the correct max would work:

```<code>>>> from pyspark.sql import functions as F
>>> exprs = [F.max(x) for x in ["col1","col2"]]
>>> print(exprs)
[Column<max(col1)>, Column<max(col2)>]
</code>```

Body:
I join two PySpark DataFrames as follows:

exprs = [max(x) for x in ["col1","col2"]]
df = df1.union(df2).groupBy(['campk', 'ppk']).agg(*exprs)

But I get this error:

AssertionError: all exprs should be Column

What is wrong?

Body:
exprs = [max(x) for x in ["col1","col2"]]

will return character with max ASCII value ie ['o', 'o']

Refering the correct max would work:

>>> from pyspark.sql import functions as F
>>> exprs = [F.max(x) for x in ["col1","col2"]]
>>> print(exprs)
[Column<max(col1)>, Column<max(col2)>]


问:
Is it Possible to migrate from PEAR Crypt to PHPSecLib RSA?
We migrated to PHPSecLib a while ago, but did not migrate our legacy data that was encrypted by the old PEAR\Crypt_RSA library. We've reached a point where we need to migrate that data into PHPSecLib's RSA format. While investigating this, I came across this old forum thread. I attempted to apply the suggestion in the response, but could not get it to successfully decrypt our data. It's not erroring out or anything, it just appears to still be encrypted or encoded. We're running PHPSecLib 2.0.6 currently, and I suspect the instructions were for 1.x.

Here's a roughed out version of my adapted decryption flow (based off the forum thread):

```<code>$rsaDecryptor = new RSA();

// The Private Key is encrypted based off a password
$mc      = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv      = mcrypt_create_iv(mcrypt_enc_get_iv_size($mc), MCRYPT_DEV_URANDOM);
$keySize = mcrypt_enc_get_key_size($mc);
$key     = substr($rsaDecryptor->password, 0, $keySize);

mcrypt_generic_init($mc, $key, $iv);
$privateKey = mdecrypt_generic($mc, base64_decode($privateKey));
mcrypt_generic_deinit($mc);
mcrypt_module_close($mc);

list($privateKeyModulus, $privateKeyExponent) = unserialize(base64_decode($privateKey));

$privateKeyExponent = new BigInteger(strrev($privateKeyExponent), 256);
$privateKeyModulus = new BigInteger(strrev($privateKeyModulus), 256);

$rsaDecryptor->modulus        = $privateKeyModulus;
$rsaDecryptor->exponent       = $privateKeyExponent;
$rsaDecryptor->publicExponent = $privateKeyExponent;
$rsaDecryptor->k              = strlen($this->decRSA->modulus->toBytes());

// ciphertext is the raw encrypted string created by PEAR\Crypt_RSA
$value = base64_decode($ciphertext);
$value = new BigInteger($value, 256);
$value = $rsaDecryptor->_exponentiate($value)->toBytes();
$value = substr($value, 1);
</code>```

答:
Bugs In PEAR's Crypt_RSA

So I was playing around with this. There's a bug in PEAR's Crypt_RSA (latest version) that might prevent this from working at all. The following code demonstrates:

```<code>$key_pair = new Crypt_RSA_KeyPair(1024);
$privkey = $key_pair->getPrivateKey();
$pubkey = $key_pair->getPublicKey();
$a = $privkey->toString();
$b = $pubkey->toString();

echo $a == $b ? 'same' : 'different';
</code>```

You'd expect $a and $b to be different, wouldn't you? Well they're not. This is because RSA/KeyPair.php does this:

```<code>$this->_public_key = &$obj;
...
$this->_private_key = &$obj;
</code>```

If you remove the ampersands it works correctly but they're in the code by default.

It looks like this is an unresolved issue as of https://pear.php.net/bugs/bug.php?id=15900

Maybe it behaves differently on PHP4 but I have no idea.

Decrypting Data

Assuming the above bug isn't an issue for you then the following worked for me (using phpseclib 2.0):

```<code>function loadKey($key) // for keys genereated with $key->toString() vs $key->toPEMString()
{
    if (!($key = base64_decode($key))) {
        return false;
    }
    if (!($key = unserialize($key))) {
        return false;
    }
    list($modulus, $exponent) = $key;
    $modulus = new BigInteger(strrev($modulus), 256);
    $exponent = new BigInteger(strrev($exponent), 256);
    $rsa = new RSA();
    $rsa->loadKey(compact('modulus', 'exponent'));
    return $rsa;
}

function decrypt($key, $ciphertext)
{
    if (!($ciphertext = base64_decode($ciphertext))) {
        return false;
    }
    $key->setEncryptionMode(RSA::ENCRYPTION_NONE);
    $ciphertext = strrev($ciphertext);
    $plaintext = $key->decrypt($ciphertext);
    $plaintext = strrev($plaintext);
    $plaintext = substr($plaintext, 0, strpos($plaintext, "\0"));
    return $plaintext[strlen($plaintext) - 1] == "\1" ?
        substr($plaintext, 0, -1) : false;
}

$key = loadKey($private_key);
$plaintext = decrypt($key, $ciphertext);
echo $plaintext;
</code>```

Private Keys Generated with toPEMString()

With PEAR's Crypt_RSA you can generate private keys an alternative way:

```<code>$key_pair->toPEMString();
</code>```

This method works without code changes. If you used this approach to generate your private keys the private key starts off with -----BEGIN RSA PRIVATE KEY-----. If this is the case then you don't need to use the loadKey function I wrote. You can do this instead:

```<code>$key = new RSA();
$key->loadKey('...');
$plaintext = decrypt($key, $ciphertext);
echo $plaintext;
</code>```

Body:
We migrated to PHPSecLib a while ago, but did not migrate our legacy data that was encrypted by the old PEAR\Crypt_RSA library. We've reached a point where we need to migrate that data into PHPSecLib's RSA format. While investigating this, I came across this old forum thread. I attempted to apply the suggestion in the response, but could not get it to successfully decrypt our data. It's not erroring out or anything, it just appears to still be encrypted or encoded. We're running PHPSecLib 2.0.6 currently, and I suspect the instructions were for 1.x.

Here's a roughed out version of my adapted decryption flow (based off the forum thread):

$rsaDecryptor = new RSA();

// The Private Key is encrypted based off a password
$mc      = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv      = mcrypt_create_iv(mcrypt_enc_get_iv_size($mc), MCRYPT_DEV_URANDOM);
$keySize = mcrypt_enc_get_key_size($mc);
$key     = substr($rsaDecryptor->password, 0, $keySize);

mcrypt_generic_init($mc, $key, $iv);
$privateKey = mdecrypt_generic($mc, base64_decode($privateKey));
mcrypt_generic_deinit($mc);
mcrypt_module_close($mc);

list($privateKeyModulus, $privateKeyExponent) = unserialize(base64_decode($privateKey));

$privateKeyExponent = new BigInteger(strrev($privateKeyExponent), 256);
$privateKeyModulus = new BigInteger(strrev($privateKeyModulus), 256);

$rsaDecryptor->modulus        = $privateKeyModulus;
$rsaDecryptor->exponent       = $privateKeyExponent;
$rsaDecryptor->publicExponent = $privateKeyExponent;
$rsaDecryptor->k              = strlen($this->decRSA->modulus->toBytes());

// ciphertext is the raw encrypted string created by PEAR\Crypt_RSA
$value = base64_decode($ciphertext);
$value = new BigInteger($value, 256);
$value = $rsaDecryptor->_exponentiate($value)->toBytes();
$value = substr($value, 1);

Body:
Bugs In PEAR's Crypt_RSA

So I was playing around with this. There's a bug in PEAR's Crypt_RSA (latest version) that might prevent this from working at all. The following code demonstrates:

$key_pair = new Crypt_RSA_KeyPair(1024);
$privkey = $key_pair->getPrivateKey();
$pubkey = $key_pair->getPublicKey();
$a = $privkey->toString();
$b = $pubkey->toString();

echo $a == $b ? 'same' : 'different';

You'd expect $a and $b to be different, wouldn't you? Well they're not. This is because RSA/KeyPair.php does this:

$this->_public_key = &$obj;
...
$this->_private_key = &$obj;

If you remove the ampersands it works correctly but they're in the code by default.

It looks like this is an unresolved issue as of https://pear.php.net/bugs/bug.php?id=15900

Maybe it behaves differently on PHP4 but I have no idea.

Decrypting Data

Assuming the above bug isn't an issue for you then the following worked for me (using phpseclib 2.0):

function loadKey($key) // for keys genereated with $key->toString() vs $key->toPEMString()
{
    if (!($key = base64_decode($key))) {
        return false;
    }
    if (!($key = unserialize($key))) {
        return false;
    }
    list($modulus, $exponent) = $key;
    $modulus = new BigInteger(strrev($modulus), 256);
    $exponent = new BigInteger(strrev($exponent), 256);
    $rsa = new RSA();
    $rsa->loadKey(compact('modulus', 'exponent'));
    return $rsa;
}

function decrypt($key, $ciphertext)
{
    if (!($ciphertext = base64_decode($ciphertext))) {
        return false;
    }
    $key->setEncryptionMode(RSA::ENCRYPTION_NONE);
    $ciphertext = strrev($ciphertext);
    $plaintext = $key->decrypt($ciphertext);
    $plaintext = strrev($plaintext);
    $plaintext = substr($plaintext, 0, strpos($plaintext, "\0"));
    return $plaintext[strlen($plaintext) - 1] == "\1" ?
        substr($plaintext, 0, -1) : false;
}

$key = loadKey($private_key);
$plaintext = decrypt($key, $ciphertext);
echo $plaintext;

Private Keys Generated with toPEMString()

With PEAR's Crypt_RSA you can generate private keys an alternative way:

$key_pair->toPEMString();

This method works without code changes. If you used this approach to generate your private keys the private key starts off with -----BEGIN RSA PRIVATE KEY-----. If this is the case then you don't need to use the loadKey function I wrote. You can do this instead:

$key = new RSA();
$key->loadKey('...');
$plaintext = decrypt($key, $ciphertext);
echo $plaintext;


问:
ImportError: No module named rest_framework_extensions.cache.mixins
Trying to set up RDMO on a apache server, but when running "python manage.py runserver" this error accures. Before that many other import Error accurred which I solved by pip install missing package, but i am not able to find requred package to solve this error.

And it would also be very helpful if someone can provide name to the whole package/bundle required for RDMO server run.

答:
you need to do,

```<code>pip install drf-extensions
</code>```

its because of drf-extensions missing.. install it will fix

Body:
you need to do,

pip install drf-extensions

its because of drf-extensions missing.. install it will fix


问:
Drawing 4 Circle one button different sizes and colors
I'm trying to do this code to output the same result as the picture

it should start with one black circle then when I click the button, a white circle appear with shift the right and get bigger by 20 pixels and so on
after the 4th circle it should clear the window and start from the beginning and I keep getting only one circle color or two circles together

here's the code

```<code>import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.WindowConstants;

public class CircleList extends JFrame implements ActionListener {
    JButton addCircle;
    int nCircle = 1;
    int step = 0;
    int shift = 0;
    int d = 0;

    public static void main (String [] args){
        new CircleList();
    }

    private class Circle {
        public int x1;
        public int y1;
        public int w;
        public int h;
        public Color color;
    }

    private List<Circle> whiteList = new ArrayList<>();
    private List<Circle> blackList = new ArrayList<>();

    public CircleList() {
        super("CircleList");
        setSize(500,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setBackground(Color.gray);
        addCircle = new JButton("Add Circle");
        add(addCircle,BorderLayout.SOUTH);
        addCircle.addActionListener(this);
        repaint();

        setVisible(true);
    }

    public void paint(Graphics g){
        super.paint(g);
        g.fillOval(35, 35, 35, 35);
        if (d==1) {
            for (Circle s: whiteList ) {
                paintWhiteCircle(g, s);
            }
            addWhiteCircle();
        }
        else if (d==2) {
            for (Circle s: blackList ) {
                 paintBlackCircle(g, s);

            }
            addBlackCircle();
        }
    }

    public void paintWhiteCircle(Graphics g, Circle circle) {
        g.setColor(circle.color);
        g.fillOval(circle.x1, circle.y1,  circle.w, circle.h);
    }

    public void paintBlackCircle(Graphics g, Circle circle) {
        g.setColor(circle.color);
        g.fillOval(circle.x1, circle.y1, circle.w, circle.h);
    }

    public void addBlackCircle(){

        Circle circle = new Circle();

        circle.x1 = 40 + shift;
        circle.y1 = 30 ;
        circle.w = 30 + step;
        circle.h = 30 + step;
        circle.color = new Color(0,0,0);
        this.blackList.add(circle);
    }
    public void addWhiteCircle() {

        Circle circle = new Circle();
        circle.x1 = 100 + shift;
        circle.y1 = 30 ;
        circle.w = 50 + step;
        circle.h = 50 + step;
        circle.color =  new Color(255*65536+255*256+255);
        this.whiteList.add(circle);
    }

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        d = 0;
        if (source == addCircle) {
            for (nCircle = 2; nCircle <= 5; nCircle++) {
                if (nCircle == 2) {
                    d = 1;
                    step+=20;
                    shift += 20;
                    nCircle++;
                }
                else if (nCircle == 3) {
                    d = 2;
                    step+=20;
                    shift += 20;
                }
                else if (nCircle == 4) {
                    d=1;
                    step+=20;
                    shift += 20;
                }
                else if (nCircle == 5)
                    repaint(); // it should clear the window and start with one circle like the beginning
                }

                repaint();
           }
      }
}
</code>```

the output should be like this

答:
I've corrected your example. It works now.</p>

```<code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class CircleList extends JPanel implements ActionListener, Runnable {

    private static final int INTERVAL = 20;

    private static final int INITIAL_DIAMETR = 20;

    private int actualXPos;

    private final List<Circle> circleList = new ArrayList<>();

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new CircleList());
    }

    @Override
    public void run() {
        JFrame frm = new JFrame(getClass().getSimpleName());
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.getContentPane().add(this);
        frm.pack();
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    public CircleList() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 500));
        setBackground(Color.gray);
        JButton addCircle = new JButton("Add Circle");
        add(addCircle, BorderLayout.SOUTH);
        addCircle.addActionListener(this);
        addCircle();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Circle c : circleList) {
            c.paint(g);
        }
    }

    private void addCircle() {

        Circle circle = new Circle();

        int num = circleList.size();
        circle.x1 = 40 + actualXPos;
        circle.y1 = 30;
        circle.w = 30 + INITIAL_DIAMETR * (num + 1);
        circle.h = 30 + INITIAL_DIAMETR * (num + 1);
        circle.color = num % 2 == 0 ? Color.BLACK : Color.WHITE;
        circleList.add(circle);
        actualXPos += circle.w + INTERVAL;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (circleList.size() == 4) {
            circleList.clear();
            actualXPos = 0;
        }
        addCircle();
        repaint();
    }

    private static class Circle {
        private int x1;

        private int y1;

        private int w;

        private int h;

        private Color color;

        public void paint(Graphics g) {
            g.setColor(color);
            g.fillOval(x1, y1, w, h);
        }
    }
}
</code>```

Body:
I'm trying to do this code to output the same result as the picture

it should start with one black circle then when I click the button, a white circle appear with shift the right and get bigger by 20 pixels and so on
after the 4th circle it should clear the window and start from the beginning and I keep getting only one circle color or two circles together

here's the code

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.WindowConstants;

public class CircleList extends JFrame implements ActionListener {
    JButton addCircle;
    int nCircle = 1;
    int step = 0;
    int shift = 0;
    int d = 0;

    public static void main (String [] args){
        new CircleList();
    }

    private class Circle {
        public int x1;
        public int y1;
        public int w;
        public int h;
        public Color color;
    }

    private List<Circle> whiteList = new ArrayList<>();
    private List<Circle> blackList = new ArrayList<>();

    public CircleList() {
        super("CircleList");
        setSize(500,500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setBackground(Color.gray);
        addCircle = new JButton("Add Circle");
        add(addCircle,BorderLayout.SOUTH);
        addCircle.addActionListener(this);
        repaint();

        setVisible(true);
    }

    public void paint(Graphics g){
        super.paint(g);
        g.fillOval(35, 35, 35, 35);
        if (d==1) {
            for (Circle s: whiteList ) {
                paintWhiteCircle(g, s);
            }
            addWhiteCircle();
        }
        else if (d==2) {
            for (Circle s: blackList ) {
                 paintBlackCircle(g, s);

            }
            addBlackCircle();
        }
    }

    public void paintWhiteCircle(Graphics g, Circle circle) {
        g.setColor(circle.color);
        g.fillOval(circle.x1, circle.y1,  circle.w, circle.h);
    }

    public void paintBlackCircle(Graphics g, Circle circle) {
        g.setColor(circle.color);
        g.fillOval(circle.x1, circle.y1, circle.w, circle.h);
    }

    public void addBlackCircle(){

        Circle circle = new Circle();

        circle.x1 = 40 + shift;
        circle.y1 = 30 ;
        circle.w = 30 + step;
        circle.h = 30 + step;
        circle.color = new Color(0,0,0);
        this.blackList.add(circle);
    }
    public void addWhiteCircle() {

        Circle circle = new Circle();
        circle.x1 = 100 + shift;
        circle.y1 = 30 ;
        circle.w = 50 + step;
        circle.h = 50 + step;
        circle.color =  new Color(255*65536+255*256+255);
        this.whiteList.add(circle);
    }

    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        d = 0;
        if (source == addCircle) {
            for (nCircle = 2; nCircle <= 5; nCircle++) {
                if (nCircle == 2) {
                    d = 1;
                    step+=20;
                    shift += 20;
                    nCircle++;
                }
                else if (nCircle == 3) {
                    d = 2;
                    step+=20;
                    shift += 20;
                }
                else if (nCircle == 4) {
                    d=1;
                    step+=20;
                    shift += 20;
                }
                else if (nCircle == 5)
                    repaint(); // it should clear the window and start with one circle like the beginning
                }

                repaint();
           }
      }
}

the output should be like this

Body:
I've corrected your example. It works now.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class CircleList extends JPanel implements ActionListener, Runnable {

    private static final int INTERVAL = 20;

    private static final int INITIAL_DIAMETR = 20;

    private int actualXPos;

    private final List<Circle> circleList = new ArrayList<>();

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new CircleList());
    }

    @Override
    public void run() {
        JFrame frm = new JFrame(getClass().getSimpleName());
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.getContentPane().add(this);
        frm.pack();
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    public CircleList() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 500));
        setBackground(Color.gray);
        JButton addCircle = new JButton("Add Circle");
        add(addCircle, BorderLayout.SOUTH);
        addCircle.addActionListener(this);
        addCircle();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (Circle c : circleList) {
            c.paint(g);
        }
    }

    private void addCircle() {

        Circle circle = new Circle();

        int num = circleList.size();
        circle.x1 = 40 + actualXPos;
        circle.y1 = 30;
        circle.w = 30 + INITIAL_DIAMETR * (num + 1);
        circle.h = 30 + INITIAL_DIAMETR * (num + 1);
        circle.color = num % 2 == 0 ? Color.BLACK : Color.WHITE;
        circleList.add(circle);
        actualXPos += circle.w + INTERVAL;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (circleList.size() == 4) {
            circleList.clear();
            actualXPos = 0;
        }
        addCircle();
        repaint();
    }

    private static class Circle {
        private int x1;

        private int y1;

        private int w;

        private int h;

        private Color color;

        public void paint(Graphics g) {
            g.setColor(color);
            g.fillOval(x1, y1, w, h);
        }
    }
}