问:
undefined index file (Tried a lot of solutions from this forum but not working ...)
I'm sorry to ask question that has been seen a lot of time, but it seems to not work for me, so I have to ask you guys ...
Thanks in advance !

here is my html form :

```<code><form action="action/actionindex.php" method="post">
<label style="text-align:center;"><b>Changer d'image</b></label>
    <input type="file" name="file" id="indeximage" style="margin-left:500px;"/>
    <div class="bg" style="background-image:url('../image/papierpeint.jpg');width:95%;margin:0 auto;height:auto;">
        <div class="welcometxt">
            <ul>

                <label><b>Titre de l'article (Saut de ligne : <img src="../image/sautligne.png"/>| Gras : <img src="../image/gras.png"/>| Italique : <img src="../image/italique.png"/>| Souligné : <img src="../image/souligne.png"/>)</b></label>
                <textarea name="indexh2" rows="1" cols="80">
                    <?php getDesc(1) ?>
                </textarea></br>
    <label><b>Contenu l'article (Saut de ligne : <img src="../image/sautligne.png"/>| Gras : <img src="../image/gras.png"/>| Italique : <img src="../image/italique.png"/>| Souligné : <img src="../image/souligne.png"/>)</b></label>
            <textarea name="indexp" rows="15" cols="110">
                <?php getDesc(2)?>
            </textarea>
            <input type="submit" name="submit" value="Modifier"></br>
</code>```

and here is actionindex.php :

```<code>if(isset($_POST['submit'])){
    $name = $_FILES['file']['name'];
    echo 'nom : '.$name;
    $temp_name  = $_FILES['file']['tmp_name'];
    echo 'dossier temp : '.$temp_name;
    if(isset($name)){
        if(!empty($name)){
            $location = '../../image/';
            if(move_uploaded_file($temp_name, $location)){
                echo 'File uploaded successfully';
            }
        }
    }  else {
        echo 'You should select a file to upload !!';
    }
}
</code>```

Hope you guys help me, thanks !!

答:
Try to change your form code as below:

```<code><form action="action/actionindex.php" method="post" enctype="multipart/form-data">
</code>```

I hope, it helps.

Body:
I'm sorry to ask question that has been seen a lot of time, but it seems to not work for me, so I have to ask you guys ...
Thanks in advance !

here is my html form :

<form action="action/actionindex.php" method="post">
Changer d'image
    <input type="file" name="file" id="indeximage" style="margin-left:500px;"/>

                Titre de l'article (Saut de ligne : | Gras : | Italique : | Souligné : )
                <textarea name="indexh2" rows="1" cols="80">
                    <?php getDesc(1) ?>
                </textarea>

    Contenu l'article (Saut de ligne : | Gras : | Italique : | Souligné : )
            <textarea name="indexp" rows="15" cols="110">
                <?php getDesc(2)?>
            </textarea>
            <input type="submit" name="submit" value="Modifier">

and here is actionindex.php :

if(isset($_POST['submit'])){
    $name = $_FILES['file']['name'];
    echo 'nom : '.$name;
    $temp_name  = $_FILES['file']['tmp_name'];
    echo 'dossier temp : '.$temp_name;
    if(isset($name)){
        if(!empty($name)){
            $location = '../../image/';
            if(move_uploaded_file($temp_name, $location)){
                echo 'File uploaded successfully';
            }
        }
    }  else {
        echo 'You should select a file to upload !!';
    }
}

Hope you guys help me, thanks !!

Body:
Try to change your form code as below:

<form action="action/actionindex.php" method="post" enctype="multipart/form-data">

I hope, it helps.


来源: stackexchange

问:
Why "kubectl describe job xxx" got TooManyActivePods?
I‘m running the job example https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/

```<code>apiVersion: batch/v1
kind: Job
metadata:
  name: pi
spec:
  template:
    metadata:
      name: pi
    spec:
      containers:
      - name: pi
        image: perl
        command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(2000)"]
      restartPolicy: Never
</code>```

I got some warning

```<code>  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-5n0vn
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-5n0vn
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-qlp5f
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-j9z6s
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-qlp5f
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-mf1j9
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-mf1j9
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-j9z6s
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-qlp5f
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-w3m2m
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-qlp5f
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-5n0vn
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-nww4h
  23m           23m             2       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-p8pt9
  23m           23m             1       {job-controller }                       Warning         FailedDelete            Error deleting: pods "pi-mf1j9" not found
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-w3m2m
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-69l9r
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-p8pt9
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-69l9r
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-p8pt9
  23m           23m             1       {job-controller }                       Warning         TooManyActivePods       Too many active pods running after completion count reached
  23m           23m             1       {job-controller }                       Warning         TooManyActivePods       Too many active pods running after completion count reached
  23m           23m             1       {job-controller }                       Warning         TooManyActivePods       Too many active pods running after completion count reached
</code>```

Why start so many pod and delete it?

I can't delete the job

```<code>[root@c3-sa-i2-20151229-buf023 ~]# kubectl delete job pi
error: timed out waiting for "pi" to be synced
</code>```

答:
Try adding --grace-period=0 --force to your delete command.

https://kubernetes.io/docs/concepts/workloads/pods/pod/#termination-of-pods

The kubectl delete command supports the --grace-period= option which allows a user to override the default and specify their own value. The value 0 force deletes the pod. In kubectl version >= 1.5, you must specify an additional flag --force along with --grace-period=0 in order to perform force deletions.

ContentLicense: CC BY-SA 3.0

Body:
I‘m running the job example https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/

apiVersion: batch/v1
kind: Job
metadata:
  name: pi
spec:
  template:
    metadata:
      name: pi
    spec:
      containers:
      - name: pi
        image: perl
        command: ["perl",  "-Mbignum=bpi", "-wle", "print bpi(2000)"]
      restartPolicy: Never

I got some warning

  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-5n0vn
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-5n0vn
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-qlp5f
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-j9z6s
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-qlp5f
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-mf1j9
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-mf1j9
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-j9z6s
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-qlp5f
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-w3m2m
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-qlp5f
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-5n0vn
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-nww4h
  23m           23m             2       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-p8pt9
  23m           23m             1       {job-controller }                       Warning         FailedDelete            Error deleting: pods "pi-mf1j9" not found
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-w3m2m
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-69l9r
  23m           23m             1       {job-controller }                       Normal          SuccessfulCreate        Created pod: pi-p8pt9
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-69l9r
  23m           23m             1       {job-controller }                       Normal          SuccessfulDelete        Deleted pod: pi-p8pt9
  23m           23m             1       {job-controller }                       Warning         TooManyActivePods       Too many active pods running after completion count reached
  23m           23m             1       {job-controller }                       Warning         TooManyActivePods       Too many active pods running after completion count reached
  23m           23m             1       {job-controller }                       Warning         TooManyActivePods       Too many active pods running after completion count reached

Why start so many pod and delete it?

I can't delete the job

[root@c3-sa-i2-20151229-buf023 ~]# kubectl delete job pi
error: timed out waiting for "pi" to be synced


问:
what is the result inside fft bin at different index?
For example if I have 10 samples in the FFT in a system sampled at 100 Hz. Then how are the results represented in FFT bin output ?
The frequency resolution is going to be how many Hz each DFT bin represents. This is, as you have noted, given by fs/N.  In this case :--

```<code>resolution = 100/10 = 10 hz
</code>```

Definition of FFT states that frequency range [0,fs] is represented by N point.

But when the result comes :--

X[0] is the constant term (also refereed to as DC bias)

X[1] is the 10 hz

X[2] is the 20 hz

X[3] is the 30 hz

X[4] is the 40 hz

X[5] is the 50 hz

X[6] to X[9] are the complex conjugates of X[4] to X[1] respectively.

so my question is :--

X[6] is the 60hz signal & its value will be complex conjugate of 40 hz signal .. is it right ?

Or X[6] does not contains spectral of 60hz but it is only complex conjugate of X[4] ?

Please suggest.

答:
The frequencies of each bin in the DFT go from $n = 0 to N-1$ where each frequency is given as $n F_s/N$.

Due to the sampling process, for any signals (either real and complex signals) the upper half of this frequency spectrum that extends from $F_s/2$ to 1 sample less than $F_s$ is equivalent to the negative half spectrum (the spectrum that extends from $-F_s/2% to 1 sample less than 0.). This applies to the DFT and all digital signals.

This is demonstrated in the graphics below, showing how an analog spectrum (top line), convolves with the sampling spectrum (second line) of a system sampled at 20 Hz to result in the digital spectrum of a sampled signal. Since the spectrum is unique over a 20 Hz range (and repeats everywhere else), we only need to show the frequencies over any 20 Hz range to represent the signal. This can be identically shown from -10 Hz to +10 Hz, or 0 to 20 Hz.

Representing the sampled spectrum of a real signal sampled at 20 Hz over the range of -10Hz to +10Hz:

The same signal can also be represented over the range of 0 to 20 Hz:

Representing the sampled spectrum of a complex signal sampled at 20 Hz over the range of -10Hz to +10Hz:

The same signal can also be represented over the range of 0 to 20 Hz:

Since the spectrum for the DFT is discrete, the samples go from $n = 0 to N-1$ where each frequency is given as $F_s/n$ as described above. There is also only N samples in the DFT of course but as you rotate the samples in the DFT, you effectively move through the expanded spectrum above.  It is helpful to view the spectrum on the surface of a cylinder with a circumference that goes from 0 to $F_s$ where you see that $F_s$ is equivalent to 0, and going backwards from 0 is equivalent to going into the negative half spectrum.

So in your example specifically:

X[0] = DC

X1 = 10

X2 = 20

X3 = 30

X4 = 40

X[5] = 50

X[6] = 60

X[7] = 70

X[8] = 80

X[9] = 90

Can also be represented as

X[0] = DC

X1 = 10

X2 = 20

X3 = 30

X4 = 40

X[5] = -50

X[6] = -40

X[7] = -30

X[8] = -20

X[9] = -10

Note that the command "FFTSHIFT" in MATLAB shifts the DFT vector accordingly to produce the following order representing the range from -F_s/2 to +F_s/2 :

fftshift([X[0], X1, X2, X3, X4, X[5], X[6], X[7], X[8], X[9]]) =

[X[5], X[6], X[7], X[8], X[9], X[0], X1, X2, X3, X4]

Body:
For example if I have 10 samples in the FFT in a system sampled at 100 Hz. Then how are the results represented in FFT bin output ?
The frequency resolution is going to be how many Hz each DFT bin represents. This is, as you have noted, given by fs/N.  In this case :--

