问:
FFTW wrong backward transform on 2D image [with Qt]
I created an application in Qt, which allow me to open image and use 2D FFT transform with FFTW library. The problem is that I can not retrieve proper pixel values with backward transformation. But let's start from begining.

This is how looks my FFTW function which I use

```<code>void FFTInterface::FFTW(int rows, int cols, QColor **imageInput,fftw_complex * in, fftw_complex * out)
{
    fftw_plan g;

    g = fftw_plan_dft_2d(rows, cols, in, out, FFTW_FORWARD, FFTW_MEASURE);

    int k = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            in[k][0] = imageInput[i][j].red();
            in[k][1] = 0.0;
            k++;
         }
     }
     fftw_execute(g);
     fftw_destroy_plan(g);
}
</code>```

rows, cols are size of an image, imageInput is the array of QColor, which keep the pixels value (in greyscale), in and out are object of fftw_complex, input and output arrays.

This function give me some result, which has to be show. To do this, I made some kind of scalling. Firstly, I use abs() function on every value, to be sure that it has positive value. After that, I scale the result.

```<code>void FFTInterface::Abs(fftw_complex *out, int rows, int cols)
{
    int k = 0;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j<cols; j++){
            out[k][0] = abs(out[k][0]);
            out[k][1] = abs(out[k][1]);
            k++;
        }
    }
}
void FFTInterface::Scale(fftw_complex * in,int rows, int cols)
{
    float c = 255.0 / log(1+Max(in,rows,cols));

    int k = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            in[k][0] = c*log(1+in[k][0]);
            in[k][1] = c*log(1+in[k][0]);
            k++;
        }
    }
}
</code>```

This process give me something that I need. Image looks ok. But I have problem to revert image to it's original.
Function for BACKWARD is like below

```<code>void FFTInterface::IFFTW(int rows, int cols, fftw_complex * in, fftw_complex * out)
{
    fftw_plan g;
    g = fftw_plan_dft_2d(rows, cols, in, out, FFTW_BACKWARD, FFTW_MEASURE);

    int k = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            in[k][1] = 0.0;
            k++;
         }
    }

    fftw_execute(g);
    fftw_destroy_plan(g);
}
</code>```

I found somewhere that it's not normalized (the results are VERY BIG). To normalize I just divide values by N (256,512 etc.) - width or height of the image (it's always a square), but the values are different then the original ones.

Do you have any idea where I'm missing something? Scalling? I should maybe use other fft method from library? I have stucked.

答:
By taking the absolute value and scaling the complex components for the purpose of displaying the image you are modifying the data in such a way that the inverse transform no longer gives you the original input. To avoid this problem I would suggest you create a copy of the data you wish to display before you scale it. Also, make sure not to forget that the input to the inverse transform should be the output from the forward transform (or the last output in a signal processing chain as may be).

In pseudo-code you could do this like so:

```<code>interface.FFTW(rows, cols, imageInput, in, out);

size_t N = rows*cols;
fftw_complex* todisplay = fftw_malloc(N);
std::copy(out, out+N, todisplay);
interface.Abs(todisplay);
interface.Scale(todisplay);
... display "todisplay" on your Qt user interface
fftw_free(todislay);

interface.IFFTW(rows, cols, out, reconstructed);
</code>```

Body:
I created an application in Qt, which allow me to open image and use 2D FFT transform with FFTW library. The problem is that I can not retrieve proper pixel values with backward transformation. But let's start from begining.

This is how looks my FFTW function which I use

void FFTInterface::FFTW(int rows, int cols, QColor **imageInput,fftw_complex * in, fftw_complex * out)
{
    fftw_plan g;

    g = fftw_plan_dft_2d(rows, cols, in, out, FFTW_FORWARD, FFTW_MEASURE);

    int k = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            in[k][0] = imageInput[i][j].red();
            in[k][1] = 0.0;
            k++;
         }
     }
     fftw_execute(g);
     fftw_destroy_plan(g);
}

rows, cols are size of an image, imageInput is the array of QColor, which keep the pixels value (in greyscale), in and out are object of fftw_complex, input and output arrays.

This function give me some result, which has to be show. To do this, I made some kind of scalling. Firstly, I use abs() function on every value, to be sure that it has positive value. After that, I scale the result.

void FFTInterface::Abs(fftw_complex *out, int rows, int cols)
{
    int k = 0;
    for(int i = 0; i < rows; i++){
        for(int j = 0; j<cols; j++){
            out[k][0] = abs(out[k][0]);
            out[k][1] = abs(out[k][1]);
            k++;
        }
    }
}
void FFTInterface::Scale(fftw_complex * in,int rows, int cols)
{
    float c = 255.0 / log(1+Max(in,rows,cols));

    int k = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            in[k][0] = c*log(1+in[k][0]);
            in[k][1] = c*log(1+in[k][0]);
            k++;
        }
    }
}

This process give me something that I need. Image looks ok. But I have problem to revert image to it's original.
Function for BACKWARD is like below

void FFTInterface::IFFTW(int rows, int cols, fftw_complex * in, fftw_complex * out)
{
    fftw_plan g;
    g = fftw_plan_dft_2d(rows, cols, in, out, FFTW_BACKWARD, FFTW_MEASURE);

    int k = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            in[k][1] = 0.0;
            k++;
         }
    }

    fftw_execute(g);
    fftw_destroy_plan(g);
}

I found somewhere that it's not normalized (the results are VERY BIG). To normalize I just divide values by N (256,512 etc.) - width or height of the image (it's always a square), but the values are different then the original ones.

Do you have any idea where I'm missing something? Scalling? I should maybe use other fft method from library? I have stucked.

Body:
By taking the absolute value and scaling the complex components for the purpose of displaying the image you are modifying the data in such a way that the inverse transform no longer gives you the original input. To avoid this problem I would suggest you create a copy of the data you wish to display before you scale it. Also, make sure not to forget that the input to the inverse transform should be the output from the forward transform (or the last output in a signal processing chain as may be).

In pseudo-code you could do this like so:

interface.FFTW(rows, cols, imageInput, in, out);

size_t N = rows*cols;
fftw_complex* todisplay = fftw_malloc(N);
std::copy(out, out+N, todisplay);
interface.Abs(todisplay);
interface.Scale(todisplay);
... display "todisplay" on your Qt user interface
fftw_free(todislay);

interface.IFFTW(rows, cols, out, reconstructed);


来源: stackexchange

问:
Relocate Qt5 installation on Linux
Does anyone know, how to relocate the QT5 installation on Linux? Especially, all the set paths of the files in the mkspecs directory?
Any tool or script letting Qt5 create these files again is o.k.

I'd like to deploy the files of QT5's "lib/bin/mkspecs..." via a central repository on other computers to be able to seemingless do the compilation.

And no, I really don't want to use the systems QT5 by some package manager.

Thanks for your help!

答:
I have attempted this a few times. It gets really hairy really fast, and my only recommendation is that you re-install to the new location.

The reason is that the path of the installation is hard-coded into so many files in so many locations that even search-replacing them all is really error prone.

ContentLicense: CC BY-SA 3.0

Title: Relocate Qt5 installation on Linux


问:
Updating an HTML list using Js
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

```<code><ul>
     <li>apple</li>
     <li>ball</li>
</ul>
</code>```

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

```<code>document.getElementById('currentword').innerHTML = word;
</code>```

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!

答:
Well to the exact solution of my question, I figured out the rest from mootools docs :)

This fiddle demonstrated most of it.. http://jsfiddle.net/WngSS/1/

As for the scroll bar goes, well to customize ur own scrollbar you just use css effects.

ContentLicense: CC BY-SA 2.5

Title: Updating an HTML list using Js

Body:
So I have a js game like scrabble. Now when the user makes a new word, I would like the word to be added to a list that is displayed in a div on my page.
The issue is I quite don't understand, how I could keep my old word created and insert a new word with new formatting and everything in a list form.

I know there is a list tag --

apple

ball

but what I can't really figure out is how do I use java script to enter the word as a new list entry.

I have used js to display the word created by the following syntax

document.getElementById('currentword').innerHTML = word;

where word is the variable that holds the current word created and currentword is the div id. but how do I use this kind of syntax for a list?
Please help!

Thanks

EDIT: I would also like the last entry to the list as the first item on my list. Seems like the list populates itself but the latest entry gets hidden and the list doesn't really auto scroll down as the items are added.
PS: Also incase someone knows how I could replace the tacky scroll bar option generated by CSS to a custom scroll bar. It would be great if you could point me in the correct direction!


问:
Player-turn based Dice game (having trouble with loops)
Background; I'm trying to create a dice game for multi-players where you can choose how many players, sides on the die and dice's themselves you want in the game. And players each take a turn rolling n amount of dices and per each roll the score gets appended to the player classes playerScore property. Once a player reaches X amount of points, player is declared a winner.

Problem; The below code is part of the "Game" class. When I compile the code, the game does what I expect for the most part; it rolls 5 dices each turn per player and appends the points to said player, but once the player reaches 100 points, the player is declared a winner, but the die's are rolled again for another player, despite the fact that the while loop is invalidated. The way i see it, the problem is with the for loop, but I have no idea how to fix this, i tried "break" but it only breaks from the if statement.

My program has 3 classes; Die, Player, Game. If you need more information or screen shots. I can provide them.

P.S. If you think this code could be improved, please comment, I'd be glad to hear it out.

答:
The if statements are messing with your flow. Why?

```<code>if (gameEnded || playerArray[i].PlayerScore >= maxPoints)
{
   Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
   gameEnded = true;
   break;
}
else if (!gameEnded )
{
    playerArray[i].PlayerScore += rollAllDice();
    Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);
}
</code>```

Here, you're checking if the current player has reached the final score. If so, you break you for loop and set gameEnded = true, breaking the while loop as well. But this checks the score of the current player; it doesn't check if the current player has reached the score. This way, you will only discover if Player A won the game on the next round, not the current.

This way, as soon as a player reaches the score, the game ends:

```<code>public void StartGame(int maxPoints)
{
    playerArray[0].PlayerTurn = true; // Not sure why you're doing this, so I'm gonna leave this here

    Player winner = null;

    while (!gameEnded)
    {
        for (int i = 0; i < playerArray.Length; i++)
        {
            Player currentPlayer = playerArray[i];

            currentPlayer.PlayerScore += rollAllDice();
            Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);

            if (currentPlayer.PlayerScore >= maxPoints)
            {
                winner = currentPlayer;
                gameEnded = true;
                break;
            }
        }
    }

    Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", winner.PlayerName, winner.PlayerScore);
}
</code>```

There is only one "problem" within this code: as soon as a player reaches the number of points, it ends the game. It doesn't wait for the round to end..

Body:
The if statements are messing with your flow. Why?

if (gameEnded || playerArray[i].PlayerScore >= maxPoints)
{
   Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.",playerArray[i].PlayerName, playerArray[i].PlayerScore);
   gameEnded = true;
   break;
}
else if (!gameEnded )
{
    playerArray[i].PlayerScore += rollAllDice();
    Console.WriteLine("'{0}': {1}", playerArray[i].PlayerName, playerArray[i].PlayerScore);
}

Here, you're checking if the current player has reached the final score. If so, you break you for loop and set gameEnded = true, breaking the while loop as well. But this checks the score of the current player; it doesn't check if the current player has reached the score. This way, you will only discover if Player A won the game on the next round, not the current.

This way, as soon as a player reaches the score, the game ends:

public void StartGame(int maxPoints)
{
    playerArray[0].PlayerTurn = true; // Not sure why you're doing this, so I'm gonna leave this here

    Player winner = null;

    while (!gameEnded)
    {
        for (int i = 0; i < playerArray.Length; i++)
        {
            Player currentPlayer = playerArray[i];

            currentPlayer.PlayerScore += rollAllDice();
            Console.WriteLine("'{0}': {1}", currentPlayer.PlayerName, currentPlayer.PlayerScore);

            if (currentPlayer.PlayerScore >= maxPoints)
            {
                winner = currentPlayer;
                gameEnded = true;
                break;
            }
        }
    }

    Console.WriteLine("Congratulations, Player '{0}' has won by reaching {1} points.", winner.PlayerName, winner.PlayerScore);
}

There is only one "problem" within this code: as soon as a player reaches the number of points, it ends the game. It doesn't wait for the round to end..


问:
pgadmin4 query tool always shows message not connected
Q: How can I diagnose and correct problems with the Query tool connection.

Using pgAdmin4 1.0-rc1 to connect to a local host "PostgreSQL 9.5.3, compiled by Visual C++ build 18..."

In the browser pane I can connect and drill down to my schema. I use the context menu to select 'Query tool'. The editor shows the correct database@host:port in the editor header bar.

When I execute this sample query
  select 1 as first;

I get the message tab showing
"Not connected to the server or the connection to the server has been closed.

instead of a simple grid showing
  first
      1

Same message shows for any query, and the time it takes to come back with the message seems to be too long, especially since I'm using a localhost.

The same query works fine in phpPgAdmin.

答:
Please upgrade to latest version pgAdmin4(1.3), This issue has been resolved now.

https://www.pgadmin.org/download/


问:
Error: Cannot find an overload for 'Init' that supplied arguments
I am unable to fix this issue, I'm using Xcode6.    </p>

```<code>var numbersOnscreen:Double = 0;
        @IBOutlet var displabel: UILabel!

        @IBAction func numbers(sender: UIButton) {
            displabel.text = displabel.text + String(sender.tag-1)
            numbersOnscreen = Double(displabel.text)  //error line
        }
</code>```

答:
Try this:

```<code>numbersOnscreen = Double(displabel.text!)!
</code>```

The init method you were calling expects a String (not an optional string):

```<code>struct Double {
    init?(_ text: String) { ... }
}
</code>```

And keep in mind this is a failable initializer so another unwrapping (i.e., the last !) is needed as well.

Body:
I am unable to fix this issue, I'm using Xcode6.

var numbersOnscreen:Double = 0;
        @IBOutlet var displabel: UILabel!

        @IBAction func numbers(sender: UIButton) {
            displabel.text = displabel.text + String(sender.tag-1)
            numbersOnscreen = Double(displabel.text)  //error line
        }

Body:
Try this:

numbersOnscreen = Double(displabel.text!)!

The init method you were calling expects a String (not an optional string):

struct Double {
    init?(_ text: String) { ... }
}

And keep in mind this is a failable initializer so another unwrapping (i.e., the last !) is needed as well.


问:
Cannot resolve symbol @ReadOnly and @Mutable in Kotlin 1.1.0 compilation
I got errors "Cannot resolve symbol ReadOnly" and "Cannot resolve symbole Mutable" in compiling with Kotlin 1.1.0. Is @ReadOnly and @Mutable not available with Kotlin 1.1.0? The following is a sample code.

SampleList.java Kotlin 1.0.7

```<code>import org.jetbrains.annotations.Mutable;
import org.jetbrains.annotations.ReadOnly;

import java.util.ArrayList;
import java.util.List;

public class SampleList {
    @ReadOnly // Can resolve symbol 'ReadOnly'
    public static List<Integer> getReadOnlyList() {
        return new ArrayList<>();
    }

    @Mutable // Can resolve symbol 'Mutable'
    public static List<Integer> getMutableList() {
        return new ArrayList<>();
    }
}
</code>```

SampleList.java Kotlin 1.1.0

```<code>import org.jetbrains.annotations.Mutable;
import org.jetbrains.annotations.ReadOnly;

import java.util.ArrayList;
import java.util.List;

public class SampleList {
    @ReadOnly // Cannot resolve symbol 'ReadOnly'
    public static List<Integer> getReadOnlyList() {
        return new ArrayList<>();
    }

    @Mutable // Cannot resolve symbol 'Mutable'
    public static List<Integer> getMutableList() {
        return new ArrayList<>();
    }
}
</code>```

Thanks in advance.

答:
I'm sorry. Adding kotlin-compiler enabled @Mutable and @ReadOnly. The settings of build.gradle are as follows.

```<code>// build.gradle
dependencies {
    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-compiler:$kotlin_version" // Added
    ...
}
</code>```

Body:
I got errors "Cannot resolve symbol ReadOnly" and "Cannot resolve symbole Mutable" in compiling with Kotlin 1.1.0. Is @ReadOnly and @Mutable not available with Kotlin 1.1.0? The following is a sample code.

SampleList.java Kotlin 1.0.7

import org.jetbrains.annotations.Mutable;
import org.jetbrains.annotations.ReadOnly;

import java.util.ArrayList;
import java.util.List;

public class SampleList {
    @ReadOnly // Can resolve symbol 'ReadOnly'
    public static List<Integer> getReadOnlyList() {
        return new ArrayList<>();
    }

    @Mutable // Can resolve symbol 'Mutable'
    public static List<Integer> getMutableList() {
        return new ArrayList<>();
    }
}

SampleList.java Kotlin 1.1.0

import org.jetbrains.annotations.Mutable;
import org.jetbrains.annotations.ReadOnly;

import java.util.ArrayList;
import java.util.List;

public class SampleList {
    @ReadOnly // Cannot resolve symbol 'ReadOnly'
    public static List<Integer> getReadOnlyList() {
        return new ArrayList<>();
    }

    @Mutable // Cannot resolve symbol 'Mutable'
    public static List<Integer> getMutableList() {
        return new ArrayList<>();
    }
}

Thanks in advance.

Body:
I'm sorry. Adding kotlin-compiler enabled @Mutable and @ReadOnly. The settings of build.gradle are as follows.

// build.gradle
dependencies {
    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-compiler:$kotlin_version" // Added
    ...
}


问:
Error using insertBefore & appendChild while creating element
Trying to append a button to both the top and bottom of the body tag, however it's only performing whichever one of the two is last. Am I missing something obvious here?</p>

```<code>var msg_node = document.createElement("a");
msg_node.setAttribute("onclick", "collapseAll()");
msg_node.setAttribute("href", "javascript:void(0)");
msg_node.setAttribute("class", "kc_button");
var msg_textnode = document.createTextNode('COLLAPSE ALL');
msg_node.appendChild(msg_textnode);
document.getElementsByTagName('body')[0].appendChild(msg_node);  // supposed to make button
document.body.insertBefore(msg_node, document.body.children[0]); // makes only this button
</code>```

答:
Clone the node before appending it the second time:</p>

```<code>var msg_node = document.createElement("a");
msg_node.setAttribute("onclick", "collapseAll()");
msg_node.setAttribute("href", "javascript:void(0)");
msg_node.setAttribute("class", "kc_button");
var msg_textnode = document.createTextNode('COLLAPSE ALL');
msg_node.appendChild(msg_textnode);
document.getElementsByTagName('body')[0].appendChild(msg_node);  // supposed to make button
document.body.insertBefore(msg_node.cloneNode(true), document.body.children[0]); // makes only this button
</code>```

Body:
Trying to append a button to both the top and bottom of the body tag, however it's only performing whichever one of the two is last. Am I missing something obvious here?

var msg_node = document.createElement("a");
msg_node.setAttribute("onclick", "collapseAll()");
msg_node.setAttribute("href", "javascript:void(0)");
msg_node.setAttribute("class", "kc_button");
var msg_textnode = document.createTextNode('COLLAPSE ALL');
msg_node.appendChild(msg_textnode);
document.getElementsByTagName('body')[0].appendChild(msg_node);  // supposed to make button
document.body.insertBefore(msg_node, document.body.children[0]); // makes only this button

Body:
Clone the node before appending it the second time:

var msg_node = document.createElement("a");
msg_node.setAttribute("onclick", "collapseAll()");
msg_node.setAttribute("href", "javascript:void(0)");
msg_node.setAttribute("class", "kc_button");
var msg_textnode = document.createTextNode('COLLAPSE ALL');
msg_node.appendChild(msg_textnode);
document.getElementsByTagName('body')[0].appendChild(msg_node);  // supposed to make button
document.body.insertBefore(msg_node.cloneNode(true), document.body.children[0]); // makes only this button


问:
Check which form is used
I created to do list, through a database,

But the sign in and sign up need to go through 1 manager... yet I dont know how to check which form is used. Hope someone can help me put the 2 pieces of PHP toghter in one manager! Thanks for all help in advance!

EDIT THIS IS HOW IT WORKS!

THE MANAGER FILE