resolution = 100/10 = 10 hz

Definition of FFT states that frequency range [0,fs] is represented by N point.

But when the result comes :--

X[0] is the constant term (also refereed to as DC bias)

X[1] is the 10 hz

X[2] is the 20 hz

X[3] is the 30 hz

X[4] is the 40 hz

X[5] is the 50 hz

X[6] to X[9] are the complex conjugates of X[4] to X[1] respectively.

so my question is :--

X[6] is the 60hz signal & its value will be complex conjugate of 40 hz signal .. is it right ?

Or X[6] does not contains spectral of 60hz but it is only complex conjugate of X[4] ?

Please suggest.


问:
CodeIgniter auth security model
I've built a custom auth system for CodeIgniter (I know there are various 3rd party libraries available but this is for my own benefit) but I'm worried I'm missing something obvious that could bring the whole thing down.

I use CI sessions (through the database) and encrypt cookie values for a little bit of probably pointless obfuscation. Logins take place over SSL (and cookies are modified to be secure only). I also use phpass to hash passwords for storage, though thats not really relevant here. There may be a weak link in this part somewhere but my main concern is that page-to-page checks basically consist of a if is_logged_in = true type approach along with their username in the session. This bit concerns me as it seems a bit too 'easy'. Is this approach quite vulnerable? Should I be computing a page-by-page hash of, say, user-agent or whatever and making sure they match?

Any pointers would be most appreciated. Like I said, I'm aware of pre-existing solutions but I'm trying to learn me some learning here :)

答:
Everything you mentioned is good. I'm not familiar with phpass however.  Make sure that when you hash the passwords, that you are using a salt.

An if_logged_in = true check is sufficient because session data is stored server-side.  The reason for checking things such as user-agent is to help protect against session hijacking, where one person obtains another person's session ID.

ContentLicense: CC BY-SA 2.5

Title: CodeIgniter auth security model


问:
Pivot spark multilevel Dataset
I have the Dataset in Spark with these schemas:

```<code>root
 |-- from: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
 |-- v1: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
 |-- v2: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
 |-- v3: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
 |-- to: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
</code>```

How to make the table(with only 3 columns id,name,tags) from this Dataset on Scala?

答:
Just combine all the columns into an array, explode and select all nested fields:

```<code>import org.apache.spark.sql.functions.{array, col, explode}

case class Vertex(id: String, name: String, tags: String)

val df  = Seq(((
  Vertex("1", "from", "a"), Vertex("2", "V1", "b"), Vertex("3", "V2", "c"),
  Vertex("4", "v3", "d"), Vertex("5", "to", "e")
)).toDF("from", "v1", "v2", "v3", "to")

df.select(explode(array(df.columns map col: _*)).alias("col")).select("col.*")
</code>```

with the result as follows:

+---+----+----+
| id|name|tags|
+---+----+----+
|  1|from|   a|
|  2|  V1|   b|
|  3|  V2|   c|
|  4|  v3|   d|
|  5|  to|   e|
+---+----+----+
```

Title: Pivot spark multilevel Dataset

Body:
I have the Dataset in Spark with these schemas:

root
 |-- from: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
 |-- v1: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
 |-- v2: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
 |-- v3: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)
 |-- to: struct (nullable = false)
 |    |-- id: string (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- tags: string (nullable = true)

How to make the table(with only 3 columns id,name,tags) from this Dataset on Scala?

Body:
Just combine all the columns into an array, explode and select all nested fields:

import org.apache.spark.sql.functions.{array, col, explode}

case class Vertex(id: String, name: String, tags: String)

val df  = Seq(((
  Vertex("1", "from", "a"), Vertex("2", "V1", "b"), Vertex("3", "V2", "c"),
  Vertex("4", "v3", "d"), Vertex("5", "to", "e")
)).toDF("from", "v1", "v2", "v3", "to")

df.select(explode(array(df.columns map col: _*)).alias("col")).select("col.*")

with the result as follows:

+---+----+----+
| id|name|tags|
+---+----+----+
|  1|from|   a|
|  2|  V1|   b|
|  3|  V2|   c|
|  4|  v3|   d|
|  5|  to|   e|
+---+----+----+


问:
Use pano id of new photo spheres with Google Streetview Image API
I want to take the pano ID from a Google Streetview photosphere (e.g. this one: https://www.google.com/maps/@52.5162672,13.3777133,3a,75y,90t/data=!3m7!1e1!3m5!1s-C3h-fjBdBFo%2FWCz53BtP3dI%2FAAAAAAAAEok%2F2KEziwlh5e4SYRpoC1vnn0hQydXo9HpiACLIB!2e4!3e12!7i9000!8i4500) to receive static images with the help of the Streetview Image API.
I am aware of the fact that there is a "pano" field which takes a pano ID, however Google seems to have changed the way the pano IDs look like.
From what I understand the ID from the above link should be

"-C3h-fjBdBFo/WCz53BtP3dI/AAAAAAAAEok/2KEziwlh5e4SYRpoC1vnn0hQydXo9HpiACLIB"

(i.e. the part between !1s and !2e).

Pasting this ID into the Streetview API (http://maps.googleapis.com/maps/api/streetview?fov=120&pano=-C3h-fjBdBFo%2FWCz53BtP3dI%2FAAAAAAAAEok%2F2KEziwlh5e4SYRpoC1vnn0hQydXo9HpiACLIB&pitch=0&sensor=false&heading=36.9998231626&size=640x640) doesn't give me an image.

Am I missing something?

答:
Indeed, photo spheres weren't available in the Streetview Image API, but recently Google enabled access to User Generated content via Streetview Image API.

The important detail is that the pano ID format that you mentioned in this question was replaced by the new format.

Now the pano ID F:-C3h-fjBdBFo/WCz53BtP3dI/AAAAAAAAEok/2KEziwlh5e4SYRpoC1vnn0hQydXo9HpiACLIB from your question should be replaced by the new pano ID CAMSSi1DM2gtZmpCZEJGby9XQ3o1M0J0UDNkSS9BQUFBQUFBQUVvay8yS0V6aXdsaDVlNFNZUnBvQzF2bm4waFF5ZFhvOUhwaUFDTElC.

You can easily convert the previous pano ID to the new format using the Streetview Image Metadata requests. These requests are free of charge and don't consume a quota

https://maps.googleapis.com/maps/api/streetview/metadata?pano=F%3A-C3h-fjBdBFo%2FWCz53BtP3dI%2FAAAAAAAAEok%2F2KEziwlh5e4SYRpoC1vnn0hQydXo9HpiACLIB&key=YOUR_API_KEY

```<code>{
    "copyright":"© miguel angel Victoria",
    "date":"2016-11",
    "location":{
        "lat":52.51626719999999,
        "lng":13.3777133
    }, "pano_id":"CAMSSi1DM2gtZmpCZEJGby9XQ3o1M0J0UDNkSS9BQUFBQUFBQUVvay8yS0V6aXdsaDVlNFNZUnBvQzF2bm4waFF5ZFhvOUhwaUFDTElC",
   "status":"OK"
}
</code>```

Use the new pano ID to retrieve photo sphere:

https://maps.googleapis.com/maps/api/streetview?pano=CAMSSi1DM2gtZmpCZEJGby9XQ3o1M0J0UDNkSS9BQUFBQUFBQUVvay8yS0V6aXdsaDVlNFNZUnBvQzF2bm4waFF5ZFhvOUhwaUFDTElC&size=600x400&key=YOUR_API_KEY

Body:
Indeed, photo spheres weren't available in the Streetview Image API, but recently Google enabled access to User Generated content via Streetview Image API.

The important detail is that the pano ID format that you mentioned in this question was replaced by the new format.

Now the pano ID F:-C3h-fjBdBFo/WCz53BtP3dI/AAAAAAAAEok/2KEziwlh5e4SYRpoC1vnn0hQydXo9HpiACLIB from your question should be replaced by the new pano ID CAMSSi1DM2gtZmpCZEJGby9XQ3o1M0J0UDNkSS9BQUFBQUFBQUVvay8yS0V6aXdsaDVlNFNZUnBvQzF2bm4waFF5ZFhvOUhwaUFDTElC.

You can easily convert the previous pano ID to the new format using the Streetview Image Metadata requests. These requests are free of charge and don't consume a quota

https://maps.googleapis.com/maps/api/streetview/metadata?pano=F%3A-C3h-fjBdBFo%2FWCz53BtP3dI%2FAAAAAAAAEok%2F2KEziwlh5e4SYRpoC1vnn0hQydXo9HpiACLIB&key=YOUR_API_KEY

{
    "copyright":"© miguel angel Victoria",
    "date":"2016-11",
    "location":{
        "lat":52.51626719999999,
        "lng":13.3777133
    }, "pano_id":"CAMSSi1DM2gtZmpCZEJGby9XQ3o1M0J0UDNkSS9BQUFBQUFBQUVvay8yS0V6aXdsaDVlNFNZUnBvQzF2bm4waFF5ZFhvOUhwaUFDTElC",
   "status":"OK"
}

Use the new pano ID to retrieve photo sphere:

https://maps.googleapis.com/maps/api/streetview?pano=CAMSSi1DM2gtZmpCZEJGby9XQ3o1M0J0UDNkSS9BQUFBQUFBQUVvay8yS0V6aXdsaDVlNFNZUnBvQzF2bm4waFF5ZFhvOUhwaUFDTElC&size=600x400&key=YOUR_API_KEY


问:
Check a checkbox with JavaFX using a keyboard key
Hey so I am working on an autoclicker with random delays etc for a friend but he has asked for me to make a UI with javafx. I said ok but now I need to toggle the autoclicker by pressing the key "r". My code is as follows, I decided on checkbox so I can know whether it is toggled or not but I want to make it so that I can press r to check the checkbox and press again to uncheck therefore stopping the autoclicker. Thanks in advance.

public class MainFrame extends Application {

 CheckBox toggleclick;

  @Override
     public void start(Stage primaryStage) {

    GridPane grid = new GridPane();
         grid.setAlignment(Pos.CENTER);
         grid.setHgap(10);
         grid.setVgap(10);
         grid.setPadding(new Insets(25, 25, 25, 25));

    Text scenetitle = new Text("11.1 CPS Clicker");
         scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 30));
         grid.add(scenetitle, 0, 0, 2, 1);

         CheckBox cb = new CheckBox();
         cb.setText("Begin Clicking");

         HBox hbBtn = new HBox(10);
         hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
         hbBtn.getChildren().add(cb);
         grid.add(hbBtn, 1, 4);

         final Text actiontarget = new Text();
         grid.add(actiontarget, 1, 6);

         cb.setOnAction(new EventHandler<ActionEvent>() {

             @Override
             public void handle(ActionEvent e) {

              while (true) {
            try {
             Mouse.sendLeftClick();
            } catch (AWTException e1) {
             e1.printStackTrace();
            }
                  double deviation = 22;
                  double mean = 90;
                  int min = 43;
                  int max = 198;
                  Random r = new Random();
                  double randGauss = (r.nextGaussian() * deviation);
                  long delayPreClamp = Math.round(randGauss + mean);
                  long delay = (long) MathUtil.clamp(delayPreClamp, min, max);
                  try {
                      Thread.sleep(delay);
                  } catch (InterruptedException e2) {
                      e2.printStackTrace();
                  }
              }
             }
         });

         Scene scene = new Scene(grid, 325, 250);
         primaryStage.setScene(scene);
         primaryStage.show();

         primaryStage.setTitle("AutoClicker");
         primaryStage.setScene(scene);
         primaryStage.show();
     }
  public static void main(String[] args) {
         launch(args);
     }
}```