```<code><?php
    if ($_GET['action'] == 'login')  {
    $email = $_POST['email'];
    $wachtwoord = $_POST['pass'];
    $code       = sha1($wachtwoord);
    $pass       = crypt($code, 'ex');

    $sql = "SELECT * FROM tbl_users WHERE password = '$pass' AND email = '$email'";
    $result = $db_conn->query($sql)->rowCount();

    if ($result == 1)
    {
        session_start();
        $_SESSION['LoggedIn'] = true;
        header("Location: ../public/todo.php");
    }
    else{
        $ErrorMessage = "<strong>U heeft foutieve gegevens gebruikt, probeer het nog eens!</strong>";
        header("Location: ../public/index.php?message=$ErrorMessage");
    }
} else if($_GET['action'] == 'register')  {

    $ErrorMessage = "<strong>U moet een naam invullen!</strong>";
    if (empty($_POST['name'])){header("Location: ../public/signup.php?message=$ErrorMessage");die;}
    $ErrorMessage = "<strong>U moet een wachtwoord invullen!</strong>";
    if (empty($_POST['pass'])){header("Location: ../public/signup.php?message=$ErrorMessage");die;}
    $ErrorMessage = "<strong>U moet een geldige email invullen!</strong>";
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){header("Location: ../public/signup.php?message=$ErrorMessage");die;}

    $email  = $_POST['email'];

    $qry="SELECT `email` FROM `tbl_users` ORDER BY `email`";
    $qryObj = $db_conn->prepare($qry);
    $qryObj->execute();

    $resultArr = $qryObj->fetchAll(PDO::FETCH_ASSOC);

    foreach($resultArr as $row)
    {
        if ($email === $row['email']) {
            $ErrorMessage = "<strong>Deze mail bestaat al!</strong>";
            header("Location: ../public/signup.php?message=$ErrorMessage");die;
        }
    }

    $name   = htmlspecialchars($_POST['name']);
    $wachtwoord = $_POST['pass'];
    $code = sha1($wachtwoord);
    $pass = crypt($code,'ex');

    $verificatie='name='.$name.'&email='.$email.'&pass='.$pass;

    $subject = 'Verifeer uw email adres';
    $from = 'De TODO Servicedesk';
    $bericht = '/verificatie.php?'.$verificatie;

    ini_set('sendmail_from', $from);

    $headers   = array();
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-type: text/plain; charset=iso-8859-1";
    $headers[] = "From: TODO Servicedesk <{$from}>";
    $headers[] = "Reply-To: TODO Servicedesk <{$from}>";
    //$headers[] = "Subject: {$subject}";

    mail($email, $subject, $bericht, implode("\r\n", $headers) );
    $ErrorMessage = "<strong>Er is een activatiemail verstuurd!</strong>";
    header("Location: ../public/signup.php?message=$ErrorMessage");
}
</code>```

?>

This are the FORMS

login form:

```<code><section>
<form action="../app/account_manager.php?action=login" method="POST">
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" class="form-control" name="email">
    </div>
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" class="form-control" name="pass">
    </div>
    <div class="form-group">
        <input type="submit" value="Login!" class="btn btn-primary" name="login">
    </div>
</form>
<?php
if (isset($_GET['message'])!= null )
{
    echo $_GET['message'];
}
?>
</code>```

Register Form:

```<code><section>
<form action="../app/account_manager.php?action=register" method="POST">
    <div class="form-group">
        <label for="name">Name:</label>
        <input type="text" class="form-control" name="name">
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" class="form-control" name="email">
    </div>
    <div class="form-group">
        <label for="pass">Password:</label>
        <input type="password" class="form-control" name="pass">
    </div>
    <div class="form-group">
        <input type="submit" value="Registreer!" class="btn btn-primary" name="submit">
    </div>
</form>
<?php
if (isset($_GET['message'])!= null )
{
    echo $_GET['message'];
}
?>
</code>```

答:
You can use hidden input in each forms. the first and second forms would have a unique name for examle: form_name="first" so </p>

```<code>if ($_POST['form_name'] == 'first'){

}else{

}
</code>```

Title: Check which form is used

Body:
I created to do list, through a database,

But the sign in and sign up need to go through 1 manager... yet I dont know how to check which form is used. Hope someone can help me put the 2 pieces of PHP toghter in one manager! Thanks for all help in advance!

EDIT THIS IS HOW IT WORKS!

THE MANAGER FILE

<?php
    if ($_GET['action'] == 'login')  {
    $email = $_POST['email'];
    $wachtwoord = $_POST['pass'];
    $code       = sha1($wachtwoord);
    $pass       = crypt($code, 'ex');

    $sql = "SELECT * FROM tbl_users WHERE password = '$pass' AND email = '$email'";
    $result = $db_conn->query($sql)->rowCount();

    if ($result == 1)
    {
        session_start();
        $_SESSION['LoggedIn'] = true;
        header("Location: ../public/todo.php");
    }
    else{
        $ErrorMessage = "U heeft foutieve gegevens gebruikt, probeer het nog eens!";
        header("Location: ../public/index.php?message=$ErrorMessage");
    }
} else if($_GET['action'] == 'register')  {

    $ErrorMessage = "U moet een naam invullen!";
    if (empty($_POST['name'])){header("Location: ../public/signup.php?message=$ErrorMessage");die;}
    $ErrorMessage = "U moet een wachtwoord invullen!";
    if (empty($_POST['pass'])){header("Location: ../public/signup.php?message=$ErrorMessage");die;}
    $ErrorMessage = "U moet een geldige email invullen!";
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){header("Location: ../public/signup.php?message=$ErrorMessage");die;}

    $email  = $_POST['email'];

    $qry="SELECT `email` FROM `tbl_users` ORDER BY `email`";
    $qryObj = $db_conn->prepare($qry);
    $qryObj->execute();

    $resultArr = $qryObj->fetchAll(PDO::FETCH_ASSOC);

    foreach($resultArr as $row)
    {
        if ($email === $row['email']) {
            $ErrorMessage = "Deze mail bestaat al!";
            header("Location: ../public/signup.php?message=$ErrorMessage");die;
        }
    }

    $name   = htmlspecialchars($_POST['name']);
    $wachtwoord = $_POST['pass'];
    $code = sha1($wachtwoord);
    $pass = crypt($code,'ex');

    $verificatie='name='.$name.'&email='.$email.'&pass='.$pass;

    $subject = 'Verifeer uw email adres';
    $from = 'De TODO Servicedesk';
    $bericht = '/verificatie.php?'.$verificatie;

    ini_set('sendmail_from', $from);

    $headers   = array();
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-type: text/plain; charset=iso-8859-1";
    $headers[] = "From: TODO Servicedesk <{$from}>";
    $headers[] = "Reply-To: TODO Servicedesk <{$from}>";
    //$headers[] = "Subject: {$subject}";

    mail($email, $subject, $bericht, implode("\r\n", $headers) );
    $ErrorMessage = "Er is een activatiemail verstuurd!";
    header("Location: ../public/signup.php?message=$ErrorMessage");
}

?>

This are the FORMS

login form:

<form action="../app/account_manager.php?action=login" method="POST">

        Email:
        <input type="email" class="form-control" name="email">

        Password:
        <input type="password" class="form-control" name="pass">

        <input type="submit" value="Login!" class="btn btn-primary" name="login">

</form>
<?php
if (isset($_GET['message'])!= null )
{
    echo $_GET['message'];
}
?>

Register Form:

<form action="../app/account_manager.php?action=register" method="POST">

        Name:
        <input type="text" class="form-control" name="name">

        Email:
        <input type="email" class="form-control" name="email">

        Password:
        <input type="password" class="form-control" name="pass">

        <input type="submit" value="Registreer!" class="btn btn-primary" name="submit">

</form>
<?php
if (isset($_GET['message'])!= null )
{
    echo $_GET['message'];
}
?>

Body:
You can use hidden input in each forms. the first and second forms would have a unique name for examle: form_name="first" so

if ($_POST['form_name'] == 'first'){

}else{

}


问:
Remove an item from a Set that doesn't match criteria
For a school project, the goal is to do a fuzzy match of a query string to a lyric string inside a Song object.  The overall data structure is a TreeMap of unique words paired with sets of songs that contain that word in the lyrics.

I have my preliminary match set of songs that contain the query string.  The twist here is that I have to assign each result song a rank based on the number of characters in the match section, spaces inclusive.  For example, searching for "she loves you" returns these among the matches:

"... She loves you ..."  The Beatles, rank= 13

"... She just loves you ..."  Bonnie Raitt, rank=18

"... She loves me, well you ..."  Elvis Presley, rank=23

The I'm using to sort the results is:

```<code>for (int i=0; i<lyrics.length; i++) {
  if (lyrics[i].equals(query[0])) { //got the start point
  start=i; //adjust the start index point

  //loop through lyrics from start point
  for (int j=1; j<query.length; j++) {
    if (lyrics[j].equals(query[query.length-1])) {
        end=i; //found the last word
    }

    //if next lyric word doesn't match this query word
    if (!lyrics[i+j].equals(query[j])) {

    //advance loop through lyrics. when a match is found, i is adjusted to
    //the match index
    for (int k= i+j+1; k<lyrics.length; k++) {
        if (lyrics[k].equals(query[j]) || lyrics[k].equals(query[0]))
            i=k++;
        } //end inner advance loop

    } //end query string test

  }//end query test loop

  song.setRanks(start, end); //start and end points for the rank algorithm.

} //end start point test
</code>```

Since all the songs in the result set contain the query words in any particular order, they will not all be included in the result printout.  Using this algorithm, how can I set a trigger to remove the song from the set if the query is not matched to any particular length?

Edit- Is Lucene a solution to this?  This is a gray area in the project, and one I will bring up in class tomorrow.  He is allowing us to choose whatever data structures for this project, but I don't know if using another implementation for string matching will pass muster.

Edit 2 @ belisarius- I don't see how edit distance applies here.  The most common application of Levenshtein distance requres a String a of length n and String b of length m, and the distance is the number of edits required for a==b.  For this project, all that is required is the rank of characters in a match, with the start and end points unknown.  With some changes to the code posted above, I am finding the start and end points accurately.  What I need is a way to remove the non-matches from the set if the the lyrics don't fit the search in any fashion.

答:
A Patricia trie might just do it for you.

Go through this one see if it has what u need.

http://code.google.com/p/patricia-trie/

Body:
For a school project, the goal is to do a fuzzy match of a query string to a lyric string inside a Song object.  The overall data structure is a TreeMap of unique words paired with sets of songs that contain that word in the lyrics.

I have my preliminary match set of songs that contain the query string.  The twist here is that I have to assign each result song a rank based on the number of characters in the match section, spaces inclusive.  For example, searching for "she loves you" returns these among the matches:

"... She loves you ..."  The Beatles, rank= 13

"... She just loves you ..."  Bonnie Raitt, rank=18

"... She loves me, well you ..."  Elvis Presley, rank=23

The I'm using to sort the results is:

for (int i=0; i<lyrics.length; i++) {
  if (lyrics[i].equals(query[0])) { //got the start point
  start=i; //adjust the start index point

  //loop through lyrics from start point
  for (int j=1; j<query.length; j++) {
    if (lyrics[j].equals(query[query.length-1])) {
        end=i; //found the last word
    }

    //if next lyric word doesn't match this query word
    if (!lyrics[i+j].equals(query[j])) {

    //advance loop through lyrics. when a match is found, i is adjusted to
    //the match index
    for (int k= i+j+1; k<lyrics.length; k++) {
        if (lyrics[k].equals(query[j]) || lyrics[k].equals(query[0]))
            i=k++;
        } //end inner advance loop

    } //end query string test

  }//end query test loop

  song.setRanks(start, end); //start and end points for the rank algorithm.

} //end start point test

Since all the songs in the result set contain the query words in any particular order, they will not all be included in the result printout.  Using this algorithm, how can I set a trigger to remove the song from the set if the query is not matched to any particular length?

Edit- Is Lucene a solution to this?  This is a gray area in the project, and one I will bring up in class tomorrow.  He is allowing us to choose whatever data structures for this project, but I don't know if using another implementation for string matching will pass muster.

Edit 2 @ belisarius- I don't see how edit distance applies here.  The most common application of Levenshtein distance requres a String a of length n and String b of length m, and the distance is the number of edits required for a==b.  For this project, all that is required is the rank of characters in a match, with the start and end points unknown.  With some changes to the code posted above, I am finding the start and end points accurately.  What I need is a way to remove the non-matches from the set if the the lyrics don't fit the search in any fashion.


问:
Keeping the script running when closing the window and opening a text editor in Python
As we all know April fools is coming so i tought i would write a nice script to prank someone, a harmless version of the well known and feared MEMZ Virus.

The Script i have currently:

```<code>import webbrowser
import time

def program():
    time.sleep(13)
    url = "https://www.google.nl/#q=TROLOL+GO+TO+LAUGH+IDIOT&*"
    webbrowser.open(url,new=new)
    time.sleep(16)
    url = "https://www.google.nl/webhp?sourceid=chrome-instant&rlz=1CAACAG_enNL654NL655&ion=1&espv=2&ie=UTF-8#q=CS:GO+Hacks+No+Download&*"
    webbrowser.open(url, new=new)
    time.sleep(18)
    url = "https://www.youtube.com/watch?v=7S94ohyErSw"
    webbrowser.open(url, new=new)
    time.sleep(23)

def main():
    pass

if __name__ == "__main__":
    main()
</code>```

What i want is to be able to open a text editor with text just like in the real virus.
A windows error box would be fine to. Also i dont want the prompt. so a way to close the prompt without ending the script would be nice.

Anyone got some ideas?

Thank you in advance.

Natan.

EDIT: My victim's Computer has Windows.

EDIT2:
I have updated the script:

```<code>import webbrowser
import ctypes
import time

MB_OK = 0x0
MB_OKCXL = 0x01
MB_YESNOCXL = 0x03
MB_YESNO = 0x04
MB_HELP = 0x4000
ICON_EXLAIM = 0x30
ICON_INFO = 0x40
ICON_STOP = 0x10
ICON_QUES = 0x20

def program():
    ctypes.windll.user32.MessageBoxW(0, "Your computer is fucked by the MEMZ Trojan, good luck trying to keep using it.", "GET REKT, DABBBB", MB_OK | ICON_INFO)
    time.sleep(2)
    ctypes.windll.user32.MessageBoxW(0, "BTW if you shut down your computer you wont be able to start it back up.", "Almost forgot....", MB_OK | ICON_INFO)
    time.sleep(13)
    url = "https://www.google.nl/#q=TROLOL+GO+TO+LAUGH+IDIOT&*"
    webbrowser.open(url,new=new)
    time.sleep(16)
    url = "https://www.google.nl/webhp?sourceid=chrome-instant&rlz=1CAACAG_enNL654NL655&ion=1&espv=2&ie=UTF-8#q=CS:GO+Hacks+No+Download&*"
    webbrowser.open(url, new=new)
    time.sleep(18)
    url = "https://www.youtube.com/watch?v=7S94ohyErSw"
    webbrowser.open(url, new=new)
    time.sleep(23)
    ctypes.windll.user32.MessageBoxW(0, "Still using this computer?", "Hell is that way", MB_OK | ICON_QUES)
    time.sleep(17)
    url = "https://www.gottabemobile.com/black-ops-3-cheats-hacks-things-to-know/"
    webbrowser.open(url, new=new)
    time.sleep(12)
    url = "https://thepiratebay.org/"
    webbrowser.open(url, new=new)
    time.sleep(32)
    url = "http://stackoverflow.com/questions/43114927/keeping-the-script-running-when-closing-the-window-and-opening-a-text-editor-in"
    webbrowser.open(url, new=new)
    ctypes.windll.user32.MessageBoxW(0, "Trololol. Fijne 1 april nog Justus! Groetjes Natan!", "April fools", MB_OK | ICON_INFO)

def main():
    program()

if __name__ == "__main__":
    main()
</code>```

答:
The solution provided by @Abhishake gupta is good, you can also os module to open a notepad with some text.</p>

```<code>import os
f = open('foo.txt','w')
f.write('Hello world!')
f.close()
os.system("notepad.exe foo.txt")
</code>```

Body:
As we all know April fools is coming so i tought i would write a nice script to prank someone, a harmless version of the well known and feared MEMZ Virus.

The Script i have currently:

import webbrowser
import time

def program():
    time.sleep(13)
    url = "https://www.google.nl/#q=TROLOL+GO+TO+LAUGH+IDIOT&*"
    webbrowser.open(url,new=new)
    time.sleep(16)
    url = "https://www.google.nl/webhp?sourceid=chrome-instant&rlz=1CAACAG_enNL654NL655&ion=1&espv=2&ie=UTF-8#q=CS:GO+Hacks+No+Download&*"
    webbrowser.open(url, new=new)
    time.sleep(18)
    url = "https://www.youtube.com/watch?v=7S94ohyErSw"
    webbrowser.open(url, new=new)
    time.sleep(23)

def main():
    pass

if __name__ == "__main__":
    main()

What i want is to be able to open a text editor with text just like in the real virus.
A windows error box would be fine to. Also i dont want the prompt. so a way to close the prompt without ending the script would be nice.

Anyone got some ideas?

Thank you in advance.

Natan.

EDIT: My victim's Computer has Windows.

EDIT2:
I have updated the script:

import webbrowser
import ctypes
import time

MB_OK = 0x0
MB_OKCXL = 0x01
MB_YESNOCXL = 0x03
MB_YESNO = 0x04
MB_HELP = 0x4000
ICON_EXLAIM = 0x30
ICON_INFO = 0x40
ICON_STOP = 0x10
ICON_QUES = 0x20

def program():
    ctypes.windll.user32.MessageBoxW(0, "Your computer is fucked by the MEMZ Trojan, good luck trying to keep using it.", "GET REKT, DABBBB", MB_OK | ICON_INFO)
    time.sleep(2)
    ctypes.windll.user32.MessageBoxW(0, "BTW if you shut down your computer you wont be able to start it back up.", "Almost forgot....", MB_OK | ICON_INFO)
    time.sleep(13)
    url = "https://www.google.nl/#q=TROLOL+GO+TO+LAUGH+IDIOT&*"
    webbrowser.open(url,new=new)
    time.sleep(16)
    url = "https://www.google.nl/webhp?sourceid=chrome-instant&rlz=1CAACAG_enNL654NL655&ion=1&espv=2&ie=UTF-8#q=CS:GO+Hacks+No+Download&*"
    webbrowser.open(url, new=new)
    time.sleep(18)
    url = "https://www.youtube.com/watch?v=7S94ohyErSw"
    webbrowser.open(url, new=new)
    time.sleep(23)
    ctypes.windll.user32.MessageBoxW(0, "Still using this computer?", "Hell is that way", MB_OK | ICON_QUES)
    time.sleep(17)
    url = "https://www.gottabemobile.com/black-ops-3-cheats-hacks-things-to-know/"
    webbrowser.open(url, new=new)
    time.sleep(12)
    url = "https://thepiratebay.org/"
    webbrowser.open(url, new=new)
    time.sleep(32)
    url = "http://stackoverflow.com/questions/43114927/keeping-the-script-running-when-closing-the-window-and-opening-a-text-editor-in"
    webbrowser.open(url, new=new)
    ctypes.windll.user32.MessageBoxW(0, "Trololol. Fijne 1 april nog Justus! Groetjes Natan!", "April fools", MB_OK | ICON_INFO)

def main():
    program()

if __name__ == "__main__":
    main()

Body:
The solution provided by @Abhishake gupta is good, you can also os module to open a notepad with some text.

import os
f = open('foo.txt','w')
f.write('Hello world!')
f.close()
os.system("notepad.exe foo.txt")


问:
How can I return value instead of console.log
Thanks to @redsquare's answer on question Javascript/jQuery - How do I obtain name of the class of clicked element? I am using the following JS to log innerText of the CSS class and a parent element.

The code has the desired outcome in console however I need to return the value instead of using console.log(). What would be the best way to do this?

I need to pass this value into a tag management system.

My attempts to include a return statement into the existing code have not worked.

window.onclick = function(e) {
  var classList = e.target.className.split(/\s+/);
  for (i = 0; i < classList.length; i++) {
    if (classList[i] === 'myClass') {
      console.log(e.target.innerText + " - " + e.target.parentNode.parentElement.children[1].innerText);
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <span class="myClass">Click here</span> and more text</code>```

答:
Change console.log() to a function you write, here processTagContent()

function processTagContent(str) {
  alert(str);
  // here you can ajax stuff to server
}
window.onclick = function(e) {
  var classList = e.target.className.split(/\s+/);
  for (i = 0; i < classList.length; i++) {
    if (classList[i] === 'myClass') {
      processTagContent(e.target.innerText + " - " + e.target.parentNode.parentElement.children[1].innerText);
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <span class="myClass">Click here</span> and more text</code>```

Body:
Thanks to @redsquare's answer on question Javascript/jQuery - How do I obtain name of the class of clicked element? I am using the following JS to log innerText of the CSS class and a parent element.

The code has the desired outcome in console however I need to return the value instead of using console.log(). What would be the best way to do this?

I need to pass this value into a tag management system.

My attempts to include a return statement into the existing code have not worked.

window.onclick = function(e) {
  var classList = e.target.className.split(/\s+/);
  for (i = 0; i < classList.length; i++) {
    if (classList[i] === 'myClass') {
      console.log(e.target.innerText + " - " + e.target.parentNode.parentElement.children[1].innerText);
    }
  }
}

    Click here and more text

Body:
Change console.log() to a function you write, here processTagContent()

function processTagContent(str) {
  alert(str);
  // here you can ajax stuff to server
}
window.onclick = function(e) {
  var classList = e.target.className.split(/\s+/);
  for (i = 0; i < classList.length; i++) {
    if (classList[i] === 'myClass') {
      processTagContent(e.target.innerText + " - " + e.target.parentNode.parentElement.children[1].innerText);
    }
  }
}

    <span class="myClass">Click here</span> and more text


问:
Can not copy row data to a dataframe in pandas while iterating a dataframe row wise
I am trying to create a new dataframe into which data is to be filled from another dataframe's column.

```<code>import pandas as pd

df = {'account_number' : [1,2,3,4,5,6],
 'id_value' : [101,101,201,201,301,301]}
df = pd.DataFrame(df)
out = pd.DataFrame(columns=['node1','node2','relation'])

for index,row in df.iterrows():
    if (index % 2 == 0):
        out['node1'] = row['account_number']
    else:
        out['node2'] = row['account_number']
        out['relation'] = 'SELF'

out
</code>```

I am trying to achieve :

```<code>node1    node2    relation
  1        2       SELF
  3        4       SELF
  5        6       SELF
</code>```

I don't seem to understand the flaw in my code. When I print the values row[account_number] they get printed correct but when I copy them to my result dataframe they don't get copied.

I am pretty much new to python, pandas and even stack overflow, please excuse me for bad code or anything I have violated.

答:
You are assigning values to an empty data frame's column, which according to broadcasting, will do nothing, because it is empty initially.

```<code>out = pd.DataFrame(columns=['node1','node2','relation'])
out['node1'] = 1
out
# node1 node2   relation
</code>```

You can provide a row index to avoid this:

```<code>for index,row in df.iterrows():
    if (index % 2 == 0):
        out.loc[index//2, 'node1'] = row['account_number']
    else:
        out.loc[index//2, 'node2'] = row['account_number']
        out.loc[index//2, 'relation'] = 'SELF'

out
#node1  node2   relation
#0   1      2       SELF
#1   3      4       SELF
#2   5      6       SELF
</code>```

Body:
I am trying to create a new dataframe into which data is to be filled from another dataframe's column.

import pandas as pd

df = {'account_number' : [1,2,3,4,5,6],
 'id_value' : [101,101,201,201,301,301]}
df = pd.DataFrame(df)
out = pd.DataFrame(columns=['node1','node2','relation'])

for index,row in df.iterrows():
    if (index % 2 == 0):
        out['node1'] = row['account_number']
    else:
        out['node2'] = row['account_number']
        out['relation'] = 'SELF'

out

I am trying to achieve :

node1    node2    relation
  1        2       SELF
  3        4       SELF
  5        6       SELF

I don't seem to understand the flaw in my code. When I print the values row[account_number] they get printed correct but when I copy them to my result dataframe they don't get copied.

I am pretty much new to python, pandas and even stack overflow, please excuse me for bad code or anything I have violated.

Body:
You are assigning values to an empty data frame's column, which according to broadcasting, will do nothing, because it is empty initially.

out = pd.DataFrame(columns=['node1','node2','relation'])
out['node1'] = 1
out
# node1 node2   relation

You can provide a row index to avoid this:

for index,row in df.iterrows():
    if (index % 2 == 0):
        out.loc[index//2, 'node1'] = row['account_number']
    else:
        out.loc[index//2, 'node2'] = row['account_number']
        out.loc[index//2, 'relation'] = 'SELF'

out
#node1  node2   relation
#0   1      2       SELF
#1   3      4       SELF
#2   5      6       SELF


问:
To find a particular string from multiples text files in the same directory
I am finding a string, for example "error", from a multiple text files. The multiple text files are within a similar directory. After finding, it must be able to print that line containing the string.

So far, I have only been successful on searching and printing out the string from one text file.

In the below code, I tried to create a list of the filenames in the directory; the list is called logz, but it printed out nothing. It only worked when the logz in line 10 is listed as a TXT file.

The desired output should be something like this:

Line 0: asdasda error wefrewfawvewvaw

Line 3: awvawvawvaw error afvavavav

Line 6: e ERROR DSCVSVWASEFVEWVWEVW

Here is my code:

```<code>import re
import sys
import os

logz = [fn for fn in os.listdir(r'my text file directory') if fn.endswith('.txt')]

err_occur = [] # The list where we will store results.
pattern = re.compile(" error ", re.IGNORECASE)

try: # Try to:
    with open ('logz', 'rt') as in_file: # open file for reading text.
        for linenum, line in enumerate(in_file):
            if pattern.search(line) != None:
                err_occur.append((linenum, line.rstrip('/n')))
                print("Line ", linenum, ": ", line, sep='')
</code>```

答:
You can use the following program as an example for writing yours. Replace the '.' in line 5 with the path to your text file directory. Line 9 can be modified as needed to search for words other than 'error' as well. You will need to be running Python 3.6 if you want to use f'' strings (line 10).

```<code>import pathlib

def main():
    for path in pathlib.Path('.').iterdir():
        if path.suffix.lower() == '.txt':
            with path.open() as file:
                for line, text in enumerate(file):
                    if 'error' in text.lower():
                        print(f'Line {line}: {text}')

if __name__ == '__main__':
    main()
</code>```

Body:
I am finding a string, for example "error", from a multiple text files. The multiple text files are within a similar directory. After finding, it must be able to print that line containing the string.

So far, I have only been successful on searching and printing out the string from one text file.

In the below code, I tried to create a list of the filenames in the directory; the list is called logz, but it printed out nothing. It only worked when the logz in line 10 is listed as a TXT file.

The desired output should be something like this:

Line 0: asdasda error wefrewfawvewvaw

Line 3: awvawvawvaw error afvavavav

Line 6: e ERROR DSCVSVWASEFVEWVWEVW

Here is my code:

import re
import sys
import os

logz = [fn for fn in os.listdir(r'my text file directory') if fn.endswith('.txt')]

err_occur = [] # The list where we will store results.
pattern = re.compile(" error ", re.IGNORECASE)

try: # Try to:
    with open ('logz', 'rt') as in_file: # open file for reading text.
        for linenum, line in enumerate(in_file):
            if pattern.search(line) != None:
                err_occur.append((linenum, line.rstrip('/n')))
                print("Line ", linenum, ": ", line, sep='')

Body:
You can use the following program as an example for writing yours. Replace the '.' in line 5 with the path to your text file directory. Line 9 can be modified as needed to search for words other than 'error' as well. You will need to be running Python 3.6 if you want to use f'' strings (line 10).

import pathlib

def main():
    for path in pathlib.Path('.').iterdir():
        if path.suffix.lower() == '.txt':
            with path.open() as file:
                for line, text in enumerate(file):
                    if 'error' in text.lower():
                        print(f'Line {line}: {text}')

if __name__ == '__main__':
    main()


问:
PHP array_search for multi dimensional array and return key
I'm trying to search for a value in a multi dimensional array (below is only a part of the big array) and get the key for that value but I can't manage it by myself. Here is what I have tried :

```<code>Array
(
    [0] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => -
            [4] => -
            [5] => ALES
            [6] => 44-
            [7] => -
            [8] => FR*S30*E36*1*1
            [9] => FR*S30*E36*1*1
            [10] => US*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )

    [1] => Array  // <-- wanted key
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => Chemin Des Sports
            [4] => -
            [5] => ALES
            [6] => -
            [7] => -
            [8] => FR*S30*E37*2*1  // <-- wanted value
            [9] => FR*S30*E37*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 33762
            [13] => Normale
            [14] => -
        )

    [2] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => 0
            [3] => Ecole Des Mines
            [4] => -
            [5] => ALES
            [6] => 4-
            [7] => -
            [8] => FR*S30*E38*2*1
            [9] => FR*S30*E38*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )
)

$key = array_search("FR*S30*E37*2*1", array_column($data, '8'));
var_dump($data[$key]);
</code>```

With this code I can't get the key of desired array. What am I doing wrong ?

答:
If you don't need to key, you could use array_filter

```<code>$result = array_filter($data, function($item) use ($search) {
    return $item[8] == $search;
})[0];
</code>```

If you need the key, you could modify it like this

```<code>$key = false;
$result = array_filter($data, function($item, $k) use ($search, &$key) {
    if ($item[8] == $search) {
        $key = $k;
        return true;
    }
    return false;
}, ARRAY_FILTER_USE_BOTH)[0];
</code>```

To handle cases, where no result is found, you have to skip the [0] party and test if count($result) != 0

Body:
I'm trying to search for a value in a multi dimensional array (below is only a part of the big array) and get the key for that value but I can't manage it by myself. Here is what I have tried :

Array
(
    [0] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => -
            [4] => -
            [5] => ALES
            [6] => 44-
            [7] => -
            [8] => FR*S30*E36*1*1
            [9] => FR*S30*E36*1*1
            [10] => US*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )

    [1] => Array  // <-- wanted key
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => Chemin Des Sports
            [4] => -
            [5] => ALES
            [6] => -
            [7] => -
            [8] => FR*S30*E37*2*1  // <-- wanted value
            [9] => FR*S30*E37*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 33762
            [13] => Normale
            [14] => -
        )

    [2] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => 0
            [3] => Ecole Des Mines
            [4] => -
            [5] => ALES
            [6] => 4-
            [7] => -
            [8] => FR*S30*E38*2*1
            [9] => FR*S30*E38*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )
)

$key = array_search("FR*S30*E37*2*1", array_column($data, '8'));
var_dump($data[$key]);

With this code I can't get the key of desired array. What am I doing wrong ?

Body:
If you don't need to key, you could use array_filter

$result = array_filter($data, function($item) use ($search) {
    return $item[8] == $search;
})[0];

If you need the key, you could modify it like this

$key = false;
$result = array_filter($data, function($item, $k) use ($search, &$key) {
    if ($item[8] == $search) {
        $key = $k;
        return true;
    }
    return false;
}, ARRAY_FILTER_USE_BOTH)[0];

To handle cases, where no result is found, you have to skip the [0] party and test if count($result) != 0


问:
LINQ to SQL for self-referencing tables?
I have a self referencing Categories table. Each Category has a CategoryID, ParentCategoryID, CategoryName, etc. And each category can have any number of sub categories, and each of those sub categories can have any number of sub categories, and so and and so forth. So basically the tree can be X levels deep.

Then Products are associated to leaf (sub) Categories. Is there a way to get all the Products for any given Category (which would be all the products associated to all its leaf descendants) using LINQ to SQL?

This feels like a recursive problem. Is it better to used a Stored Procedure instead?

答:
Well here is a terrible rushed implementation using LINQ.
Don't use this :-)</p>

```<code>public IQueryable GetCategories(Category parent)
{
    var cats = (parent.Categories);
    foreach (Category c in cats )
    {
        cats  = cats .Concat(GetCategories(c));
    }
    return a;
}
</code>```

OwnerDisplayName: Ricky

Body:
Well here is a terrible rushed implementation using LINQ.
Don't use this :-)

public IQueryable GetCategories(Category parent)
{
    var cats = (parent.Categories);
    foreach (Category c in cats )
    {
        cats  = cats .Concat(GetCategories(c));
    }
    return a;
}

OwnerDisplayName: Graphain


问:
How to capture an event trigger when a flash movie successfully loaded?
I'm currently using jQuery, as well as swfObject to dynamically embed the swf movie into my web page.

I currently having a problem on embeding immem's music player into my web page, as their embed code doesn't have any loading screen. So, when I replace the element using swfObject, that area will generally blank. In worst case, it means that user won't know that the embed song is loading.

So, I'm trying to find out the way to bind an event after that flash got loaded. Since my plan would be placing image with huge z-index on the top and use this trigger to hide the image. I think I've tried to use $('#embed').load(function(){ ... });, with no luck.

Does somebody have any solution for this? I just wonder if that is possible, since I don't want to get hacking with the flash and try to add 'loader' to the flash file.

Some more note: To make it more clear, I want to embed imeem's music player into my webpage. So, I really don't have any control over the flash file, i.e. I can't create a flash file by myself.

答:
Typically the easiest thing to do is plain ol' <body onload="..." which would wait for your external resources to finish loading before calling your handler.

However, if you're using swfObject to add an embedded plugin dynamically the browser will fire the onload for the body exclusive of your flash movie (it doesn't know anything about your plugin).

See http://blog.deconcept.com/swfobject/forum/discussion/271/javascript-onload-event-does-not-reflect-page-load-using-swfobject/ for a similar discussion to yours. It's my best guess that you cannot do what you want without modifying the original swf in some fashion.

OwnerDisplayName: Sikachu

LastEditorDisplayName: Sikachu


问:
slow textarea in internet explorer after big table list
I'm working on an ecommerce website for my work that gives me articles that can be ordered. Below my list of articles I have a textarea where you can give comments, when my list of articles is long the typing in this textarea is very slow.

When I have small lists everything goes fine, but with large lists ie hangs. No other webbrowser has this issue.

Can somebody help me with this?

答: There could be javascript code which listens events on textarea and do something with it (keydown, keyup, keypress). If it's so than this code related to each article and how many articles you have that much events are set up.</p>


问:
How to connect to VMware Linux guest over wireless network?
Setup:
Windows 7 host
Vmware workstation running Oracle Linux guest

I have a static IP assigned to my guest OS (Can be accessed only from office-LAN or with VPN). Using the bridged network , everything works fine. What setup needs to be done when i have to access this VM over wireless network (When my host is connected to wireless internet connection at home) ?

The static IP over wireless can only be accessed once i am connected to VPN.

答: Go to bridged networking, choose 'Bridged to' adapter to your wireless adapter. Usually Bridged to' adapter will be ethernet adapter.


问:
PHP regex for admin, admin/ and admin/more/ etc
I'm currently building a CMS for my projects and I'm trying to route to my 'Admin' controller. Now my regexp is:

```<code>'admin(.*)'
</code>```

But with this everything that start with 'admin' will be matched. I would like to match the route when 'admin', 'admin/foo' and 'admin/foo/bar' etc, is present. Not when 'adminn' or something like that.

Hope you understand what I'm after. Thx / Tobias

答:
Alter the regex like this:</p>

```<code>admin(\/.*)?
</code>```

Body:
I'm currently building a CMS for my projects and I'm trying to route to my 'Admin' controller. Now my regexp is:

'admin(.*)'

But with this everything that start with 'admin' will be matched. I would like to match the route when 'admin', 'admin/foo' and 'admin/foo/bar' etc, is present. Not when 'adminn' or something like that.

Hope you understand what I'm after. Thx / Tobias

Body:
Alter the regex like this:

admin(\/.*)?


问:
How do I use Session_Start in ASP.NET MVC?
It's quite weird, I thought that simply adding this code in the Global.asax.cs would be enough:

```<code>void Session_Start(object sender, EventArgs e) {
  // your code here, it will be executed upon session start
}
</code>```

But the method isn't called... How do I let ASP.NET call a the Session_Start method when the session starts?

I can't figure how to catch the event of a session creation.

答:
Yes, that is enough ... when you have enabled sessions:</p>

```<code><system.web>
  <sessionState cookieName="auth" mode="InProc" timeout="480"/>
</system.web>
</code>```

Body:
It's quite weird, I thought that simply adding this code in the Global.asax.cs would be enough:

void Session_Start(object sender, EventArgs e) {
  // your code here, it will be executed upon session start
}

But the method isn't called... How do I let ASP.NET call a the Session_Start method when the session starts?

I can't figure how to catch the event of a session creation.

Body:
Yes, that is enough ... when you have enabled sessions:

<system.web>
  <sessionState cookieName="auth" mode="InProc" timeout="480"/>
</system.web>


问:
Symfony : is it a bad practice to use a service to return entity?
In my project, I have :

Company Entity : created with Doctrine

CompanyController : list actions that can be realized for the company

CompanyManager Service : used to process some Company Entity data.

For example, Company Entity has a getOpeningDays() function, and CompanyManager Service has a getRealOpeningDays() function that filter out holidays :

```<code><?php
namespace AppBundle\Services\Company;

class CompanyManager
{

    private $em;
    private $companyBase;

    public function __construct(
        \Doctrine\ORM\EntityManager $em,
        \AppBundle\Services\Work\PublicHolidays $publicHolidays
    ) {
        $this->em               = $em;
        $this->publicHolidays   = $publicHolidays;
    }

    public function setCompanyId($companyId)
    {
        $this->companyBase = $this->em->getRepository('AppBundle:CompanyBase')->findOneBy(
            array('id' => $companyId)
        );
    }

    public function getRealOpeningDays()
    {
        // ...
        foreach($publicHolidays as $publicHolidayKey => $publicHolidayData)
        {
            if(in_array($publicHolidayKey, $this->companyBase->getWorkedPublicHolidaysIds()) == false)
            {
                // ...
            }
        }
        return $publicHolidaysNonWorkedDates;
    }
}
</code>```

In my CompanyController, I have sometimes form that require to use Company Entity.

I am now wondering if it is a bad practice to return this Company Entity from CompanyManager Service, in a similar function :

```<code><?php
namespace AppBundle\Services\Company;

class CompanyManager
{

    //...

    public function getEntity()
    {
        return $this->companyBase;
    }
}
</code>```

It would allow me to change this :

```<code>public function companySocialAction(Request $request)
{
    $session = $request->getSession();
    $companyBase = $this->getDoctrine()->getRepository('AppBundle:CompanyBase')->findOneBy(array('id' => $session->get('companyId')));

    $companyManager = $this->get('CompanyManager');
    $companyManager->setId($companyBase->getId());

    $form = $this->createForm(CompanySocialType::class, $companyBase);
    $form->handleRequest($request);

    // ...
}
</code>```

In this :

```<code>public function companySocialAction(Request $request)
{
    $session = $request->getSession();

    $companyManager = $this->get('CompanyManager');
    $companyManager->setId($session->get('companyId'));

    $form = $this->createForm(CompanySocialType::class, $companyManager->getEntity());
    $form->handleRequest($request);

    // ...
}
</code>```

Thank you.

答:
This is more of a code review question and thus highly opinion based. But I hope, this is helpful. However, I would split it into to parts:

CompanyManager

Is your CompanyManager a manager in the sense of an EntityManager like the one you're injecting (\Doctrine\ORM\EntityManager)? So all methods like find|findAll|persist|flush etc. are wrapped? Or is it more like a Factory or in terms of Symfony a Provider? If so, you could name it to CompanyProvider and it should only do what the name suggests.

Symfony already uses a provider for the User entity. The scheme can be adopted for other entities as well: Create a User Provider:

```<code>class CompanyProvider {
    public function loadCompanyById($id) {
        // […]

        if ($company) {
            return $company;
        }

        throw new CompanyNotFoundException(
            sprintf('Company with id "%s" does not exist.', $id)
        );
    }

    public function refreshCompany(\Company $company)
    {
        // […]
        return $this->loadCompanyById($company->getId());
    }
}
</code>```

getRealOpeningDays()

I don't think that this method should be part of the class that provides Company entities. It looks more like a utility or service, which could be available for other entities or values as well. Also this function is ambiguous - at least by looking at the simplified example. It is called getRealOpeningDays but it returns something called publicHolidaysNonWorkedDates. If I got you right, you could create a filter like this:

```<code>namespace AppBundle\Services;

class HolidayService {

    private $publicHolidays;

    public function __construct(\AppBundle\Services\Work\PublicHolidays $publicHolidays) {
        $this-> publicHolidays = $publicHolidays;
    }

    public function getPublicHolidays() {
        return $this->publicHolidays;
    }

    public function filterByPublicHolidays($datesOpen, $datesOpenOnHolidays = null) {
        // reduce $dateOpen by $this->publicHolidays
        // if $datesOpenOnHolidays is given, don't remove holidays that the company or any other entity is actually open
        return $collection;
    }
}
</code>```

Minor adjustments

Don't call a method setCompanyId when it never actually sets the company id, but loads a whole object instead.

In the first version of companySocialAction you load the entity twice, which is unnecessary. You could simply pass the object around. (I assume that setId means setCompanyId.)

Body:
In my project, I have :

Company Entity : created with Doctrine

CompanyController : list actions that can be realized for the company

CompanyManager Service : used to process some Company Entity data.

For example, Company Entity has a getOpeningDays() function, and CompanyManager Service has a getRealOpeningDays() function that filter out holidays :

<?php
namespace AppBundle\Services\Company;

class CompanyManager
{

    private $em;
    private $companyBase;

    public function __construct(
        \Doctrine\ORM\EntityManager $em,
        \AppBundle\Services\Work\PublicHolidays $publicHolidays
    ) {
        $this->em               = $em;
        $this->publicHolidays   = $publicHolidays;
    }

    public function setCompanyId($companyId)
    {
        $this->companyBase = $this->em->getRepository('AppBundle:CompanyBase')->findOneBy(
            array('id' => $companyId)
        );
    }

    public function getRealOpeningDays()
    {
        // ...
        foreach($publicHolidays as $publicHolidayKey => $publicHolidayData)
        {
            if(in_array($publicHolidayKey, $this->companyBase->getWorkedPublicHolidaysIds()) == false)
            {
                // ...
            }
        }
        return $publicHolidaysNonWorkedDates;
    }
}

In my CompanyController, I have sometimes form that require to use Company Entity.

I am now wondering if it is a bad practice to return this Company Entity from CompanyManager Service, in a similar function :

<?php
namespace AppBundle\Services\Company;

class CompanyManager
{

    //...

    public function getEntity()
    {
        return $this->companyBase;
    }
}

It would allow me to change this :

public function companySocialAction(Request $request)
{
    $session = $request->getSession();
    $companyBase = $this->getDoctrine()->getRepository('AppBundle:CompanyBase')->findOneBy(array('id' => $session->get('companyId')));

    $companyManager = $this->get('CompanyManager');
    $companyManager->setId($companyBase->getId());

    $form = $this->createForm(CompanySocialType::class, $companyBase);
    $form->handleRequest($request);

    // ...
}

In this :

public function companySocialAction(Request $request)
{
    $session = $request->getSession();

    $companyManager = $this->get('CompanyManager');
    $companyManager->setId($session->get('companyId'));

    $form = $this->createForm(CompanySocialType::class, $companyManager->getEntity());
    $form->handleRequest($request);

    // ...
}

Thank you.

Body:
This is more of a code review question and thus highly opinion based. But I hope, this is helpful. However, I would split it into to parts:

CompanyManager

Is your CompanyManager a manager in the sense of an EntityManager like the one you're injecting (\Doctrine\ORM\EntityManager)? So all methods like find|findAll|persist|flush etc. are wrapped? Or is it more like a Factory or in terms of Symfony a Provider? If so, you could name it to CompanyProvider and it should only do what the name suggests.

Symfony already uses a provider for the User entity. The scheme can be adopted for other entities as well: Create a User Provider:

class CompanyProvider {
    public function loadCompanyById($id) {
        // […]

        if ($company) {
            return $company;
        }

        throw new CompanyNotFoundException(
            sprintf('Company with id "%s" does not exist.', $id)
        );
    }

    public function refreshCompany(\Company $company)
    {
        // […]
        return $this->loadCompanyById($company->getId());
    }
}

getRealOpeningDays()

I don't think that this method should be part of the class that provides Company entities. It looks more like a utility or service, which could be available for other entities or values as well. Also this function is ambiguous - at least by looking at the simplified example. It is called getRealOpeningDays but it returns something called publicHolidaysNonWorkedDates. If I got you right, you could create a filter like this:

namespace AppBundle\Services;

class HolidayService {

    private $publicHolidays;

    public function __construct(\AppBundle\Services\Work\PublicHolidays $publicHolidays) {
        $this-> publicHolidays = $publicHolidays;
    }

    public function getPublicHolidays() {
        return $this->publicHolidays;
    }

    public function filterByPublicHolidays($datesOpen, $datesOpenOnHolidays = null) {
        // reduce $dateOpen by $this->publicHolidays
        // if $datesOpenOnHolidays is given, don't remove holidays that the company or any other entity is actually open
        return $collection;
    }
}

Minor adjustments

Don't call a method setCompanyId when it never actually sets the company id, but loads a whole object instead.

In the first version of companySocialAction you load the entity twice, which is unnecessary. You could simply pass the object around. (I assume that setId means setCompanyId.)


问:
Uploading products data from excel file - Amazon MWS
Can someone provide me with the example code for uploading the excel file to amazon MWS ?

Or maybe explain the process, how do I send the excel file to amazon ? Amazon says they support flat file format but they don't provide any example about using it.

Thanks.

答:
To use MWS to send products, you'll use the Feeds API.  Choose a FeedType from the list of product and inventory feeds and click the XSD or text file templates links to learn about the format.  Once you have the feed formatted, you'll call the SubmitFeed operation to upload the feed.  Have a look at the flowchart to understand the process.

If you download one of the client libraries in your language of choice, they have all the code you'll need written already, just plug in your account information and have your feed ready to send.


问:
Including file inside a class php
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.

This is my class

```<code>class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}
</code>```

This is my config.php file

```<code>return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);
</code>```

How do i do it?

```<code>PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)
</code>```

答:
Include this:

```<code> $dbconn = include("config.php");
</code>```

in your construct function.

Title: Including file inside a class php

Body:
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.

This is my class

class User {

    $dbconn = include("config.php");
    private $dbHost     = $dbconn->host;
    private $dbUsername = $dbconn->username;
    private $dbPassword = $dbconn->pass;
    private $dbName     = $dbconn->database;
    private $userTbl    = 'users';

    function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
}

This is my config.php file

return (object) array(
    'host' => 'localhost',
    'username' => 'my_user',
    'pass' => 'my_pass',
    'database' => 'my_db'
);

How do i do it?

PHP Parse error:  syntax error, unexpected '$dbconn' (T_VARIABLE)

Body:
Include this:

 $dbconn = include("config.php");

in your construct function.


答: For string, such as admin/foo/bar/salami/pizza, how about preg_match('~^admin\/~', $string)?

Title: PHP regex for admin, admin/ and admin/more/ etc


问:
Alternative for a linked list in CUDA
I have a problem with my CUDA code. I search for values in an 1D array. When I found for example the value 255 in an RGB image i want to store the index of this value without gaps.

I know how to do it with standard c++ (like a linked list) but i have no clue how to do this in parallel with cuda c.

Thank you in advance!

答:
One possible approach, using atomics:

```<code>const int MAX_SIZE = MAX_SIZE_OF_IMAGE;
const int nTPB = 256;
__device__ int base = 0;
__device__ int dev_indices[MAX_SIZE];
template <typename T>
__global__ void findvalindex(const T* __restrict__ imagedata, const T val, const int imagelen){
  int idx=threadIdx.x+blockDim.x*blockIdx.x;
  if (idx < imagelen)
    if (imagedata[idx] == val){
      int mylocation = atomicAdd(&base, 1);
      dev_indices[mylocation] = idx;}
  }
</code>```

in host code:

```<code>// assume image data is already copied to the device using device pointer image
findvalindex<<<(MAX_SIZE+nTPB-1)/nTPB, nTPB>>>(image, 255, MAX_SIZE);
int num_indices;
cudaMemcpyFromSymbol(&num_indices, base, sizeof(int));
int *indices = new int[num_indices];
cudaMemcpyFromSymbol(indices, dev_indices, sizeof(int)*num_indices));
// indices now contains the list of matching indices
</code>```

(coded in browser)

The basic idea here is that we are using atomics to guarantee that every thread that finds a match will get a unique insertion point in the index array.  There will be no gaps using this method.

Title: Alternative for a linked list in CUDA

Body:
One possible approach, using atomics:

const int MAX_SIZE = MAX_SIZE_OF_IMAGE;
const int nTPB = 256;
__device__ int base = 0;
__device__ int dev_indices[MAX_SIZE];
template <typename T>
__global__ void findvalindex(const T* __restrict__ imagedata, const T val, const int imagelen){
  int idx=threadIdx.x+blockDim.x*blockIdx.x;
  if (idx < imagelen)
    if (imagedata[idx] == val){
      int mylocation = atomicAdd(&base, 1);
      dev_indices[mylocation] = idx;}
  }

in host code:

// assume image data is already copied to the device using device pointer image
findvalindex<<<(MAX_SIZE+nTPB-1)/nTPB, nTPB>>>(image, 255, MAX_SIZE);
int num_indices;
cudaMemcpyFromSymbol(&num_indices, base, sizeof(int));
int *indices = new int[num_indices];
cudaMemcpyFromSymbol(indices, dev_indices, sizeof(int)*num_indices));
// indices now contains the list of matching indices

(coded in browser)

The basic idea here is that we are using atomics to guarantee that every thread that finds a match will get a unique insertion point in the index array.  There will be no gaps using this method.


问:
surrounding a pattern in python string with brackets
I have a string looks like this:

```<code>oldString="this is my {{string-d}}" => "this is my {{(string-d)}}"
oldString2="this is my second{{ new_string-d }}" => "this is my second{{ (new_string-d) }}"
oldString2="this is my second new_string-d " => "this is my second (new_string-d) "
oldString2="this is my second new[123string]-d " => "this is my second (new[123string]-d) "
</code>```

I want to add brackets whenever I see "-d" right after it and before the word that is attached to it.

I wrote a code that looks for the pattern "-d" in strings and partition the string after finding the pattern to 3 partitions before "-d", after "-d" and "-d" itself then I check the block before "-d" until I find whitespace or "{" and stop and add brackets. my code looks like this:
P.S. I have many files that I read from them and try to modify the string there the example above is just for demonstrating what I'm trying to do.

```<code>   if ('-d') in oldString:
    p = oldString.partition('-d')
    v = p[p.index('-d')-1]
    beforeString=''
    for i in reversed(v):
        if i != ' ' or i != '{':
            beforeString=i+beforeString
            indexNew = v.index(i)
    outPutLine = v[:indexNew]+'('+v[indexNew:]
    newString = outPutLine + '-d' + ' )'
    print newString
</code>```

the result of running the code will be:

```<code>newString = "(this is my {{string-d )"
</code>```

as you can see that the starting bracket is before "this" instead of before "string" why is this happening? also, I'm not sure if this is the best way to do this kind of find and replace any suggestions would be much appreciated.

答:
```<code>>>> import re
>>> oldString = "this is my {{string-d}}"
>>> oldString2 = "this is my second{{ new_string-d }}"
>>> re.sub(r"(\w*-d)", r"(\1)", oldString)
'this is my {{(string-d)}}'
>>> re.sub(r"(\w*-d)", r"(\1)", oldString2)
'this is my second{{ (new_string-d) }}'
</code>```

Note that this matches "words" assuming that a word is composed of only letters, numbers, and underscores.

Here's a more thorough breakdown of what's happening:

An r before a string literal means the string is a "raw string". It prevents Python from interpreting characters as an escape sequence. For instance, r"\n" is a slash followed by the letter n, rather than being interpreted as a single newline character. I like to use raw strings for my regex patterns, even though it's not always necessary.

the parentheses surrounding \w*-d is a capturing group. It indicates to the regex engine that the contents of the group should be saved for later use.

the sequence \w means "any alphanumeric character or underscore".

* means "zero or more of the preceding item". \w* together means "zero or more alphanumeric characters or underscores".

-d means "a hyphen followed by the letter d.

All together, (\w*-d) means "zero or more alphanumeric characters or underscores, followed by a hyphen and the letter d. Save all of these characters for later use."

The second string describes what the matched data should be replaced with. "\1" means "the contents of the first captured group". The parentheses are just regular parentheses. All together, (\1) in this context means "take the saved content from the captured group, surround it in parentheses, and put it back into the string".

If you want to match more characters than just alphanumeric and underscore, you can replace \w with whatever collection of characters you want to match.

```<code>>>> re.sub(r"([\w\.\[\]]*-d)", r"(\1)", "{{startingHere[zero1].my_string-d }}")
'{{(startingHere[zero1].my_string-d) }}'
</code>```

If you also want to match words ending with "-d()", you can match a parentheses pair with \(\) and mark it as optional using ?.

```<code>>>> re.sub(r"([\w\.\[\]]*-d(\(\))?)", r"(\1)", "{{startingHere[zero1].my_string-d() }}")
'{{(startingHere[zero1].my_string-d()) }}'
</code>```

Body:
I have a string looks like this:

oldString="this is my {{string-d}}" => "this is my {{(string-d)}}"
oldString2="this is my second{{ new_string-d }}" => "this is my second{{ (new_string-d) }}"
oldString2="this is my second new_string-d " => "this is my second (new_string-d) "
oldString2="this is my second new[123string]-d " => "this is my second (new[123string]-d) "

I want to add brackets whenever I see "-d" right after it and before the word that is attached to it.

I wrote a code that looks for the pattern "-d" in strings and partition the string after finding the pattern to 3 partitions before "-d", after "-d" and "-d" itself then I check the block before "-d" until I find whitespace or "{" and stop and add brackets. my code looks like this:
P.S. I have many files that I read from them and try to modify the string there the example above is just for demonstrating what I'm trying to do.

   if ('-d') in oldString:
    p = oldString.partition('-d')
    v = p[p.index('-d')-1]
    beforeString=''
    for i in reversed(v):
        if i != ' ' or i != '{':
            beforeString=i+beforeString
            indexNew = v.index(i)
    outPutLine = v[:indexNew]+'('+v[indexNew:]
    newString = outPutLine + '-d' + ' )'
    print newString

the result of running the code will be:

newString = "(this is my {{string-d )"

as you can see that the starting bracket is before "this" instead of before "string" why is this happening? also, I'm not sure if this is the best way to do this kind of find and replace any suggestions would be much appreciated.

Body:
>>> import re
>>> oldString = "this is my {{string-d}}"
>>> oldString2 = "this is my second{{ new_string-d }}"
>>> re.sub(r"(\w*-d)", r"(\1)", oldString)
'this is my {{(string-d)}}'
>>> re.sub(r"(\w*-d)", r"(\1)", oldString2)
'this is my second{{ (new_string-d) }}'

Note that this matches "words" assuming that a word is composed of only letters, numbers, and underscores.

Here's a more thorough breakdown of what's happening:

An r before a string literal means the string is a "raw string". It prevents Python from interpreting characters as an escape sequence. For instance, r"\n" is a slash followed by the letter n, rather than being interpreted as a single newline character. I like to use raw strings for my regex patterns, even though it's not always necessary.

the parentheses surrounding \w*-d is a capturing group. It indicates to the regex engine that the contents of the group should be saved for later use.

the sequence \w means "any alphanumeric character or underscore".

* means "zero or more of the preceding item". \w* together means "zero or more alphanumeric characters or underscores".

-d means "a hyphen followed by the letter d.

All together, (\w*-d) means "zero or more alphanumeric characters or underscores, followed by a hyphen and the letter d. Save all of these characters for later use."

The second string describes what the matched data should be replaced with. "\1" means "the contents of the first captured group". The parentheses are just regular parentheses. All together, (\1) in this context means "take the saved content from the captured group, surround it in parentheses, and put it back into the string".

If you want to match more characters than just alphanumeric and underscore, you can replace \w with whatever collection of characters you want to match.

>>> re.sub(r"([\w\.\[\]]*-d)", r"(\1)", "{{startingHere[zero1].my_string-d }}")
'{{(startingHere[zero1].my_string-d) }}'

If you also want to match words ending with "-d()", you can match a parentheses pair with \(\) and mark it as optional using ?.

>>> re.sub(r"([\w\.\[\]]*-d(\(\))?)", r"(\1)", "{{startingHere[zero1].my_string-d() }}")
'{{(startingHere[zero1].my_string-d()) }}'


答:
You can't have executable code in a variable definition, only static values. So this sort of thing is not supported:

```<code>class foo {
    public $var = result_of_some_function();
}
</code>```

If you want to initialize a value, use the constructor. You're probably better off reading it as a config file:

```<code>class User {
    public function __construct() {
        $config = json_decode(file_get_contents('config.json'));
        $conn = new mysqli($config->host, ...);
    }
}
</code>```

Or better, using dependency injection:

```<code>class User {
    protected $db = null;
    public function __construct($db) {
        $this->db = $db;
    }
}
</code>```

Then in your code that creates a user object:

```<code>$db = new Db($config);
$user = new User($db);
</code>```

Title: Including file inside a class php

Body:
You can't have executable code in a variable definition, only static values. So this sort of thing is not supported:

class foo {
    public $var = result_of_some_function();
}

If you want to initialize a value, use the constructor. You're probably better off reading it as a config file:

class User {
    public function __construct() {
        $config = json_decode(file_get_contents('config.json'));
        $conn = new mysqli($config->host, ...);
    }
}

Or better, using dependency injection:

class User {
    protected $db = null;
    public function __construct($db) {
        $this->db = $db;
    }
}

Then in your code that creates a user object:

$db = new Db($config);
$user = new User($db);


问:
SpringBoot Rest response not deserialiazed with jackson
I am a running a project with SpringBoot. In this project I am calling an external Rest Service. I have modeled the response items into bean.
But when I get the response back the data are not serialised into the beans.
I guess there must be some configuration missing but I cannot find what.

I have added onfiguration spring-boot-starter-test to the configuration of Maven:

The rest client:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
public class RestClientTest {

    @Autowired
    private RestTemplateBuilder restTemplate;

    @Test
    public void sayHello() {
        System.out.println("Hello");
        assert(true);
    }

    @Test
    public void testGetEmployee() {
        RestTemplate template = restTemplate.build();;
        HttpHeaders headers = new HttpHeaders();

        List<MediaType> types = new ArrayList<MediaType>();
        types.add(MediaType.APPLICATION_JSON);
        types.add(MediaType.APPLICATION_XML);
        headers.setAccept(types);
        headers.set("Authorization", "Bearer gWRdGO7sUhAXHXBnjlBCtTP");
        HttpEntity<Items> entity = new HttpEntity<Items>(headers);

        String uri = "https://mytest.com/employees";

        //ResponseEntity<String> rec = template.exchange(uri, HttpMethod.GET, entity, String.class);
        //System.out.println("Received: " + rec);

        ResponseEntity<Items> rec = template.exchange(uri, HttpMethod.GET, entity, Items.class);
        System.out.println("Received: " + rec);
    }
}
</code>```

When I inspect the elements of the response it, I get a list, all the items are with null values

```<code>    @JsonFormat(shape = JsonFormat.Shape.OBJECT)
    public class Item implements Serializable {

    @JsonProperty
    private String id;
    @JsonProperty
    private String name;
    @JsonProperty
    private String email;
    @JsonProperty
    private String phone;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public class Items implements Serializable {

    @JsonProperty
    private List<Item> items = new ArrayList<Item>();

    public List<Item> getItems() {
        return items;
    }
}
</code>```

Do you see what I am missing here?

The response is like this:

```<code>{
  "items": [
    {
      "item": {
        "id": 0,
        "name": "string",
        "email": "string",
        "phone": "string",
</code>```

Do you see what I am missing here?

Thanks

Gilles

答:
You might need to add this to your ObjectMapper:

mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

And on your entity add @JsonRootName("item")

Body:
I am a running a project with SpringBoot. In this project I am calling an external Rest Service. I have modeled the response items into bean.
But when I get the response back the data are not serialised into the beans.
I guess there must be some configuration missing but I cannot find what.

I have added onfiguration spring-boot-starter-test to the configuration of Maven:

The rest client:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RestClientTest {

    @Autowired
    private RestTemplateBuilder restTemplate;

    @Test
    public void sayHello() {
        System.out.println("Hello");
        assert(true);
    }

    @Test
    public void testGetEmployee() {
        RestTemplate template = restTemplate.build();;
        HttpHeaders headers = new HttpHeaders();

        List<MediaType> types = new ArrayList<MediaType>();
        types.add(MediaType.APPLICATION_JSON);
        types.add(MediaType.APPLICATION_XML);
        headers.setAccept(types);
        headers.set("Authorization", "Bearer gWRdGO7sUhAXHXBnjlBCtTP");
        HttpEntity<Items> entity = new HttpEntity<Items>(headers);

        String uri = "https://mytest.com/employees";

        //ResponseEntity<String> rec = template.exchange(uri, HttpMethod.GET, entity, String.class);
        //System.out.println("Received: " + rec);

        ResponseEntity<Items> rec = template.exchange(uri, HttpMethod.GET, entity, Items.class);
        System.out.println("Received: " + rec);
    }
}

When I inspect the elements of the response it, I get a list, all the items are with null values

    @JsonFormat(shape = JsonFormat.Shape.OBJECT)
    public class Item implements Serializable {

    @JsonProperty
    private String id;
    @JsonProperty
    private String name;
    @JsonProperty
    private String email;
    @JsonProperty
    private String phone;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public class Items implements Serializable {

    @JsonProperty
    private List<Item> items = new ArrayList<Item>();

    public List<Item> getItems() {
        return items;
    }
}

Do you see what I am missing here?

The response is like this:

{
  "items": [
    {
      "item": {
        "id": 0,
        "name": "string",
        "email": "string",
        "phone": "string",

Do you see what I am missing here?

Thanks

Gilles