答:
Try to create an new EventHandler to define an event when a key is pushed, like this :

```<code>cb.setOnKeyPressed(new EventHandler<KeyEvent>() {
                @Override
                public void handle(KeyEvent event) {
                   if("R".equals(ke.getText().toUpperCase() )) {
                       if(cb.isSelected()) {
                          cb.setSelected(false);
                        } else {
                          cb.setSelected(true);
                        }
                   }
                });
</code>```

ke.getText() returns the value of the pressed key, and if it's R, you check or uncheck the checkBox.

Body:
Try to create an new EventHandler to define an event when a key is pushed, like this :

cb.setOnKeyPressed(new EventHandler<KeyEvent>() {
                @Override
                public void handle(KeyEvent event) {
                   if("R".equals(ke.getText().toUpperCase() )) {
                       if(cb.isSelected()) {
                          cb.setSelected(false);
                        } else {
                          cb.setSelected(true);
                        }
                   }
                });

ke.getText() returns the value of the pressed key, and if it's R, you check or uncheck the checkBox.


问:
How do I link two HTML pages in a web application?
I've got two HTML pages, with one being an opening page for an application and the second being a login page. I have a button on the opening page and I want to be able to click on it and have it take me to the login page. How do I do this?</p>

答:
```<code> <a href="secondpage.html"></a>
</code>```

Body: <a href="secondpage.html"></a>


问:
Confirmation dialog on ng-click - AngularJS
I am trying to setup a confirmation dialog on an ng-click using a custom angularjs directive:

```<code>app.directive('ngConfirmClick', [
    function(){
        return {
            priority: 1,
            terminal: true,
            link: function (scope, element, attr) {
                var msg = attr.ngConfirmClick || "Are you sure?";
                var clickAction = attr.ngClick;
                element.bind('click',function (event) {
                    if ( window.confirm(msg) ) {
                        scope.$eval(clickAction)
                    }
                });
            }
        };
}])
</code>```

This works great but unfortunately, expressions inside the tag using my directive are not evaluated:

```<code><button ng-click="sayHi()" ng-confirm-click="Would you like to say hi?">Say hi to {{ name }}</button>
</code>```

(name is not evaluated is this case). It seems to be due to the terminal parameter of my directive. Do you have any ideas of workaround?

To test my code:
http://plnkr.co/edit/EHmRpfwsgSfEFVMgRLgj?p=preview

答:
Confirmation dialog can implemented using AngularJS Material:

$mdDialog opens a dialog over the app to inform users about critical
  information or require them to make decisions. There are two
  approaches for setup: a simple promise API and regular object syntax.

Implementation example: Angular Material - Dialogs

Body:
I am trying to setup a confirmation dialog on an ng-click using a custom angularjs directive:

app.directive('ngConfirmClick', [
    function(){
        return {
            priority: 1,
            terminal: true,
            link: function (scope, element, attr) {
                var msg = attr.ngConfirmClick || "Are you sure?";
                var clickAction = attr.ngClick;
                element.bind('click',function (event) {
                    if ( window.confirm(msg) ) {
                        scope.$eval(clickAction)
                    }
                });
            }
        };
}])

This works great but unfortunately, expressions inside the tag using my directive are not evaluated:

<button ng-click="sayHi()" ng-confirm-click="Would you like to say hi?">Say hi to {{ name }}</button>

(name is not evaluated is this case). It seems to be due to the terminal parameter of my directive. Do you have any ideas of workaround?

To test my code:
http://plnkr.co/edit/EHmRpfwsgSfEFVMgRLgj?p=preview


问:
Supported Serialization Types
What types of serialization do WCF data services support?  Is binary serialization an option?  Can someone point me to some documentation from Microsoft on this subject?</p>

答:
Binary serialization is an option, as well as SOAP and REST.

Please see this as a starter:
http://msdn.microsoft.com/en-us/library/ms731073.aspx

Title: Supported Serialization Types


问:
Count How many number multiple by the number from input user between a range
again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot

write a program input an integer in the range 100 to 200 inclusive.  If the user enters invalid input then your algorithm should re-prompt the user until the input is valid.  Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input.  Finally, the count should be output to the user.  You should make good use of sub-modules.

Here my code

```<code>import java.util.*;

public class Exam3
{
    public static void main(String args[])
    {
        int count = 0;
        int input = 0;

        Scanner sc = new Scanner(System.in);

            System.out.println("Enter number: ");
            input = sc.nextInt();

           while(input < 100 || input > 200)
            {
                System.out.println("Enter number between 100 to 200");
                input = sc.nextInt();

                count ++;

            }
          System.out.println("count is: " + count);
    }
    public static void int getCount(int input, int count)
    {
        for(int i = 499;i <= 1000; i++ )
        {
                if(i % input==0)
                {
                    count++;
                }
        }
        return count;
    }
}
</code>```

答:
The algorithm should be:

Having correct input, find all multiples of it that are in range [500, 1000]. Count them.

It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.

Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.

```<code>public static void main(String args[]) {
    int count = 0;
    int input = 0;

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number: ");
    input = sc.nextInt();

    while (input < 100 || input > 200) {
        System.out.println("Enter number between 100 to 200");
        input = sc.nextInt();
        count++;
    }
    System.out.println(input + " fits " + count(input) + " times");
}

private static int count(int input) {
    int result = 0;
    int temp = input;
    while (temp <= 1000) {
        if (temp >= 500) {
            result++;
        }
        temp += input;
    }
    return result;
}
</code>```

According to your code, I see some issues. I'll point them out, as it is important for practicing Java.

Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,

It's important to stick to Java styling. Don't put too many empty lines, keep indents.

Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.

Body:
again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot

write a program input an integer in the range 100 to 200 inclusive.  If the user enters invalid input then your algorithm should re-prompt the user until the input is valid.  Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input.  Finally, the count should be output to the user.  You should make good use of sub-modules.

Here my code

import java.util.*;

public class Exam3
{
    public static void main(String args[])
    {
        int count = 0;
        int input = 0;

        Scanner sc = new Scanner(System.in);

            System.out.println("Enter number: ");
            input = sc.nextInt();

           while(input < 100 || input > 200)
            {
                System.out.println("Enter number between 100 to 200");
                input = sc.nextInt();

                count ++;

            }
          System.out.println("count is: " + count);
    }
    public static void int getCount(int input, int count)
    {
        for(int i = 499;i <= 1000; i++ )
        {
                if(i % input==0)
                {
                    count++;
                }
        }
        return count;
    }
}

Body:
The algorithm should be:

Having correct input, find all multiples of it that are in range [500, 1000]. Count them.

It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.

Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.

public static void main(String args[]) {
    int count = 0;
    int input = 0;

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number: ");
    input = sc.nextInt();

    while (input < 100 || input > 200) {
        System.out.println("Enter number between 100 to 200");
        input = sc.nextInt();
        count++;
    }
    System.out.println(input + " fits " + count(input) + " times");
}

private static int count(int input) {
    int result = 0;
    int temp = input;
    while (temp <= 1000) {
        if (temp >= 500) {
            result++;
        }
        temp += input;
    }
    return result;
}

According to your code, I see some issues. I'll point them out, as it is important for practicing Java.

Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,

It's important to stick to Java styling. Don't put too many empty lines, keep indents.

Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.


问:
PHP - Has anyway to encrypt/decrpyt hash in PHP?
I'm interested to encrypt/decrpyt hash in PHP.

But as I know hash can be encoding only with md5, sha1, sha256.

However, is it possible to make encrypt/decrpyt in PHP by another hash like ripemd160, haval256,5 or ripemd256?

Thank

答:
Hashes are one way algorithms.The only way to crack them is by brute force.

As an example, Bitcoin uses SHA-256 hashes for the receiving addresses. You can brute force the first couple of letters/digits quite quickly, but even just cracking the first 6 will take over a day. 7 will take a week, 8 could be months! Cracking an entire bitcoin address would take years upon years!

So I'm afraid what you are asking can't be done.


问:
How to recursively compute Delayed in collection
I am a new user to try dask delayed. I want to use delayed to automatically transform function and code into Delayed. However, I found delayed.compute didn't recursively compute Delayed in collection...

```<code>from dask import delayed, base

@delayed
def inc(x):
    return x + 1

@delayed
def colls(ind):
    return [inc(i) for i in xrange(ind)]

data2 = colls(2)
data2.compute() # I expect [1, 2], but get [Delayed('inc-...'),
 Delayed('inc-...')]
</code>```

Did I missing any thing to make it work or Dask.delayed doesn't support it?

答:
You are correct that you should not use delayed functions within other delayed functions (unless you are doing something very strange).  However you can pass delayed values into other delayed functions.

In your particular example I would leave colls as not-delayed.  You want it to immediately determine how many delayed inc calls to make.  Generally you want to immediately call any code that builds out your task graph and delay any function that just does work.

```<code>from dask import delayed, compute

@delayed
def inc(x):
    return x + 1

def colls(ind):
    return [inc(i) for i in xrange(ind)]

data2 = colls(2)
compute(data2)
# [1, 2]
</code>```

Body:
I am a new user to try dask delayed. I want to use delayed to automatically transform function and code into Delayed. However, I found delayed.compute didn't recursively compute Delayed in collection...

from dask import delayed, base

@delayed
def inc(x):
    return x + 1

@delayed
def colls(ind):
    return [inc(i) for i in xrange(ind)]

data2 = colls(2)
data2.compute() # I expect [1, 2], but get [Delayed('inc-...'),
 Delayed('inc-...')]

Did I missing any thing to make it work or Dask.delayed doesn't support it?

Body:
You are correct that you should not use delayed functions within other delayed functions (unless you are doing something very strange).  However you can pass delayed values into other delayed functions.

In your particular example I would leave colls as not-delayed.  You want it to immediately determine how many delayed inc calls to make.  Generally you want to immediately call any code that builds out your task graph and delay any function that just does work.

from dask import delayed, compute

@delayed
def inc(x):
    return x + 1

def colls(ind):
    return [inc(i) for i in xrange(ind)]

data2 = colls(2)
compute(data2)
# [1, 2]


问:
Tool for posting test messages onto a JMS queue?
Can anyone recommend a tool for quickly posting test messages onto a JMS queue?

Description:

The tool should allow the user to enter some data, perhaps an XML
payload, and then submit it to a queue.

I should be able to test consumer without producer.

答:
IBM provide a free, powerful command line tool called perfharness.

Although aimed at benchmarking JMS providers, it's really good at generating (and consuming) test messages. You can use data either generated randomly or taken from a file.

The power features include sending and consuming messages at a fixed rate, using a specific number of threads, using either JMS or native MQ, etc. It generates statistics telling you exactly how fast your queue is performing (hence the name).

The only down side is that it's not super intuitive, given the number of operations it supports.

OwnerDisplayName: redspike

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Christian Berg

OwnerDisplayName: Air


问:
python alternative to the goto command?
I have a python program that is essentailly made up of turtle graphics, and it is basically asking the user how many squares to draw, and then after each square, it adds 1 to a counter using:

```<code>counter=1
<drawing code here>
counter +=1
</code>```

And then after that I wanted to do a check to see if the number of squares is equal to the amount that the user typed in, and if it is, then I wanted to go to the bottom of the script where I would make it say something like done!!. but I dont know how to make it go to a certain part of the script as the goto command that I'm used to in batch isn't supported in python (i know, goto= spaghetti code)

I found an easy workaround is just to download a module that someone made that lets you import the goto command into python and use it just as you would in batch but I would like a native python solution if any!

my current code is:

```<code>from turtle import *
import time
counter=1
color("red", "blue")
down()

user=int(raw_input('how many balls do you want?'))
counter +=1
if user===counter:

# solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(120,0)
down()

counter +=1
if user==counter:

#solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(0,-50)
write("Done!")

time.sleep(5)
</code>```

If you have an answer or alternative to this problem it would be greatly appreciated!

Title: python alternative to the goto command?

Body:
I have a python program that is essentailly made up of turtle graphics, and it is basically asking the user how many squares to draw, and then after each square, it adds 1 to a counter using:

counter=1
<drawing code here>
counter +=1

And then after that I wanted to do a check to see if the number of squares is equal to the amount that the user typed in, and if it is, then I wanted to go to the bottom of the script where I would make it say something like done!!. but I dont know how to make it go to a certain part of the script as the goto command that I'm used to in batch isn't supported in python (i know, goto= spaghetti code)

I found an easy workaround is just to download a module that someone made that lets you import the goto command into python and use it just as you would in batch but I would like a native python solution if any!

my current code is:

from turtle import *
import time
counter=1
color("red", "blue")
down()

user=int(raw_input('how many balls do you want?'))
counter +=1
if user===counter:

# solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(120,0)
down()

counter +=1
if user==counter:

#solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(0,-50)
write("Done!")

time.sleep(5)

If you have an answer or alternative to this problem it would be greatly appreciated!

Body:
some hints:

>>> def square():
    print "+--+"
    print "|  |"
    print "|  |"
    print "+--+"
    print

>>> range(5)
[0, 1, 2, 3, 4]
>>> for x in range(5):
    print x
    square()

0
+--+
|  |
|  |
+--+

1
+--+
|  |

[snip]


问:
ERROR 1045 (28000): Unknown error 1045
After Successfully Installation of mysql-community-server-5.6 on Oracle Linux the mysqld service is started. But when I connect the MySQL following error has been occur.

init.d]# service mysqld status

mysqld (pid  2563) is running...

]# mysql

]# ERROR 1045 (28000): Unknown error 1045

Please advice me how to fix this problem.

答:
This is probably due to invalid or missing authentication data. If you know the root (or any user) password, check if mysql -u root -p works or not.

If yes, you can create /root/.my.cnf in the following format to enable autologin.

[client]
user=root
password='your_root_pass'

Some older versions of MySQL do not accept password within quotes.

Title: ERROR 1045 (28000): Unknown error 1045


问:
How to add data from a text file to ComboBox in JavaFX?
I create a ComboBox in Scene Builder and I want to populate him with data from a text file (eg. Text.txt):

public class ToDoListController implements Initializable {

```<code>@FXML
private ComboBox<?> eventsSelector;
</code>```

How to do this?

Thank you very much!

Two solutions:
1.

@FXML
    private ComboBox eventsSelector;

```<code>@Override
public void initialize(URL location, ResourceBundle resources) {
      List<String> myList;
      try {
        myList = Files.lines(Paths.get("path of my text file")).collect(Collectors.toList());
        eventsSelector.setItems(FXCollections.observableArrayList(myList));
    } catch (IOException e) {
        System.out.println("Don t find file");
    }
</code>```

}
2.

```<code>    //Read items from txt File
    try {
        BufferedReader br = new BufferedReader(new
        FileReader("path of my text file"));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            //Add Item
            eventsSelector.getItems().add(line);

            sb.append(line);
            line = br.readLine();
        }
        br.close();
    } catch (IOException e) {
        System.out.println("Don t find file");

    }
</code>```

答:
Since you want to add content from a .txt file the items in the ComboBox are Strings so you can change to this :

```<code>@FXML
private ComboBox<String> eventsSelector;
</code>```

Then you need a list of the elements that you want to add to the ComboBox<String>, then you can add them simply by:

```<code>List<String> myList = Files.lines(path).collect(Collectors.toList());
comboBox.setItems(FXCollections.observableArrayList(myList));
</code>```

Body:
I create a ComboBox in Scene Builder and I want to populate him with data from a text file (eg. Text.txt):

public class ToDoListController implements Initializable {

@FXML
private ComboBox<?> eventsSelector;

How to do this?

Thank you very much!

Two solutions:
1.

@FXML
    private ComboBox eventsSelector;

@Override
public void initialize(URL location, ResourceBundle resources) {
      List<String> myList;
      try {
        myList = Files.lines(Paths.get("path of my text file")).collect(Collectors.toList());
        eventsSelector.setItems(FXCollections.observableArrayList(myList));
    } catch (IOException e) {
        System.out.println("Don t find file");
    }

}
2.

    //Read items from txt File
    try {
        BufferedReader br = new BufferedReader(new
        FileReader("path of my text file"));
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            //Add Item
            eventsSelector.getItems().add(line);

            sb.append(line);
            line = br.readLine();
        }
        br.close();
    } catch (IOException e) {
        System.out.println("Don t find file");

    }

Body:
Since you want to add content from a .txt file the items in the ComboBox are Strings so you can change to this :

@FXML
private ComboBox<String> eventsSelector;

Then you need a list of the elements that you want to add to the ComboBox<String>, then you can add them simply by:

List<String> myList = Files.lines(path).collect(Collectors.toList());
comboBox.setItems(FXCollections.observableArrayList(myList));


答:
Login

When users click on the link above, it will take them to the login page.

Title: How do I link two HTML pages in a web application?

Body: I've got two HTML pages, with one being an opening page for an application and the second being a login page. I have a button on the opening page and I want to be able to click on it and have it take me to the login page. How do I do this?

Body:
<a href="login.html">Login</a>

When users click on the link above, it will take them to the login page.


问:
Getting Unix timestamp from the past with java 8
since Java 8 I can use instant and LocalDateTime

To get the Unix timestamp:

```<code>long unixTimestamp = Instant.now().getEpochSecond();
</code>```

But if I want to get a time from the past, lets say 2 weeks I use this:

```<code>int unixtime2weeksAgo = (int) ((System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 14) / 1000L)
</code>```

With the docu I couldn't build a solution based on the new java 8 features is here someone who could provide a good solution by using instant or LocalDateTime?

答:
see below:</p>

```<code>import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class TimestampExample {

    public static void main(String[] args) {
        long currentUnixTimestamp = Instant.now().getEpochSecond();
        System.out.println(currentUnixTimestamp);

        // two weeks ago
        long pastTimestamp = Instant.now().minus(14, ChronoUnit.DAYS).getEpochSecond();
        System.out.println(pastTimestamp);

    }
}
</code>```

Body:
since Java 8 I can use instant and LocalDateTime

To get the Unix timestamp:

long unixTimestamp = Instant.now().getEpochSecond();

But if I want to get a time from the past, lets say 2 weeks I use this:

int unixtime2weeksAgo = (int) ((System.currentTimeMillis() - 24 * 60 * 60 * 1000 * 14) / 1000L)

With the docu I couldn't build a solution based on the new java 8 features is here someone who could provide a good solution by using instant or LocalDateTime?

Body:
see below:

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class TimestampExample {

    public static void main(String[] args) {
        long currentUnixTimestamp = Instant.now().getEpochSecond();
        System.out.println(currentUnixTimestamp);

        // two weeks ago
        long pastTimestamp = Instant.now().minus(14, ChronoUnit.DAYS).getEpochSecond();
        System.out.println(pastTimestamp);

    }
}


问:
Converting a number into an array of digits
I'm having a little problem converting a number into an array of digits. </p>

```<code>#include <iostream>

using namespace std;

int main()
{
    int a[11];
    int number;
    cin >> number;
    for (int i = 10; i >= 0; i--)
    {
        a[i] =  number%10;
        number = number/10;
    }
for (int i = 0; i < 11; i++)
        cout << a[i];
cout << endl;
}
</code>```

<p>Instead of getting the number I entered, I get some random digits. This problem doesn't occur when the the number I enter is less or equal than 9 digits. </p>

答:
I will suggest to init the array(is a good practice) doing somethinglike:

```<code>int a[11] = {-1};
</code>```

and if you add a newline char after printing every element of the array then it will become meaningful and easier to read...

your code is working as expected actually

```<code>#include <iostream>

using namespace std;

int main()
{
    int a[11] = {-1};
    int number;
    cin >> number;
    for (int i = 10; i >= 0; i--)
    {

        a[i] = number % 10;
        number = number / 10;
    }
    for (int i = 0; i < 11; i++)
        cout <<"@[" <<i<<"]: "<< a[i] <<endl;
    cin.get();
}
</code>```

for an input like 432

you get the output:

Body:
I'm having a little problem converting a number into an array of digits.

#include <iostream>

using namespace std;

int main()
{
    int a[11];
    int number;
    cin >> number;
    for (int i = 10; i >= 0; i--)
    {
        a[i] =  number%10;
        number = number/10;
    }
for (int i = 0; i < 11; i++)
        cout << a[i];
cout << endl;
}

Instead of getting the number I entered, I get some random digits. This problem doesn't occur when the the number I enter is less or equal than 9 digits.

Body:
I will suggest to init the array(is a good practice) doing somethinglike:

int a[11] = {-1};

and if you add a newline char after printing every element of the array then it will become meaningful and easier to read...

your code is working as expected actually

#include <iostream>

using namespace std;

int main()
{
    int a[11] = {-1};
    int number;
    cin >> number;
    for (int i = 10; i >= 0; i--)
    {

        a[i] = number % 10;
        number = number / 10;
    }
    for (int i = 0; i < 11; i++)
        cout <<"@[" <<i<<"]: "<< a[i] <<endl;
    cin.get();
}

for an input like 432

you get the output:


问:
ASP MVC HTML Helpers - Good or Bad?
I understand the reason for having the HTML helpers in ASP.NET MVC and extending this to provide your own, but I am wondering whether using HTML helpers is a good idea.

I thought one of the benefits of ASP.NET MVC is control over the HTML. If you start hiding it away in helper functions that generate HTML don't you start losing visibility? I guess this isn't such a problem when you are generating simple controls such as a button, but I have seen the use of html helpers to create grids and more complex HTML output.

Now I also understand the reason for doing so is to keep things DRY, avoiding duplication. But is there not a danger of having something akin to code-behind here? In addition, what if you are working in collaboration with designers? Generally the designer would be creating the markup and applying styling. If you start injecting your view with helpers that generate markup, doesn't this make such collaboration difficult?

答:
I think one important point that the others haven't mentioned is portability of your views.

You can move your HTML, javascript and CSS to an application on another platform immediately. You don't have to convert all the ugly HTMLHiders.. sorry, HTMLHelpers.. to actual HTML.

While I have the highest regard for the .NET framework that reduces my development time and makes my job easy, I strongly feel that views should be non-proprietary.

You can gain almost all of the benefit from the framework in the model and controller anyway. Injecting dependencies on the framework in your presentation layer is not at all worth the tradeoff, IMO.

Title: ASP MVC HTML Helpers - Good or Bad?


问:
Count number of selected rows in ag-grid
I want to count the number of selected rows but it seems onRowClicked or onRowSelected happens before the row i click actually is selected.

How can I count the number of rows when I select a row? I thought this was the way to go.

```<code>this.gridOptions.onRowSelected = function (params) {
    console.log(this.gridOptions.api.getSelectedRows().length)
    // Prints one less then the number of rows that is selected.
}
</code>```

答:
In a React (with ES6) project I use this:

```<code>onSelectionChanged = debounce((e) => {
    this.setState({
        selectedRows: this.api.getSelectedRows(),
    });
}, 1)
</code>```

(this.api is https://www.ag-grid.com/javascript-grid-api/?framework=all#gsc.tab=0)

I use Lodash's debounce to solve a performance problem if many rows are selected at the same time. (Although after some quick testing, looks like this has been fixed in ag-grid at some point.)

The simplest version could look like (untested):

```<code>this.gridOptions.onSelectionChanged = function () {
    console.log(this.gridOptions.api.getSelectedRows().length);
}
</code>```

Body:
I want to count the number of selected rows but it seems onRowClicked or onRowSelected happens before the row i click actually is selected.

How can I count the number of rows when I select a row? I thought this was the way to go.

this.gridOptions.onRowSelected = function (params) {
    console.log(this.gridOptions.api.getSelectedRows().length)
    // Prints one less then the number of rows that is selected.
}

Body:
In a React (with ES6) project I use this:

onSelectionChanged = debounce((e) => {
    this.setState({
        selectedRows: this.api.getSelectedRows(),
    });
}, 1)

(this.api is https://www.ag-grid.com/javascript-grid-api/?framework=all#gsc.tab=0)

I use Lodash's debounce to solve a performance problem if many rows are selected at the same time. (Although after some quick testing, looks like this has been fixed in ag-grid at some point.)

The simplest version could look like (untested):

this.gridOptions.onSelectionChanged = function () {
    console.log(this.gridOptions.api.getSelectedRows().length);
}


问:
Search many expressions in many documents using Python
I often have to search many words (1000+) in many documents (million+). I need position of matched word (if matched).

So slow pseudo version of code is

```<code>for text in documents:
     for word in words:
             position = search(word, text)
             if position:
                  print word, position
</code>```

Is there any fast Python module for doing this? Or should I implement something myself?

答:
What's wrong with grep?

So you have to use python? How about:

```<code>import subprocess

subprocess.Popen('grep <pattern> <file>')
</code>```

which is insane. But hey! You are using python ;-)

Body:
I often have to search many words (1000+) in many documents (million+). I need position of matched word (if matched).

So slow pseudo version of code is

for text in documents:
     for word in words:
             position = search(word, text)
             if position:
                  print word, position

Is there any fast Python module for doing this? Or should I implement something myself?

Body:
What's wrong with grep?

So you have to use python? How about:

import subprocess

subprocess.Popen('grep <pattern> <file>')

which is insane. But hey! You are using python ;-)


问:
C# MVC 5 - json object with properties and objects null inside it
My project have huge objects but in the most of times many properties and other objects inside it aren't used, is there a way to not send to the JSON the objects and properties that is null?</p>

答:
Yes, there are, but exactly how to do it depends on which serializer you're using.

For example, if you're using the DataContractJsonSerializer, you can use

```<code>[DataMember(EmitDefaultValue = false)]
</code>```

on the members, or globally using

```<code>new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
};
</code>```

(See How to set the EmitDefaultValue to false globally for all Data Members in Web API? for details.)

Body:
Yes, there are, but exactly how to do it depends on which serializer you're using.

For example, if you're using the DataContractJsonSerializer, you can use

[DataMember(EmitDefaultValue = false)]

on the members, or globally using

new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
};

(See How to set the EmitDefaultValue to false globally for all Data Members in Web API? for details.)


问:
After changing the url in .htaccess php is not working
I changed this url
 http://localhost/rozgar/job.php?search=Testing%201&id=43
 to this
http://localhost/rozgar/job/Testing%201/43
by using .htaccess

```<code>RewriteRule ^job/([A-Za-z]+) job.php?id=$1&search=$2
</code>```

Link is working fine but php is not loading data from database it's showing me error..

```<code>    <?php
include "inc/db.php";
$id = @$_GET['id'];
$search = @$_GET['search'];
session_start();
$email = @$_SESSION['email'];

  $id=@$_GET['id'];
  $query="select * from company,jobs where company.id = jobs.company_id AND jobs.id = '$id'";
$run=mysqli_query($db,$query);

while ($row = mysqli_fetch_assoc($run)) {
}
</code>```

答:
you have to try this rule. You have passed value only for search field but you also passed value for id  like (0-9). so then your htaccess rule make like below.

```<code>RewriteRule ^job/([A-Za-z-]+)/([0-9]+) job.php?search=$1&id=$2
</code>```

After this you can cehck it out this url.

```<code> http://localhost/rozgar/job/testing/43
</code>```

And remember one thing you should not pass value in url which have space like "testing 002" the your htaccess rule break. For this you have to convert space in to underscore.

Body:
I changed this url
 http://localhost/rozgar/job.php?search=Testing%201&id=43
 to this
http://localhost/rozgar/job/Testing%201/43
by using .htaccess

RewriteRule ^job/([A-Za-z]+) job.php?id=$1&search=$2

Link is working fine but php is not loading data from database it's showing me error..

    <?php
include "inc/db.php";
$id = @$_GET['id'];
$search = @$_GET['search'];
session_start();
$email = @$_SESSION['email'];

  $id=@$_GET['id'];
  $query="select * from company,jobs where company.id = jobs.company_id AND jobs.id = '$id'";
$run=mysqli_query($db,$query);

while ($row = mysqli_fetch_assoc($run)) {
}

Body:
you have to try this rule. You have passed value only for search field but you also passed value for id  like (0-9). so then your htaccess rule make like below.

RewriteRule ^job/([A-Za-z-]+)/([0-9]+) job.php?search=$1&id=$2

After this you can cehck it out this url.

 http://localhost/rozgar/job/testing/43

And remember one thing you should not pass value in url which have space like "testing 002" the your htaccess rule break. For this you have to convert space in to underscore.


问:
Using two RequestBody in Spring Restful Service
I am trying to use two request bodies for a Mapping in Spring Rest.

I have already read through some questions and there are suggestion to use two different methods with consumes one as application/json and other as application/x-www-form-urlencoded.

I wanted to know if this the only approach or are there any alternatives so that i could use both application/json and urlencoded as my RequestBody.

答:
I am not sure why would you need two - @RequestBody - one for application/json & other for application/x-www-form-urlencoded while conceptually a HTTP request has only one body so two bodies don't make sense to me.

What you are looking for is same method handling two different content - types not two bodies. Body generation / conversion process will vary as per content type but there remains only one body since client will send same data.

Two different content types are already supported as highlighted here

With consumes={MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_FORM_URLENCODED_VALUE} , you can send both content - types with a single @RequestBody by changing content type header in your request.

There can be only one method for a unique @RequestMapping otherwise it will become ambiguous mapping.

Multiple mappings can map to single method but vice versa is not allowed.


问:
Public schema is not defined in security definer function's search_path but it is still accessible
When I define a function such as this one:

```<code>create or replace function test_func_a()
returns table(search_path name[], public_func_result text) as $$
  select current_schemas('true'), trim(' does it work ');
$$ language sql stable security definer set search_path = pg_temp;
select test_func_a();
                test_func_a
-------------------------------------------
 ("{pg_catalog,pg_temp_2}","does it work")
</code>```

Why am I still able to use a function in the public schema such as trim or current_schemas for that matter? Shouldn't it only work if I explicitly use public.trim()?

Functions that are in schemas that I've created do not work in the same fashion. In this example I attempt to use a function in the util schema without setting it in the search_path:

```<code>create or replace function test_func_b()
returns table(search_path name[], public_func_result text) as $$
  select current_schemas('true'), trim_whitespace(' does it work ');
$$ language sql stable security definer set search_path = pg_temp;
ERROR:  function trim_whitespace(unknown) does not exist
LINE 3:   select current_schemas('true'), trim_whitespace(' does it ...
                                          ^
HINT:  No function matches the given name and argument types. You might need
to add explicit type casts.
</code>```

Outside of functions, my search_path is set as this:

```<code>select current_schemas('true');
                      current_schemas
 ------------------------------------------------------------
 {pg_temp_2,pg_catalog,public,util}
</code>```

答:
Look inside your public schema. Do you see TRIM? current_schemas? No, they're not there. Have a read of this https://www.postgresql.org/docs/current/static/ddl-schemas.html

On the public schema:

By default [...] tables (and other objects) are automatically put into
  a schema named "public". Every new database contains such a schema.
  [...] There is nothing special about the public schema except that it
  exists by default. It can be dropped, too.

So how is it resolving current_schemas?

In addition to public and user-created schemas, each database contains
  a pg_catalog schema, which contains the system tables and all the
  built-in data types, functions, and operators. pg_catalog is always
  effectively part of the search path. If it is not named explicitly in
  the path then it is implicitly searched before searching the path's
  schemas. This ensures that built-in names will always be findable.
  However, you can explicitly place pg_catalog at the end of your search
  path if you prefer to have user-defined names override built-in names.

Have a look inside pg_catalog (under Catalogs in PGAdmin), current_schemas is in the function list there.

And the built-in function TRIM is a keyword which PG recognises, see https://www.postgresql.org/docs/current/static/sql-keywords-appendix.html

Body:
When I define a function such as this one:

create or replace function test_func_a()
returns table(search_path name[], public_func_result text) as $$
  select current_schemas('true'), trim(' does it work ');
$$ language sql stable security definer set search_path = pg_temp;
select test_func_a();
                test_func_a
-------------------------------------------
 ("{pg_catalog,pg_temp_2}","does it work")

Why am I still able to use a function in the public schema such as trim or current_schemas for that matter? Shouldn't it only work if I explicitly use public.trim()?

Functions that are in schemas that I've created do not work in the same fashion. In this example I attempt to use a function in the util schema without setting it in the search_path:

create or replace function test_func_b()
returns table(search_path name[], public_func_result text) as $$
  select current_schemas('true'), trim_whitespace(' does it work ');
$$ language sql stable security definer set search_path = pg_temp;
ERROR:  function trim_whitespace(unknown) does not exist
LINE 3:   select current_schemas('true'), trim_whitespace(' does it ...
                                          ^
HINT:  No function matches the given name and argument types. You might need
to add explicit type casts.

Outside of functions, my search_path is set as this:

select current_schemas('true');
                      current_schemas
 ------------------------------------------------------------
 {pg_temp_2,pg_catalog,public,util}


问:
Incorrect port number returned by $_SERVER['server_port']
Scenario: I'm working on a Apache web server with some PHP.  I point my browser at https://my.example.com/test.php that has the following lines of code in it:

```<code>```
<?php
print_r($_SERVER);
?>
```
</code>```

The value printed out for SERVER_PORT is 80, not 443.  But if I go to https://my.example.com:80/test.php the web server (Apache) barfs (An error occurred during a connection to my.example.com:80. SSL received a record that exceeded the maximum permissible length. Error code: ssl_error_rx_record_too_long).  If I go to https://my.example.com:443/test.php then the URL redirects to https://my.example.com/test.php with no errors or problems except that my PHP prints out that the server port is 80 instead of 443.

Here's the relevant section from the conf.d/ssl.conf file (I removed what I believe are extraneous directives out and replaced the actual IP address with the word IP_ADDRESS):

```<code>Listen IP_ADDRESS:443
<VirtualHost *:443>
        ServerName my.example.com
        ServerAlias my
        DocumentRoot "/path/to/document_root/htdocs"
        Options +Indexes
</VirtualHost>
</code>```

Here is the full print out of $_SERVER variable (with my server details redacted/changed to anonymous examples):

```<code>Array
(
    [HTTP_HOST] => my.example.com
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5
    [HTTP_ACCEPT_ENCODING] => gzip,deflate
    [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
    [HTTP_KEEP_ALIVE] => 115
    [HTTP_CONNECTION] => keep-alive
    [HTTP_COOKIE] => PHPSESSID=randomstring_yes_I'm_that_paranoid
    [PATH] => /sbin:/usr/sbin:/bin:/usr/bin
    [SERVER_SIGNATURE] =>
Apache/2.2.3 (Red Hat) Server at my.example.com Port 80

    [SERVER_SOFTWARE] => Apache/2.2.3 (Red Hat)
    [SERVER_NAME] => my.example.com
    [SERVER_ADDR] => IP_ADDRESS_1
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => IP_ADDRESS_2
    [DOCUMENT_ROOT] => /path/to/document_root/htdocs
    [SERVER_ADMIN] => admin@example.com
    [SCRIPT_FILENAME] => /path/to/document_root/htdocs/test.php
    [REMOTE_PORT] => 49178
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => GET
    [QUERY_STRING] =>
    [REQUEST_URI] => /test.php
    [SCRIPT_NAME] => /test.php
    [PHP_SELF] => /test.php
    [REQUEST_TIME] => 1292273758
)
</code>```

As you can see, the SERVER_PORT is 80 and $_SERVER['HTTPS'] isn't set.  According to the PHP docs, I thought it was supposed to be set to a non-empty value if the PHP script is accessed via HTTPS (which is what I'm doing).

Any idea what's going on?  I'm just the web developer - I don't manage this server but my server admin tells me everything is working but I would like to know why $_SERVER['SERVER_PORT'] is returning 80 instead of 443 when viewing an HTTPS URL.

EDIT: I've edited the above example to illustrate my results in printing out the entire $_SERVER variable.

EDIT 2: Trying https://my.example.com:443/test.php as suggested in the comments below does the same thing - SERVER_PORT is 80 and HTTPS isn't set (specifically trying this URL redirects to https://my.example.com/test.php).

EDIT 3: OK, I've posted what I believe is the answer to this below (TL;DR: moving the SSL directives inside the VirtualHost directive and changing that directive to reference my site using it's IP address rather than a wildcard appears to have resolved the problem).

答:
OK, I think I figured it out.  My server admin changed the conf.d/ssl.conf from

```<code>SSLEngine On
# and other SSL directives

<VirtualHost *:443>
        ServerName my.example.com
        ServerAlias my

        # and more directives
</VirtualHost>
</code>```

to

```<code><VirtualHost IP_ADDRESS:443>
        ServerName my.example.com
        ServerAlias my

        SSLEngine On
        # and other SSL directives

        # and more directives
</VirtualHost>
</code>```

and now PHP is seeing the correct SERVER_PORT # (443) and $_SERVER['HTTPS'] is also now set.  So either it was putting the SSL directives inside the VirtualHost directive for my.example.com or maybe it was changing the VirtualHost directive to reference an actual IP address rather than a wild card that resolved this issue.  Thanks everyone for your help on this.

Body:
Scenario: I'm working on a Apache web server with some PHP.  I point my browser at https://my.example.com/test.php that has the following lines of code in it:

<?php
print_r($_SERVER);
?>

The value printed out for SERVER_PORT is 80, not 443.  But if I go to https://my.example.com:80/test.php the web server (Apache) barfs (An error occurred during a connection to my.example.com:80. SSL received a record that exceeded the maximum permissible length. Error code: ssl_error_rx_record_too_long).  If I go to https://my.example.com:443/test.php then the URL redirects to https://my.example.com/test.php with no errors or problems except that my PHP prints out that the server port is 80 instead of 443.

Here's the relevant section from the conf.d/ssl.conf file (I removed what I believe are extraneous directives out and replaced the actual IP address with the word IP_ADDRESS):

Listen IP_ADDRESS:443
<VirtualHost *:443>
        ServerName my.example.com
        ServerAlias my
        DocumentRoot "/path/to/document_root/htdocs"
        Options +Indexes
</VirtualHost>

Here is the full print out of $_SERVER variable (with my server details redacted/changed to anonymous examples):

Array
(
    [HTTP_HOST] => my.example.com
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.11) Gecko/20101012 Firefox/3.6.11
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5
    [HTTP_ACCEPT_ENCODING] => gzip,deflate
    [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7
    [HTTP_KEEP_ALIVE] => 115
    [HTTP_CONNECTION] => keep-alive
    [HTTP_COOKIE] => PHPSESSID=randomstring_yes_I'm_that_paranoid
    [PATH] => /sbin:/usr/sbin:/bin:/usr/bin
    [SERVER_SIGNATURE] =>
Apache/2.2.3 (Red Hat) Server at my.example.com Port 80

    [SERVER_SOFTWARE] => Apache/2.2.3 (Red Hat)
    [SERVER_NAME] => my.example.com
    [SERVER_ADDR] => IP_ADDRESS_1
    [SERVER_PORT] => 80
    [REMOTE_ADDR] => IP_ADDRESS_2
    [DOCUMENT_ROOT] => /path/to/document_root/htdocs
    [SERVER_ADMIN] => admin@example.com
    [SCRIPT_FILENAME] => /path/to/document_root/htdocs/test.php
    [REMOTE_PORT] => 49178
    [GATEWAY_INTERFACE] => CGI/1.1
    [SERVER_PROTOCOL] => HTTP/1.1
    [REQUEST_METHOD] => GET
    [QUERY_STRING] =>
    [REQUEST_URI] => /test.php
    [SCRIPT_NAME] => /test.php
    [PHP_SELF] => /test.php
    [REQUEST_TIME] => 1292273758
)

As you can see, the SERVER_PORT is 80 and $_SERVER['HTTPS'] isn't set.  According to the PHP docs, I thought it was supposed to be set to a non-empty value if the PHP script is accessed via HTTPS (which is what I'm doing).

Any idea what's going on?  I'm just the web developer - I don't manage this server but my server admin tells me everything is working but I would like to know why $_SERVER['SERVER_PORT'] is returning 80 instead of 443 when viewing an HTTPS URL.

EDIT: I've edited the above example to illustrate my results in printing out the entire $_SERVER variable.

EDIT 2: Trying https://my.example.com:443/test.php as suggested in the comments below does the same thing - SERVER_PORT is 80 and HTTPS isn't set (specifically trying this URL redirects to https://my.example.com/test.php).

EDIT 3: OK, I've posted what I believe is the answer to this below (TL;DR: moving the SSL directives inside the VirtualHost directive and changing that directive to reference my site using it's IP address rather than a wildcard appears to have resolved the problem).

Body:
OK, I think I figured it out.  My server admin changed the conf.d/ssl.conf from

SSLEngine On
# and other SSL directives

<VirtualHost *:443>
        ServerName my.example.com
        ServerAlias my

        # and more directives
</VirtualHost>

to

<VirtualHost IP_ADDRESS:443>
        ServerName my.example.com
        ServerAlias my

        SSLEngine On
        # and other SSL directives

        # and more directives
</VirtualHost>

and now PHP is seeing the correct SERVER_PORT # (443) and $_SERVER['HTTPS'] is also now set.  So either it was putting the SSL directives inside the VirtualHost directive for my.example.com or maybe it was changing the VirtualHost directive to reference an actual IP address rather than a wild card that resolved this issue.  Thanks everyone for your help on this.


问:
Error 404 on delete row codeigniter 2
im deleting a row in coneigniter2  but it takes me to 404 page
(The page you requested was not found.)

this is my code

Controler Post

```<code> class Posts extends CI_Controller{

public function index(){
 $data['title'] = 'Ultimos Post';
  $data['posts'] = $this->Post_model->get_posts();
   $this->load->view('templates/header');
    $this->load->view('posts/index',$data);
     $this->load->view('templates/footer');
 }
   ...

   public function delete($id){
      //apagar post pelo id
         $this->Post_Model->delete_post($id);
          redirect('posts');

   }}
</code>```

Post Model

```<code> class Post_model extends Ci_Model{
  ...

    public function delete_post($id) {

              $this->db->where('id',$id);
                $this->db->delete('posts');

        }}
</code>```

In the View.php

```<code><?php echo form_open('/posts/delete/'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger" name="delete">
</code>```

Routes.php

```<code>$route['posts/create'] = 'posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

答:
Replace this code

Controller

```<code>class Posts extends CI_Controller{
...
    public function delete(){
        $id = $this->input->post('id');
        $this->Post_Model->delete_post($id);
        redirect('posts');
    }
}
</code>```

Model

```<code>class Post_model extends Ci_Model{
...
    public function delete_post($id) {
        $this->db->where('id',$id);
        $this->db->delete('posts');
    }
}
</code>```

View

```<code><?php echo form_open('/posts/delete'); ?>
<input type="hidden" name="id" value="<?php echo $post['id']; ?>" />
<input type="submit" value="Delete" class="btn btn-danger" name="delete">
</form>
</code>```

Title: Error 404 on delete row codeigniter 2

Body:
im deleting a row in coneigniter2  but it takes me to 404 page
(The page you requested was not found.)

this is my code

Controler Post

 class Posts extends CI_Controller{

public function index(){
 $data['title'] = 'Ultimos Post';
  $data['posts'] = $this->Post_model->get_posts();
   $this->load->view('templates/header');
    $this->load->view('posts/index',$data);
     $this->load->view('templates/footer');
 }
   ...

   public function delete($id){
      //apagar post pelo id
         $this->Post_Model->delete_post($id);
          redirect('posts');

   }}

Post Model

 class Post_model extends Ci_Model{
  ...

    public function delete_post($id) {

              $this->db->where('id',$id);
                $this->db->delete('posts');

        }}

In the View.php

<?php echo form_open('/posts/delete/'.$post['id']);?>
<input type="submit" value="Delete" class="btn btn-danger" name="delete">

Routes.php

$route['posts/create'] = 'posts/create';
$route['posts/(:any)'] = 'posts/view/$1';
$route['posts'] = 'posts/index';
$route['default_controller'] = "pages/view";
$route['(:any)'] = 'pages/view/$1';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

Body:
Replace this code

Controller

class Posts extends CI_Controller{
...
    public function delete(){
        $id = $this->input->post('id');
        $this->Post_Model->delete_post($id);
        redirect('posts');
    }
}

Model

class Post_model extends Ci_Model{
...
    public function delete_post($id) {
        $this->db->where('id',$id);
        $this->db->delete('posts');
    }
}

View

<?php echo form_open('/posts/delete'); ?>
<input type="hidden" name="id" value="<?php echo $post['id']; ?>" />
<input type="submit" value="Delete" class="btn btn-danger" name="delete">
</form>


问:
Can I join table one more time to existing join?
I have following query:

```<code>SELECT *
FROM A
  JOIN B ON A.id = B.a_id
  JOIN C ON B.id = C.b_id
  JOIN D ON C.id = D.c_id;
</code>```

I need to join another table to it - table E.
But I need to join it on B.id and E.a_id.
Can I write query like that:

```<code>SELECT *
FROM A
  JOIN B ON A.id = B.a_id
  JOIN C ON B.id = C.b_id
  JOIN D ON C.id = D.c_id
  JOIN E ON B.id = E.a_id;
</code>```

Is this correct way of doing this?

答:
Yes you can. If you think that joins just join tables together, this is probably what's steering you wrong.

Take a simple example:

```<code>SELECT *
FROM
   A
     INNER JOIN --J1
   B
     ON A.id = B.a_id
     INNER JOIN  --J2
   C
     ON B.id = C.b_id
</code>```

If we look at the first JOIN, J1, it's true that this is a join between two tables - A and B. But in the second JOIN, J2, the join is between table C and the result of the previous JOIN. At this point, it's valid to reference any of A, B or C in this join's ON clause (or none of them, but that's usually an error).

So long as you're not mixing around ON clauses (each JOIN is immediately followed by its matching ON clause), each JOIN is always going to be adding a new table (or another instance of an existing table) onto the result of the previous JOIN and all tables will be in scope for the ON clause.

Since I've given it as an example in comments and it's proving a discussion point, let's also have:

```<code>select
    *
from
    t1
       inner join --J1
    t2
       inner join --J2
    t3
       on t2.id = t3.id --O1
       on t1.id = t3.id --O2
</code>```

What's going on here? Well, JOIN and ON don't have to appear together, and they actually act a bit like parenthesis. So, the first JOIN that happens in this from clause is J2 - and it's matched to O1. After that JOIN, we then complete join J1 using O2. In this case, J1 ends up being a join between t1 and the result of the join between t2 and t3.

Because you have to carefully parse this style to work out what order joins are happening in and which ON clauses match to which JOIN, I'd not normally recommend writing such joins.

Body:
I have following query:

SELECT *
FROM A
  JOIN B ON A.id = B.a_id
  JOIN C ON B.id = C.b_id
  JOIN D ON C.id = D.c_id;

I need to join another table to it - table E.
But I need to join it on B.id and E.a_id.
Can I write query like that:

SELECT *
FROM A
  JOIN B ON A.id = B.a_id
  JOIN C ON B.id = C.b_id
  JOIN D ON C.id = D.c_id
  JOIN E ON B.id = E.a_id;

Is this correct way of doing this?

Body:
Yes you can. If you think that joins just join tables together, this is probably what's steering you wrong.

Take a simple example:

SELECT *
FROM
   A
     INNER JOIN --J1
   B
     ON A.id = B.a_id
     INNER JOIN  --J2
   C
     ON B.id = C.b_id

If we look at the first JOIN, J1, it's true that this is a join between two tables - A and B. But in the second JOIN, J2, the join is between table C and the result of the previous JOIN. At this point, it's valid to reference any of A, B or C in this join's ON clause (or none of them, but that's usually an error).

So long as you're not mixing around ON clauses (each JOIN is immediately followed by its matching ON clause), each JOIN is always going to be adding a new table (or another instance of an existing table) onto the result of the previous JOIN and all tables will be in scope for the ON clause.

Since I've given it as an example in comments and it's proving a discussion point, let's also have:

select
    *
from
    t1
       inner join --J1
    t2
       inner join --J2
    t3
       on t2.id = t3.id --O1
       on t1.id = t3.id --O2

What's going on here? Well, JOIN and ON don't have to appear together, and they actually act a bit like parenthesis. So, the first JOIN that happens in this from clause is J2 - and it's matched to O1. After that JOIN, we then complete join J1 using O2. In this case, J1 ends up being a join between t1 and the result of the join between t2 and t3.

Because you have to carefully parse this style to work out what order joins are happening in and which ON clauses match to which JOIN, I'd not normally recommend writing such joins.


问:
Access vba Check if file exists
I have a database split in FrontEnd and BackEnd.

I have it running:
i) in my office
ii) updating/testing in my personal computer.

My BackEnd file is running in different Folder location according to computer running.

I want to place a code and check if file exist.

Code:

```<code>Sub FileExists()
Dim strPath As String   '<== Office.
Dim strApplicationFolder As String
Dim strPathAdmin As String   '<== Admin.

strPath = "\\iMac\Temp\"
strApplicationFolder = Application.CurrentProject.Path
strPathAdmin = strApplicationFolder & "\Temp\"

If Dir(strApplicationFolder & "SerialKey.txt") = "" Then
'===> Admin User.
    If Dir(strPathAdmin & "*.*") = "" Then
        '===> Empty Folder.
    Else
        '===> Files on folder.
    End If
Else
    '===> Office User.
    If Dir(strPath & "*.*") = "" Then
        '===> Empty Folder.
    Else
        '===> Files on folder.
    End If
End If
End Sub()
</code>```

I have this until now.

Any help.

Thank you...

答:
Create a small function to check if a file exists and call it when needed.

```<code>Public Function FileExists(ByVal path_ As String) As Boolean
    FileExists = (Len(Dir(path_)) > 0)
End Function
</code>```

Since the backend database paths dont change, why dont you declare two constants and simply check their value?

```<code>Sub Exist()

    Const workFolder As String = "C:\Work Folder\backend.accdb"
    Const personalFolder As String = "D:\Personal Folder\backend.accdb"

    If FileExists(workFolder) Then
        'Work folder exists
    End If

    '....

    If FileExists(personalFolder) Then
        'Personal folder exists
    End If
End Sub
</code>```

Title: Access vba Check if file exists

Body:
I have a database split in FrontEnd and BackEnd.

I have it running:
i) in my office
ii) updating/testing in my personal computer.

My BackEnd file is running in different Folder location according to computer running.

I want to place a code and check if file exist.

Code:

Sub FileExists()
Dim strPath As String   '<== Office.
Dim strApplicationFolder As String
Dim strPathAdmin As String   '<== Admin.

strPath = "\\iMac\Temp\"
strApplicationFolder = Application.CurrentProject.Path
strPathAdmin = strApplicationFolder & "\Temp\"

If Dir(strApplicationFolder & "SerialKey.txt") = "" Then
'===> Admin User.
    If Dir(strPathAdmin & "*.*") = "" Then
        '===> Empty Folder.
    Else
        '===> Files on folder.
    End If
Else
    '===> Office User.
    If Dir(strPath & "*.*") = "" Then
        '===> Empty Folder.
    Else
        '===> Files on folder.
    End If
End If
End Sub()

I have this until now.

Any help.

Thank you...

Body:
Create a small function to check if a file exists and call it when needed.

Public Function FileExists(ByVal path_ As String) As Boolean
    FileExists = (Len(Dir(path_)) > 0)
End Function

Since the backend database paths dont change, why dont you declare two constants and simply check their value?

Sub Exist()

    Const workFolder As String = "C:\Work Folder\backend.accdb"
    Const personalFolder As String = "D:\Personal Folder\backend.accdb"

    If FileExists(workFolder) Then
        'Work folder exists
    End If

    '....

    If FileExists(personalFolder) Then
        'Personal folder exists
    End If
End Sub


问:
Nginx Error ("http" directive is not allowed here in /etc/nginx/sites-enabled/abc)
I am geeting below error while starting Nginx service

"http" directive is not allowed here in /etc/nginx/sites-enabled/abc:1

Here is my abc config

```<code>worker_processes  1;
error_log /usr/local/openresty/nginx/logs/lua.log debug;
events {
  worker_connections 1024;
}
http {
  upstream kibana {
    server server1:30001;
    server server2:30001;
    keepalive 15;
  }
  server {
    listen 8882;
    location / {
        ssl_certificate /etc/pki/tls/certs/ELK-Stack.crt;
        ssl_certificate_key /etc/pki/tls/private/ELK-Stack.key;
        ssl_session_cache shared:SSL:10m;
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/htpasswd.users;
      proxy_pass http://kibana;
      proxy_redirect off;
      proxy_buffering off;
      proxy_http_version 1.1;
      proxy_set_header Connection "Keep-Alive";
      proxy_set_header Proxy-Connection "Keep-Alive";
    }
  }
}
</code>```

--> FYI I am creating this file in /etc/nginx/sites-available and linking it to
/etc/nginx/sites-enabled . I am providing a link using following command

```<code>sudo ln -s /etc/nginx/sites-available/abc /etc/nginx/sites-enabled/abc
</code>```

After the above command I can see a link is been created in /etc/nginx/sites-enabled directory .

Please suggest what I am doing wrong ?

Regards,

答:
The http directive dos not belong there.

In the ngnix.conf you have already the http directive

```<code>http {
    ..config logs ...
    inclide etc/ngnix/sites-enabled/*;  <--- This Line include your files
    .. more config...
    server {
       (..default server ...)
       location / {
           index
           root
       }
    }
}
</code>```

The files in your sites enabled must only contain servers, the http directive is in the principal configuration.
I would try:

```<code>events {
  worker_connections 1024;
}

  upstream kibana {
    server server1:30001;
    server server2:30001;
    keepalive 15;
  }

    error_log /usr/local/openresty/nginx/logs/lua.log debug;

    listen 8882;
    location / {
        basic "Restricted Access";
        auth_basic_user_file /etc/nginx/htpasswd.users;
      proxy_pass http://kibana;
      proxy_redirect off;
      proxy_buffering off;
      proxy_http_version 1.1;
      proxy_set_header Connection "Keep-Alive";
      proxy_set_header Proxy-Connection "Keep-Alive";
    }

    ssl_certificate /etc/pki/tls/certs/ELK-Stack.crt;
    ssl_certificate_key /etc/pki/tls/private/ELK-Stack.key;
    ssl_session_cache shared:SSL:10m;

}
</code>```

Body:
I am geeting below error while starting Nginx service

"http" directive is not allowed here in /etc/nginx/sites-enabled/abc:1

Here is my abc config

worker_processes  1;
error_log /usr/local/openresty/nginx/logs/lua.log debug;
events {
  worker_connections 1024;
}
http {
  upstream kibana {
    server server1:30001;
    server server2:30001;
    keepalive 15;
  }
  server {
    listen 8882;
    location / {
        ssl_certificate /etc/pki/tls/certs/ELK-Stack.crt;
        ssl_certificate_key /etc/pki/tls/private/ELK-Stack.key;
        ssl_session_cache shared:SSL:10m;
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/htpasswd.users;
      proxy_pass http://kibana;
      proxy_redirect off;
      proxy_buffering off;
      proxy_http_version 1.1;
      proxy_set_header Connection "Keep-Alive";
      proxy_set_header Proxy-Connection "Keep-Alive";
    }
  }
}

--> FYI I am creating this file in /etc/nginx/sites-available and linking it to
/etc/nginx/sites-enabled . I am providing a link using following command

sudo ln -s /etc/nginx/sites-available/abc /etc/nginx/sites-enabled/abc

After the above command I can see a link is been created in /etc/nginx/sites-enabled directory .

Please suggest what I am doing wrong ?

Regards,

Body:
The http directive dos not belong there.

In the ngnix.conf you have already the http directive

http {
    ..config logs ...
    inclide etc/ngnix/sites-enabled/*;  <--- This Line include your files
    .. more config...
    server {
       (..default server ...)
       location / {
           index
           root
       }
    }
}

The files in your sites enabled must only contain servers, the http directive is in the principal configuration.
I would try:

events {
  worker_connections 1024;
}

  upstream kibana {
    server server1:30001;
    server server2:30001;
    keepalive 15;
  }

    error_log /usr/local/openresty/nginx/logs/lua.log debug;

    listen 8882;
    location / {
        basic "Restricted Access";
        auth_basic_user_file /etc/nginx/htpasswd.users;
      proxy_pass http://kibana;
      proxy_redirect off;
      proxy_buffering off;
      proxy_http_version 1.1;
      proxy_set_header Connection "Keep-Alive";
      proxy_set_header Proxy-Connection "Keep-Alive";
    }

    ssl_certificate /etc/pki/tls/certs/ELK-Stack.crt;
    ssl_certificate_key /etc/pki/tls/private/ELK-Stack.key;
    ssl_session_cache shared:SSL:10m;

}


问:
why is cordova downloading gradle again?
I am trying to run my ionic 2 app on my android phone. I have installed the android sdk and gradle. But when i run cordova run android, it starts downloading the 3.3 version of gradle while my gradle version is 3.5. Also, the download got stuck somewhere for 20 minutes so i stopped it .
Why is this happening?

gradle -v` returns

```<code>------------------------------------------------------------
Gradle 3.5
------------------------------------------------------------

Build time:   2017-04-10 13:37:25 UTC
Revision:     b762622a185d59ce0cfc9cbc6ab5dd22469e18a6

Groovy:       2.4.10
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_121 (Oracle Corporation 25.121-b13)
OS:           Linux 3.16.0-77-generic amd64
</code>```

cordova run android =>

```<code>`ANDROID_HOME=/home/user6/Android/Sdk
JAVA_HOME=/usr/lib/jvm/java-8-oracle
[12:37:44]  lint finished in 76.80 s
Subproject Path: CordovaLib
Downloading https://services.gradle.org/distributions/gradle-3.3-all.zip
.
<followed by a series of dots>
</code>```

答:
I think you installed gradle is in different location than the one which the cordova is looking for when u run using cordova run android.

As far as I know you need not install gradle explicitly when you use cordova.

Reference here - Android Builds Now Using Gradle By Default.

Check the Android SDK path libraries and JAVA_HOME path. As of now I am not sure where the general path will be. It should be installed along with Android SDK.

Else, uninstall your preinstalled gradle. Let cordova download the gradle parts once. Next time it should not download when u run it.

Check this Configuring Gradle documentation. It might help you.

Body:
I am trying to run my ionic 2 app on my android phone. I have installed the android sdk and gradle. But when i run cordova run android, it starts downloading the 3.3 version of gradle while my gradle version is 3.5. Also, the download got stuck somewhere for 20 minutes so i stopped it .
Why is this happening?

gradle -v` returns

------------------------------------------------------------
Gradle 3.5
------------------------------------------------------------

Build time:   2017-04-10 13:37:25 UTC
Revision:     b762622a185d59ce0cfc9cbc6ab5dd22469e18a6

Groovy:       2.4.10
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_121 (Oracle Corporation 25.121-b13)
OS:           Linux 3.16.0-77-generic amd64

cordova run android =>

`ANDROID_HOME=/home/user6/Android/Sdk
JAVA_HOME=/usr/lib/jvm/java-8-oracle
[12:37:44]  lint finished in 76.80 s
Subproject Path: CordovaLib
Downloading https://services.gradle.org/distributions/gradle-3.3-all.zip
.
<followed by a series of dots>


问:
Show and Hide element from Script and/or from Razor Model View with MVC
I have an element in a Razor View:

```<code><div class="label">When? *</div>
</code>```

That I need to show in a View based on a ModeView condition:

```<code><div id="label" class="label" style="@(Model.SearchedServiceId == 14 ? "display:block" : "")">When? *</div>
</code>```

But I need to be able to hide it from jQuery:

```<code>$("#label").fadeOut();
</code>```

And I define the style like:

```<code>.label {
    display: none;
}
</code>```

The problem is that when the condition is true in the element, and the display:block is added to the element, I am unable to hide it from jQuery:

```<code>$("#label").fadeOut();
</code>```

is not hiding the element.

答:
By using style

```<code>style="@(Model.SearchedServiceId == 14 ? "display:block" : "")"
</code>```

you override all classes since inline style is more powerful than css classes ids etc.
Instead of applying following code to style echo it in class as follows

```<code>class="@(Model.SearchedServiceId == 14 ? "superClass" : "")"
</code>```

then in your css file define what super class is

```<code>.superClass{
  display:block;
}
</code>```

by this way you wont need to override with important thus you can use fadeOut without problem.

If displaying it as block still causes problem you can use .removeClass('superClass'); before you fade out

Body:
I have an element in a Razor View:

When? *

That I need to show in a View based on a ModeView condition:

When? *

But I need to be able to hide it from jQuery:

$("#label").fadeOut();

And I define the style like:

.label {
    display: none;
}

The problem is that when the condition is true in the element, and the display:block is added to the element, I am unable to hide it from jQuery:

$("#label").fadeOut();

is not hiding the element.

Body:
By using style

style="@(Model.SearchedServiceId == 14 ? "display:block" : "")"

you override all classes since inline style is more powerful than css classes ids etc.
Instead of applying following code to style echo it in class as follows

class="@(Model.SearchedServiceId == 14 ? "superClass" : "")"

then in your css file define what super class is

.superClass{
  display:block;
}

by this way you wont need to override with important thus you can use fadeOut without problem.

If displaying it as block still causes problem you can use .removeClass('superClass'); before you fade out