问:
Calling javascript form php
I am having a form inside a php script. I am doing the validation using javascript.

```<code><?php

$con = mysql_connect("servername","login","passsword");
if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

mysql_select_db("dbadminatms", $con);

if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['comments']))
{
    $sql="INSERT INTO feedback_comments (posted_by, email, comments_text, comment_date)
        VALUES
    ('$_POST[name]','$_POST[email]','$_POST[comments]',NOW())";
    $emailID = $_POST['email'];
    $postedBy = $_POST['name'];
    $message = $_POST['comments'];

    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    else
    {
        mail( "aaa@bbb.coml.com", "Subject: Comments", $message, "From: $emailID\r\n $postedBy" );
    }
}
    else
{

echo '

<form action="contactus.php" method="POST" id="feedback" onsubmit="javascript:return validate("feedback","name","email","comments");">

                <p id="errorMsg">All fields are required</p>

                <label for="name" class="label" id="nameLabel">Your name: </label><input id="name" type="text" size="30"  name="name" class="field"/>
                <br /><br />
                <label for="email" class="label" id="emailLabel">Your Email id: </label><input id="email" type="text" size="30"  name="email" class="field"/>
                <br /><br />

                    <label for="comments" class="label" id="commentsLabel">Comments:</label>
                  <div id="commentsSection">
                    <textarea name="comments" id="comments" class="ui-corner-all" cols="9" rows="5" tabindex="140"></textarea>
                  </div>

            <p><input type="submit" value="Submit" id="submit"/> <input type="reset" /></p>

        </form>';
}

    mysql_close($con);
?>
</code>```

Everrything's is working fine but I can't validate the form using javascript.

答:
Using jquery is better.

jQuery plugin: Validation

Title: Calling javascript form php

Body:
I am having a form inside a php script. I am doing the validation using javascript.

<?php

$con = mysql_connect("servername","login","passsword");
if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

mysql_select_db("dbadminatms", $con);

if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['comments']))
{
    $sql="INSERT INTO feedback_comments (posted_by, email, comments_text, comment_date)
        VALUES
    ('$_POST[name]','$_POST[email]','$_POST[comments]',NOW())";
    $emailID = $_POST['email'];
    $postedBy = $_POST['name'];
    $message = $_POST['comments'];

    if (!mysql_query($sql,$con))
    {
        die('Error: ' . mysql_error());
    }
    else
    {
        mail( "aaa@bbb.coml.com", "Subject: Comments", $message, "From: $emailID\r\n $postedBy" );
    }
}
    else
{

echo '

<form action="contactus.php" method="POST" id="feedback" onsubmit="javascript:return validate("feedback","name","email","comments");">

All fields are required

                Your name: <input id="name" type="text" size="30"  name="name" class="field"/>

                Your Email id: <input id="email" type="text" size="30"  name="email" class="field"/>

                    Comments:

                    <textarea name="comments" id="comments" class="ui-corner-all" cols="9" rows="5" tabindex="140"></textarea>

<input type="submit" value="Submit" id="submit"/> <input type="reset" />

        </form>';
}

    mysql_close($con);
?>

Everrything's is working fine but I can't validate the form using javascript.


来源: stackexchange

问:
Uppercase variables
im trying to set two vars uppercase, can someone help with whats wrong with this?

The var1 and the var2 will be only one letter, for example a or d.
this doesnt give any error it just put the two var´s with the same letter.

By the way im using this in a bat file

thanks

```<code>@ECHO OFF
Setlocal EnableDelayedExpansion
SET /p var1=a
SET /p var2=d
set /a "x = 1"
:while1
if %x% leq 2 (
if %x% EQU 1 (SET varvel=!var1!)
if %x% EQU 2 (SET varvel=!var2!)
    IF [%varvel%]==[] GOTO:invaliddat

        SET varvel=%varvel:a=A%
        SET varvel=%varvel:b=B%
        SET varvel=%varvel:c=C%
        SET varvel=%varvel:d=D%
        SET varvel=%varvel:e=E%
        SET varvel=%varvel:f=F%
        SET varvel=%varvel:g=G%
        SET varvel=%varvel:h=H%
        SET varvel=%varvel:i=I%
        SET varvel=%varvel:j=J%
        SET varvel=%varvel:k=K%
        SET varvel=%varvel:l=L%
        SET varvel=%varvel:m=M%
        SET varvel=%varvel:n=N%
        SET varvel=%varvel:o=O%
        SET varvel=%varvel:p=P%
        SET varvel=%varvel:q=Q%
        SET varvel=%varvel:r=R%
        SET varvel=%varvel:s=S%
        SET varvel=%varvel:t=T%
        SET varvel=%varvel:u=U%
        SET varvel=%varvel:v=V%
        SET varvel=%varvel:w=W%
        SET varvel=%varvel:x=X%
        SET varvel=%varvel:y=Y%
        SET varvel=%varvel:z=Z%

if %x% EQU 1 (set var1=!varvel!)
if %x% EQU 2 (set var2=!varvel!)
set /a "x = x + 1"
goto :while1
)
echo %var1%
echo %var2%
Pause
</code>```

答:
a bit shorter:

```<code>@echo off
setlocal enabledelayedexpansion
set "var=The quick brown fox jumps over the lazy dog."
for %%a in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do set "var=!var:%%a=%%a!"
echo %var%
</code>```

It seems strange to replace upper case letters by upper case letters, but it works.

ContentLicense: CC BY-SA 3.0

Title: Uppercase variables

Body:
im trying to set two vars uppercase, can someone help with whats wrong with this?

The var1 and the var2 will be only one letter, for example a or d.
this doesnt give any error it just put the two var´s with the same letter.

By the way im using this in a bat file

thanks

@ECHO OFF
Setlocal EnableDelayedExpansion
SET /p var1=a
SET /p var2=d
set /a "x = 1"
:while1
if %x% leq 2 (
if %x% EQU 1 (SET varvel=!var1!)
if %x% EQU 2 (SET varvel=!var2!)
    IF [%varvel%]==[] GOTO:invaliddat

        SET varvel=%varvel:a=A%
        SET varvel=%varvel:b=B%
        SET varvel=%varvel:c=C%
        SET varvel=%varvel:d=D%
        SET varvel=%varvel:e=E%
        SET varvel=%varvel:f=F%
        SET varvel=%varvel:g=G%
        SET varvel=%varvel:h=H%
        SET varvel=%varvel:i=I%
        SET varvel=%varvel:j=J%
        SET varvel=%varvel:k=K%
        SET varvel=%varvel:l=L%
        SET varvel=%varvel:m=M%
        SET varvel=%varvel:n=N%
        SET varvel=%varvel:o=O%
        SET varvel=%varvel:p=P%
        SET varvel=%varvel:q=Q%
        SET varvel=%varvel:r=R%
        SET varvel=%varvel:s=S%
        SET varvel=%varvel:t=T%
        SET varvel=%varvel:u=U%
        SET varvel=%varvel:v=V%
        SET varvel=%varvel:w=W%
        SET varvel=%varvel:x=X%
        SET varvel=%varvel:y=Y%
        SET varvel=%varvel:z=Z%

if %x% EQU 1 (set var1=!varvel!)
if %x% EQU 2 (set var2=!varvel!)
set /a "x = x + 1"
goto :while1
)
echo %var1%
echo %var2%
Pause

Body:
a bit shorter:

@echo off
setlocal enabledelayedexpansion
set "var=The quick brown fox jumps over the lazy dog."
for %%a in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do set "var=!var:%%a=%%a!"
echo %var%

It seems strange to replace upper case letters by upper case letters, but it works.


问:
fill column with previous column if NA
I have a data frame like this

```<code>df <- data.frame(v1 = 10:14, v2 = c(NA, 1, NA, 3, 6), v3 = c(1, NA, NA, 9, 4))

  v1 v2 v3
1 10 NA  1
2 11  1 NA
3 12 NA NA
4 13  3  9
5 14  6  4
</code>```

I now want to fill the NAs with the value of the previous column, so it looks like this:

```<code>  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4
</code>```

I know how to do this manually, like this:

```<code>df$v2 <- ifelse(is.na(df$v2), df$v1, df$v2)
</code>```

How can I automate this for a full data frame with many columns?

答:
Another option using Reduce with ifelse:

```<code>df[] <- Reduce(function(x, y) ifelse(is.na(y), x, y), df, accumulate = TRUE)

df
#  v1 v2 v3
#1 10 10  1
#2 11  1  1
#3 12 12 12
#4 13  3  9
#5 14  6  4
</code>```

Title: fill column with previous column if NA

Body:
I have a data frame like this

df <- data.frame(v1 = 10:14, v2 = c(NA, 1, NA, 3, 6), v3 = c(1, NA, NA, 9, 4))

  v1 v2 v3
1 10 NA  1
2 11  1 NA
3 12 NA NA
4 13  3  9
5 14  6  4

I now want to fill the NAs with the value of the previous column, so it looks like this:

  v1 v2 v3
1 10 10  1
2 11  1  1
3 12 12 12
4 13  3  9
5 14  6  4

I know how to do this manually, like this:

df$v2 <- ifelse(is.na(df$v2), df$v1, df$v2)

How can I automate this for a full data frame with many columns?

Body:
Another option using Reduce with ifelse:

df[] <- Reduce(function(x, y) ifelse(is.na(y), x, y), df, accumulate = TRUE)

df
#  v1 v2 v3
#1 10 10  1
#2 11  1  1
#3 12 12 12
#4 13  3  9
#5 14  6  4


问:
jQuery - dynamic content click event not working correctly
I am having an issue with getting a click event to work on some dynamic content.

It is a little more complicated than this but pretty much I have a select2 input which when the user types a search term will do an ajax request and add the returned data to a table.

I have some extra code which should run when the td element of this content is clicked. If there is only a small amount of ajax data returned then the click event will execute correctly and target the correct element, however, if there is a large amount of data added to the table and I have to scroll down the page and then click the td element the event will not execute, instead it will target the tbody element instead.

I am using code similar to this:

```<code>$( document ).on( 'click', function( e ) {
    var target = $( e.target );

    if( target.is( "#myId table tr td" ) ) {
        console.log("td element has been clicked!");
    }

});
</code>```

I have also tried the following:

```<code> $( document ).on( 'click', '#myId table tr td', function(e) {
    console.log( "td element has been clicked!" );
 });
</code>```

However, the results were the same as with the first section of code.

Is there any reason why scrolling and clicking a dynamically created element will target the tbody instead of the td element?

Results of console.log the target and the HTML structure:

答:
A few things:

make sure that if you do $("#myId table tr td").length it is returning the # of rows you expect

make sure this wrapped around a document.ready handler.

You could also try a more scoped example:

```<code>$( "#myId" ).on( "click", "td", function() {
  console.log( $( this ).text() );
});
</code>```

Body:
I am having an issue with getting a click event to work on some dynamic content.

It is a little more complicated than this but pretty much I have a select2 input which when the user types a search term will do an ajax request and add the returned data to a table.

I have some extra code which should run when the td element of this content is clicked. If there is only a small amount of ajax data returned then the click event will execute correctly and target the correct element, however, if there is a large amount of data added to the table and I have to scroll down the page and then click the td element the event will not execute, instead it will target the tbody element instead.

I am using code similar to this:

$( document ).on( 'click', function( e ) {
    var target = $( e.target );

    if( target.is( "#myId table tr td" ) ) {
        console.log("td element has been clicked!");
    }

});

I have also tried the following:

 $( document ).on( 'click', '#myId table tr td', function(e) {
    console.log( "td element has been clicked!" );
 });

However, the results were the same as with the first section of code.

Is there any reason why scrolling and clicking a dynamically created element will target the tbody instead of the td element?

Results of console.log the target and the HTML structure:

Body:
A few things:

make sure that if you do $("#myId table tr td").length it is returning the # of rows you expect

make sure this wrapped around a document.ready handler.

You could also try a more scoped example:

$( "#myId" ).on( "click", "td", function() {
  console.log( $( this ).text() );
});


问:
JQuery hide/show from textbox
I'm trying to get a password field to be shown/hidden depending on value that of a different input element.

For example if the username is "admin" it should hide the password field.

If you they type in anything else then the password field appears or remains.

function togglePassword() {
  if ($("#j_username").val() == "admin")
    $("#j_password").hide();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>User Name</label>
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1' onkeypress='javascript:return loginIdKeyPress(event);' />

<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2' onkeypress='javascript:return passwordKeyPress(event);' />
<br/></code>```

Currently this code doesn't work for me, what should I change?

答:
First you should actually call your function togglePassword()

Second, you need to call it when you release a key, i.e. you need to use onkeyup. Otherwise your password field will update one keystroke "too late" because onkeypress calls the function when the key is pushed down, i.e. when you press "n" it will be called, before the n actually is written.

And last, you should also include an else-clause, to show your input in case it is hidden and the username is changed to something else.

function togglePassword() {
  if ($("#j_username").val() == "admin") {
    $("#j_password").hide();
  } else {
    $("#j_password").show();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>User Name</label>
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1' onkeyup='javascript:togglePassword();' />

<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2' />
<br/></code>```

Title: JQuery hide/show from textbox

Body:
I'm trying to get a password field to be shown/hidden depending on value that of a different input element.

For example if the username is "admin" it should hide the password field.

If you they type in anything else then the password field appears or remains.

function togglePassword() {
  if ($("#j_username").val() == "admin")
    $("#j_password").hide();
}

User Name
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1' onkeypress='javascript:return loginIdKeyPress(event);' />

Password
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2' onkeypress='javascript:return passwordKeyPress(event);' />

Currently this code doesn't work for me, what should I change?

Body:
First you should actually call your function togglePassword()

Second, you need to call it when you release a key, i.e. you need to use onkeyup. Otherwise your password field will update one keystroke "too late" because onkeypress calls the function when the key is pushed down, i.e. when you press "n" it will be called, before the n actually is written.

And last, you should also include an else-clause, to show your input in case it is hidden and the username is changed to something else.

function togglePassword() {
  if ($("#j_username").val() == "admin") {
    $("#j_password").hide();
  } else {
    $("#j_password").show();
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>User Name</label>
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1' onkeyup='javascript:togglePassword();' />

<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2' />
<br/>


问:
How can I convert a byte[] to an Array (and back) using C#?
How can a byte[] instance be converted to an Array instance? And, how can I then convert an Array back to byte[]?</p>

答:
They are interchangeable:</p>

```<code>Array array = new byte[10];
byte[] buffer = (byte[]) array;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
They are interchangeable:

Array array = new byte[10];
byte[] buffer = (byte[]) array;


问:
No errors inside shader Java OpenGL code, but nothing is rendered inside window
I am trying to find what am I doing wrong in my code. I am using JOGL.

I'd like to make two VBOs, one for vertices, other for indices, inside a given object.

There is no error inside init(GLAutoDrawable glAutoDrawable) function, but display(GLAutoDrawable glAutoDrawable) does not show my object when running the program.

Where am I making a mistake? Thank you for help.

My code:

```<code>public class Test1 implements GLEventListener {

    private int program;

    IntBuffer vao = IntBuffer.allocate(1);
    private IntBuffer buffers = IntBuffer.allocate(2);
    private float[] vertices = {
            -0.853250f, -0.136293f, -0.188932f,
             -0.129650f, 0.416492f, 0.336788f,
             -1.129635f, 0.416492f, 0.661708f,
             -1.747674f, 0.416492f, -0.188932f,
             -1.129635f, 0.416492f, -1.039572f,
             -0.129650f, 0.416492f, -0.714652f,
             -0.576865f, 1.310922f, 0.661708f,
             -1.576849f, 1.310922f, 0.336788f,
             -1.576849f, 1.310922f, -0.714652f,
             -0.576865f, 1.310922f, -1.039572f,
             0.041175f, 1.310922f, -0.188932f,
             -0.853250f, 1.863707f, -0.188932f
    };
</code>```

答:
There are a considerable number of things wrong.

Your Vertex Shader is very clearly the code for a Fragment Shader. I don't know where you copied it from, but you need to fix that.

gluPerspective is intended for use with the Fixed-Function-Pipeline. It has no effect when you're using programmable shaders. You need to put a uniform for a projection matrix in your vertex shader and manually pass that matrix to the GL.

Most Java Wrappers for OpenGL require that their Buffers be "Directly Allocated", which means the backing memory is natively allocated, as opposed to being Java-Allocated. The easiest way to do that is with ByteBuffer.allocateDirect(sizeInBytes);, which returns a ByteBuffer that can then be converted to an IntBuffer or FloatBuffer using asFloatBuffer and asIntBuffer.

Body:
I am trying to find what am I doing wrong in my code. I am using JOGL.

I'd like to make two VBOs, one for vertices, other for indices, inside a given object.

There is no error inside init(GLAutoDrawable glAutoDrawable) function, but display(GLAutoDrawable glAutoDrawable) does not show my object when running the program.

Where am I making a mistake? Thank you for help.

My code:

public class Test1 implements GLEventListener {

    private int program;

    IntBuffer vao = IntBuffer.allocate(1);
    private IntBuffer buffers = IntBuffer.allocate(2);
    private float[] vertices = {
            -0.853250f, -0.136293f, -0.188932f,
             -0.129650f, 0.416492f, 0.336788f,
             -1.129635f, 0.416492f, 0.661708f,
             -1.747674f, 0.416492f, -0.188932f,
             -1.129635f, 0.416492f, -1.039572f,
             -0.129650f, 0.416492f, -0.714652f,
             -0.576865f, 1.310922f, 0.661708f,
             -1.576849f, 1.310922f, 0.336788f,
             -1.576849f, 1.310922f, -0.714652f,
             -0.576865f, 1.310922f, -1.039572f,
             0.041175f, 1.310922f, -0.188932f,
             -0.853250f, 1.863707f, -0.188932f
    };


问:
Targeting UI elements dynamically with Appcelerator Alloy?
Is there a way to target a specific alloy UI element by passing a variable? I would like to pass a variable like so:

controller.js

```<code>var flag = "se";
changeBackground(flag); //should change the background color of ImagView of the se flag

function changeBackground(elementToChange){
    elementToChange.backgroundColor = "red"; //does not work
   $. + elementToChange +  backgroundColor = "red"; //does not work
}
</code>```

view.xml

```<code><View id="flagRow" layout="horizontal" backgroundColor="blue" height="Ti.UI.SIZE">
    <ImageView id="se" height="20dp" left="5dp" image="/images/flags/se.png" onClick="downloadPastLanguageLevels"/>
    <ImageView id="de" height="20dp" left="10dp" image="/images/flags/de.png" onClick="downloadPastLanguageLevels"/>
    <ImageView id="en" height="20dp" left="10dp" image="/images/flags/en.png" onClick="downloadPastLanguageLevels"/>
            </View>
</code>```

Right now I am looping through the $.flagRow. container but I would rather know how to set the flag directly.

```<code>var i, view;
    for (i in $.flagRow.children) {
            view = $.flagRow.children[i];
            if (view.id.indexOf(flag) > -1) {
                view.backgroundColor = "red";
            } else {
                view.backgroundColor = "transparent";
            }
        }
</code>```

答:
You reference elements in a view from the controller by using $.id so if you had an element called "myButton" you would reference it as $.myButton. If you were passing the name as a variable to a function expecting a parameter called "element" then you'd address it as $[element] where element is a string representing the id so "myButton" in this case. </p>

<p>In your case changing the code to reference $[elementToChange] should do it. </p>

Body:
Is there a way to target a specific alloy UI element by passing a variable? I would like to pass a variable like so:

controller.js

var flag = "se";
changeBackground(flag); //should change the background color of ImagView of the se flag

function changeBackground(elementToChange){
    elementToChange.backgroundColor = "red"; //does not work
   $. + elementToChange +  backgroundColor = "red"; //does not work
}

view.xml

<View id="flagRow" layout="horizontal" backgroundColor="blue" height="Ti.UI.SIZE">
    <ImageView id="se" height="20dp" left="5dp" image="/images/flags/se.png" onClick="downloadPastLanguageLevels"/>
    <ImageView id="de" height="20dp" left="10dp" image="/images/flags/de.png" onClick="downloadPastLanguageLevels"/>
    <ImageView id="en" height="20dp" left="10dp" image="/images/flags/en.png" onClick="downloadPastLanguageLevels"/>
            </View>

Right now I am looping through the $.flagRow. container but I would rather know how to set the flag directly.

var i, view;
    for (i in $.flagRow.children) {
            view = $.flagRow.children[i];
            if (view.id.indexOf(flag) > -1) {
                view.backgroundColor = "red";
            } else {
                view.backgroundColor = "transparent";
            }
        }

Body:
You reference elements in a view from the controller by using $.id so if you had an element called "myButton" you would reference it as $.myButton. If you were passing the name as a variable to a function expecting a parameter called "element" then you'd address it as $[element] where element is a string representing the id so "myButton" in this case.

In your case changing the code to reference $[elementToChange] should do it.


问:
Using dispatchQueue in loops
I am attempting to loop something with a delay (just as a proof of concept) this is for something else. But to simplify it, here is an example.

so in this example, I have a string with "text" and I want to loop the addition of another string lets say 10 times. The only thing is that I want there to be a delay in each iteration. here is my code thus far.

// global variable

var myString = "text"

// an action inside a button

```<code>    let delayInSeconds = 1.0
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {

        for _ in 1...10 {
           self.myString += "another text"
        }
    }
    labelOne.text = myString

}
</code>```

I should add that the result is that all 10 "another text" are added immediately without any delay.

thank you

答:
If I understand correctly, you want to show the text one by one with delay for each “text”.
You can use recursion here.

1.Move the dispatch code into a method.
2. Remove for loop.
3. Do your necessary actions inside dispatch it.
4.call that same method  again inside dispatch.

Do remember to use a counter variable that increments each time method is called. Use it to break the recursion.

Title: Using dispatchQueue in loops

Body:
I am attempting to loop something with a delay (just as a proof of concept) this is for something else. But to simplify it, here is an example.

so in this example, I have a string with "text" and I want to loop the addition of another string lets say 10 times. The only thing is that I want there to be a delay in each iteration. here is my code thus far.

// global variable

var myString = "text"

// an action inside a button

    let delayInSeconds = 1.0
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {

        for _ in 1...10 {
           self.myString += "another text"
        }
    }
    labelOne.text = myString

}

I should add that the result is that all 10 "another text" are added immediately without any delay.

thank you


问:
how to display state inside input tag
I'm building the following react component and trying to add hidden to my input box.

```<code>class FontChooser extends React.Component {

constructor(props) {
super(props);
this.state={display:'hidden'};
}

render() {

return(
       <div>
          <input type="checkbox" id="boldCheckbox" this.state.display />
       </div>
);
}
}
</code>```

I also tried {this.state.display} but I get unexpected token

答:
Using input type attribute:

```<code><input type="text" type={this.state.display} />
</code>```

Using style:

```<code><input type="text" style={{...this.state}} />
</code>```

And change display: hidden to display: none inside your state object.

Title: how to display state inside input tag

Body:
I'm building the following react component and trying to add hidden to my input box.

class FontChooser extends React.Component {

constructor(props) {
super(props);
this.state={display:'hidden'};
}

render() {

return(

          <input type="checkbox" id="boldCheckbox" this.state.display />

);
}
}

I also tried {this.state.display} but I get unexpected token

Body:
Using input type attribute:

<input type="text" type={this.state.display} />

Using style:

<input type="text" style={{...this.state}} />

And change display: hidden to display: none inside your state object.


问:
Automate SAS program for different sites using %include
The problem I have is, I use the same program for reports on multiple sites. I have to run the code for each of them individually. I'm looking to automate my process to call the code and run for all sites in a go. This is the code I tried using but it is not working.

```<code>data _null_;
array sites {2} _temporary_ (SiteA SiteB);

do k = 1 to dim(sites);
    %let site = sites(k);

    %include '...path\SitesWait.sas';

end; run;
</code>```

The code in SiteWait works perfectly on its own. I defined a macro variable called site, which sets the site for the code to run.

The error I keep getting is 'ERROR 117-185: There was 1 unclosed DO block.'

Thanks

答:
You cannot include another multi-step program into the middle of a DATA step.  %include just puts lines from the file into the program stream as if the lines had been typed into program.  When SAS sees the first DATA or PROC statement in the included file it will stop compiling the DATA step in your main program and run it.  That is why your DO loop is not seeing the END statement.

You could just use a data step to generate code that sets the parameter and includes the program.

```<code>data _null_;
  length site $20 ;
  do site='SiteA','SiteB' ;
    call execute(cats('%nrstr(%let) site=',site,';'));
    call execute("%include '...path\SitesWait.sas';");
  end;
run;
</code>```

What you have created is basically a macro with a single parameter named SITE. In fact you could possible just use %INCLUDE as the body of the macro definition. Then you could just code the calls you want instead of trying to process some list of values.

```<code>%macro siteswait(site);
%include '...path\SitesWait.sas';
%mend;
%siteswait(SiteA)
%siteswait(SiteB)
</code>```

Body:
The problem I have is, I use the same program for reports on multiple sites. I have to run the code for each of them individually. I'm looking to automate my process to call the code and run for all sites in a go. This is the code I tried using but it is not working.

data _null_;
array sites {2} _temporary_ (SiteA SiteB);

do k = 1 to dim(sites);
    %let site = sites(k);

    %include '...path\SitesWait.sas';

end; run;

The code in SiteWait works perfectly on its own. I defined a macro variable called site, which sets the site for the code to run.

The error I keep getting is 'ERROR 117-185: There was 1 unclosed DO block.'

Thanks

Body:
You cannot include another multi-step program into the middle of a DATA step.  %include just puts lines from the file into the program stream as if the lines had been typed into program.  When SAS sees the first DATA or PROC statement in the included file it will stop compiling the DATA step in your main program and run it.  That is why your DO loop is not seeing the END statement.

You could just use a data step to generate code that sets the parameter and includes the program.

data _null_;
  length site $20 ;
  do site='SiteA','SiteB' ;
    call execute(cats('%nrstr(%let) site=',site,';'));
    call execute("%include '...path\SitesWait.sas';");
  end;
run;

What you have created is basically a macro with a single parameter named SITE. In fact you could possible just use %INCLUDE as the body of the macro definition. Then you could just code the calls you want instead of trying to process some list of values.

%macro siteswait(site);
%include '...path\SitesWait.sas';
%mend;
%siteswait(SiteA)
%siteswait(SiteB)


答:
In your example, you append your string ten times in the same work unit. Try dispatching work once per loop:

```<code>for delay in 1...10 {
    let delayInSeconds = Double(delay)
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
        self.myString += "another text"
        labelOne.text = myString
    }
}
</code>```

This loop won't work well for arbitrarily large values, though. It also doesn't provide the kind of precise timing we might want for user interface changes. For that, we can use Timer. Here’s the same problem reworked with Timer:

```<code>// Add to the class body…
var i = 1
// Lazy initialization so the timer isn’t initialized until we call it
lazy var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {timer in
    guard self.i <= 20 else {
        timer.invalidate()
        return
    }

    self.label.text?.append(" another text")
    self.i += 1
}

// Add to the button action…
timer.fire()
</code>```

Title: Using dispatchQueue in loops

Body:
In your example, you append your string ten times in the same work unit. Try dispatching work once per loop:

for delay in 1...10 {
    let delayInSeconds = Double(delay)
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
        self.myString += "another text"
        labelOne.text = myString
    }
}

This loop won't work well for arbitrarily large values, though. It also doesn't provide the kind of precise timing we might want for user interface changes. For that, we can use Timer. Here’s the same problem reworked with Timer:

// Add to the class body…
var i = 1
// Lazy initialization so the timer isn’t initialized until we call it
lazy var timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {timer in
    guard self.i <= 20 else {
        timer.invalidate()
        return
    }

    self.label.text?.append(" another text")
    self.i += 1
}

// Add to the button action…
timer.fire()


问:
requestAnimationFrame() not refreshing
I'm learning how to use requestAnimationFrame() and the animation changes when refreshing the page. Shouldn't it should continuously change the font size without having to refresh it? </p>

```<code>var x = Math.floor((Math.random() * 100));

function draw(){
  for (i=0; i < 100; i++){
    $("#lw").css("font-size", x);
  }
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);
</code>```

答: The problem is that your loop is setting the css to the value of x. Which is set outside of the loop.  If you want the size to get bigger set the font size to i instead of x</p>

Title: requestAnimationFrame() not refreshing

Body:
I'm learning how to use requestAnimationFrame() and the animation changes when refreshing the page. Shouldn't it should continuously change the font size without having to refresh it?

var x = Math.floor((Math.random() * 100));

function draw(){
  for (i=0; i < 100; i++){
    $("#lw").css("font-size", x);
  }
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);


问:
converting object to str and back to objects
i had a list of obj

```<code>[<DiffMatchPatch.patch_obj instance at 0x152a0b00>, <DiffMatchPatch.patch_obj instance at 0x152a0ab8>]
</code>```

i later converted them to a strs - then i got

```<code>["@@ -797,44 +797,8 @@\n :  %0A\n-       print 'WithDrwaing %25d' %25 shs%0A\n     \n", "@@ -854,158 +854,4 @@\n e %0A%0A\n-'''%0Aif __name__ == '__main__': %0A       b=Transcations(amount=9) %0A       b.deposit() %0A       b.withdraw(2000) %0A       b.interest(30) %0A       b.chk()%0A'''%0A%0A%0A\n"]
</code>```

is it possible to convert the strs back to objects?

答:
You must use Pickle for this purpose... </p>

```<code>from cPickle import dumps, loads

lst = [1,2,3]
pckld = dumps(lst)

print (pckld)
>> '(lp1\nI1\naI2\naI3\na.'

loads(pckld)
>> [1,2,3]
</code>```

Body:
i had a list of obj

[<DiffMatchPatch.patch_obj instance at 0x152a0b00>, <DiffMatchPatch.patch_obj instance at 0x152a0ab8>]

i later converted them to a strs - then i got

["@@ -797,44 +797,8 @@\n :  %0A\n-       print 'WithDrwaing %25d' %25 shs%0A\n     \n", "@@ -854,158 +854,4 @@\n e %0A%0A\n-'''%0Aif __name__ == '__main__': %0A       b=Transcations(amount=9) %0A       b.deposit() %0A       b.withdraw(2000) %0A       b.interest(30) %0A       b.chk()%0A'''%0A%0A%0A\n"]

is it possible to convert the strs back to objects?

Body:
You must use Pickle for this purpose...

from cPickle import dumps, loads

lst = [1,2,3]
pckld = dumps(lst)

print (pckld)
>> '(lp1\nI1\naI2\naI3\na.'

loads(pckld)
>> [1,2,3]


问:
How to verify/test Apache server
I am new to Apache server and Ubuntu.

I have Apache/2.4.29 installed on Ubuntu 14.04.5 LTS.

I was working on compliance/security issue on this Linux box.

My manager asked me to verify/test Apache server.

How do I go about doing this?

What are some of basic steps I could take?

I tried searching at Google, but this area is so broad, so I cannot focus where to go.

答:
If your manager is asking for a basic connectivity test the simplest answer is to create an index.html file, copy  it to the root folder of your server and then connect using a browser pointing to your server IP address.

Something like http://192.168.0.6

Here are a couple links to get you started:

http://php.net/manual/en/tutorial.firstpage.php

https://mediatemple.net/community/products/dv/204643880/how-can-i-create-a-phpinfo.php-page

Good luck!

Title: How to verify/test Apache server


问:
Cake Build auto merge functionality
I'm using cakebuid as my build tool for TFS 2017 Update 2 and trying to implement the traditional Git Flow. In this flow, there are a few automatic merges that happen every time changes get into master, those changes need to be propagated to the develop branch.
Using cake I can run a PowerShell script or use LibGit2Sharp to accomplish the automatic merge for the best case scenarios. But, what about when the merge has conflicts? Do I need to fail the whole build because the merge process fail?
We have certainly something to deal with merges in TFS, this is no other than the Pull Request.

Question

Is there any tool or add-in for cake that allows me to create
  Pull Request during the execution of a build step?

答:
It was recently announced that there is a VSTS CLI:

https://blogs.msdn.microsoft.com/devops/2017/11/15/introducing-the-new-cli-for-vsts/

Which includes the ability to create a pull request:

https://learn.microsoft.com/en-gb/cli/vsts/get-started?view=vsts-cli-latest#create-a-pull-request

I don't think it would be particularly hard to create a Cake Addin which wraps this tool, and exposes the functionality through a set of addin's.

In the mean time, you could shell out to this tool using the Process aliases that currently exist in Cake.

Title: Cake Build auto merge functionality


问:
Training mxnet:mx.mlp
I am trying to reproduce an example from ND Lewis: Neural Networks for time series forecasting with R. If I include the device argument I get the error:

```<code>Error in mx.opt.sgd(...) :
  unused argument (device = list(device = "cpu", device_id = 0, device_typeid = 1))
In addition: Warning message:
In mx.model.select.layout.train(X, y) :
  Auto detect layout of input matrix, use rowmajor..
</code>```

If I remove this parameter, I still get this warning:

```<code>Warning message:
In mx.model.select.layout.train(X, y) :
  Auto detect layout of input matrix, use rowmajor..
</code>```

The code is:

```<code>library(zoo)
library(quantmod)
library(mxnet)

# data
data("ecoli", package = "tscount")
data <- ecoli$cases
data <- as.zoo(ts(data, start = c(2001, 1), end = c(2013, 20), frequency = 52))
xorig <- do.call(cbind, lapply((1:4), function(x) as.zoo(Lag(data, k = x))))
xorig <- cbind(xorig, data)
xorig <- xorig[-(1:4), ]

# normalization
range_data <- function(x) {
  (x - min(x))/(max(x) - min(x))
}
xnorm <- data.matrix(xorig)
xnorm <- range_data(xnorm)

# test/train
y <- xnorm[, 5]
x <- xnorm[, -5]
n_train <- 600
x_train <- x[(1:n_train), ]
y_train <- y[(1:n_train)]
x_test <- x[-(1:n_train), ]
y_test <- y[-(1:n_train)]

# mxnet:
mx.set.seed(2018)
model1 <- mx.mlp(x_train,
                 y_train,
                 hidden_node = c(10, 2),
                 out_node = 1,
                 activation = "sigmoid",
                 out_activation = "rmse",
                 num.round = 100,
                 array.batch.size = 20,
                 learning.rate = 0.07,
                 momentum = 0.9
                 #, device = mx.cpu()
)
pred1_train <- predict(model1, x_train, ctx = mx.cpu())
</code>```

How can I fix this?

答:
Regarding the second warning message, MXNet is trying to detect the row/column major based on the shape of your inputs: https://github.com/apache/incubator-mxnet/blob/424143ac47ab3a38ae8aedaeb3319379887de0bc/R-package/R/model.R#L329

For the unused argument device = mx.cpu(), should the argument name be corrected to ctx instead of device?

Title: Training mxnet:mx.mlp

Body:
I am trying to reproduce an example from ND Lewis: Neural Networks for time series forecasting with R. If I include the device argument I get the error:

Error in mx.opt.sgd(...) :
  unused argument (device = list(device = "cpu", device_id = 0, device_typeid = 1))
In addition: Warning message:
In mx.model.select.layout.train(X, y) :
  Auto detect layout of input matrix, use rowmajor..

If I remove this parameter, I still get this warning:

Warning message:
In mx.model.select.layout.train(X, y) :
  Auto detect layout of input matrix, use rowmajor..

The code is:

library(zoo)
library(quantmod)
library(mxnet)

# data
data("ecoli", package = "tscount")
data <- ecoli$cases
data <- as.zoo(ts(data, start = c(2001, 1), end = c(2013, 20), frequency = 52))
xorig <- do.call(cbind, lapply((1:4), function(x) as.zoo(Lag(data, k = x))))
xorig <- cbind(xorig, data)
xorig <- xorig[-(1:4), ]

# normalization
range_data <- function(x) {
  (x - min(x))/(max(x) - min(x))
}
xnorm <- data.matrix(xorig)
xnorm <- range_data(xnorm)

# test/train
y <- xnorm[, 5]
x <- xnorm[, -5]
n_train <- 600
x_train <- x[(1:n_train), ]
y_train <- y[(1:n_train)]
x_test <- x[-(1:n_train), ]
y_test <- y[-(1:n_train)]

# mxnet:
mx.set.seed(2018)
model1 <- mx.mlp(x_train,
                 y_train,
                 hidden_node = c(10, 2),
                 out_node = 1,
                 activation = "sigmoid",
                 out_activation = "rmse",
                 num.round = 100,
                 array.batch.size = 20,
                 learning.rate = 0.07,
                 momentum = 0.9
                 #, device = mx.cpu()
)
pred1_train <- predict(model1, x_train, ctx = mx.cpu())

How can I fix this?


问:
Possible to use string formatting to split a string value?
EDIT:
I'm stuck with python 2.7.5 ...

ANOTHER EDIT:
Clarifying the need for the changes to be in the template, not the code handling the dictionary.

I'm using a string formatter for building paths from templates.

I know I can do this:

```<code>currentUser = {'first': "Monty", 'last': "Python"}
template = '/usr/{user[last]}/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Python/Monty'
</code>```

but in the case of

```<code>currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
</code>```

Is there a way to split, say, by - and use an index?

```<code># something like:
template = '/usr/{user[last].split(-)[0]/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Luxury/Raymond'
</code>```

The decision to choose:

which key to split

by what character

which index to use from split

MUST come from the template string; if the current mini-language can't achieve this, I will have to write a custom formatter.

DISCLAIMER: The example is a bit contrived, and not practical, I know.  I'm actually dealing with a database where two key bits of information are stored in a single field, joined by underscores -_-.  I understand that I could do post-processing on the data after extracting it from the database, but due to conventions for this field differing per-project, I can't even assume that a split operation is valid (some values on some projects won't have the underscore issue).  Rather than code a solution around each convention, I'm hoping to be able to provide users with a template "language" so each project can themselves determine how to extract that data, adapt to whatever naming convention they choose, and configure their templates accordingly.

TL/DR: I'm not looking for a solution to fixing my incoming data -- I'm exploring the possibility of splitting strings using Python's string format mini-language.

答:
You can use dictionary comprehension:

```<code>currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
template = '/usr/{user[last]}/{user[first]}'
template.format(user={a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})
</code>```

Output:

```<code>'/usr/Luxury/Raymond'
</code>```

This will also work for your first example:

```<code>currentUser = {'first': "Monty", 'last': "Python"}
template = '/usr/{user[last]}/{user[first]}'
template.format(user={a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})
</code>```

Output:

```<code>'/usr/Python/Monty'
</code>```

As a side note, it is more Pythonic to use unpacking (**) in your formatting to remove the __getitem__ call in the string itself:

```<code>currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
template = '/usr/{last}/{first}'.format(**{a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})
</code>```

Body:
EDIT:
I'm stuck with python 2.7.5 ...

ANOTHER EDIT:
Clarifying the need for the changes to be in the template, not the code handling the dictionary.

I'm using a string formatter for building paths from templates.

I know I can do this:

currentUser = {'first': "Monty", 'last': "Python"}
template = '/usr/{user[last]}/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Python/Monty'

but in the case of

currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}

Is there a way to split, say, by - and use an index?

# something like:
template = '/usr/{user[last].split(-)[0]/{user[first]}' # will come from a config file
template.format(user=currentUser)
# Result: '/usr/Luxury/Raymond'

The decision to choose:

which key to split

by what character

which index to use from split

MUST come from the template string; if the current mini-language can't achieve this, I will have to write a custom formatter.

DISCLAIMER: The example is a bit contrived, and not practical, I know.  I'm actually dealing with a database where two key bits of information are stored in a single field, joined by underscores -_-.  I understand that I could do post-processing on the data after extracting it from the database, but due to conventions for this field differing per-project, I can't even assume that a split operation is valid (some values on some projects won't have the underscore issue).  Rather than code a solution around each convention, I'm hoping to be able to provide users with a template "language" so each project can themselves determine how to extract that data, adapt to whatever naming convention they choose, and configure their templates accordingly.

TL/DR: I'm not looking for a solution to fixing my incoming data -- I'm exploring the possibility of splitting strings using Python's string format mini-language.

Body:
You can use dictionary comprehension:

currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
template = '/usr/{user[last]}/{user[first]}'
template.format(user={a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})

Output:

'/usr/Luxury/Raymond'

This will also work for your first example:

currentUser = {'first': "Monty", 'last': "Python"}
template = '/usr/{user[last]}/{user[first]}'
template.format(user={a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})

Output:

'/usr/Python/Monty'

As a side note, it is more Pythonic to use unpacking (**) in your formatting to remove the __getitem__ call in the string itself:

currentUser = {'first': "Raymond", 'last': "Luxury-Yacht"}
template = '/usr/{last}/{first}'.format(**{a:b.split('-')[0] if '-' in b else b for a, b in currentUser.items()})


问:
round tick marks dynamically with ggplot2
I have the following dataframe:

```<code>rExp <- read.table(text='     samples variable value
UT            F201/203    0.00255836649706595
siCTL         F201/203    0.00911222024608249
siF201/203    F201/203    0.00473993831657716
UT            F203        0.0108815320248598
siCTL         F203        0.0224404694390467
siF201/203    F203        0.0115692755110973
UT            F203/206    0.00392331892967821
siCTL         F203/206    0.010474094476624
siF201/203    F203/206    0.00494613385979193',   header=TRUE)
</code>```

I create a grouped bar plot using the following code:

```<code>p_rEx<- ggplot (data=rExp, aes(x=samples, y=value)) + scale_x_discrete(limits=samples)
p_rEx<- p_rEx + geom_bar (aes(fill = variable),stat = "identity", position = "dodge", colour='black')
p_rEx<- p_rEx + labs(y="relative expression", x='')
p_rEx<- p_rEx + guides(fill=guide_legend(title=NULL))
p_rEx<- p_rEx + scale_fill_manual(values=gray.colors(3, start = 0.3, end = 0.9, gamma = 2.2, alpha = NULL))
p_rEx
</code>```

The result is the following plot:

My problem with this is, that the tick marks are very weird numbers.
I would like them to be more "round", e.g. 0.01 instead of 0.010474094476624

The y axis needs to stay continuous though, as y values could be anywhere between 10 and 1*10^-10.

I tried something like  + scale_y_continuous(breaks= pretty_breaks()), but gave me an error (Error: Discrete value supplied to continuous scale)

Is there a way to fix this?
Thank you!

Edit:
I do not think this is the duplicate of this question:
How do I change the number of decimal places on axis labels in ggplot2?

Here, I ask for a dynamic version, that works for all y values. so a dynamic adjustment of the decimal places

答:
It looks like you've just imprted your values are a factor variable rather than numeric. Therefor the problem really is with your data import and not ggplot. But you can maybe fix it with</p>

```<code>ggplot(data=rExp, aes(x=samples, y=as.numeric(as.character(value))))
</code>```

Body:
I have the following dataframe:

rExp <- read.table(text='     samples variable value
UT            F201/203    0.00255836649706595
siCTL         F201/203    0.00911222024608249
siF201/203    F201/203    0.00473993831657716
UT            F203        0.0108815320248598
siCTL         F203        0.0224404694390467
siF201/203    F203        0.0115692755110973
UT            F203/206    0.00392331892967821
siCTL         F203/206    0.010474094476624
siF201/203    F203/206    0.00494613385979193',   header=TRUE)

I create a grouped bar plot using the following code:

p_rEx<- ggplot (data=rExp, aes(x=samples, y=value)) + scale_x_discrete(limits=samples)
p_rEx<- p_rEx + geom_bar (aes(fill = variable),stat = "identity", position = "dodge", colour='black')
p_rEx<- p_rEx + labs(y="relative expression", x='')
p_rEx<- p_rEx + guides(fill=guide_legend(title=NULL))
p_rEx<- p_rEx + scale_fill_manual(values=gray.colors(3, start = 0.3, end = 0.9, gamma = 2.2, alpha = NULL))
p_rEx

The result is the following plot:

My problem with this is, that the tick marks are very weird numbers.
I would like them to be more "round", e.g. 0.01 instead of 0.010474094476624

The y axis needs to stay continuous though, as y values could be anywhere between 10 and 1*10^-10.

I tried something like  + scale_y_continuous(breaks= pretty_breaks()), but gave me an error (Error: Discrete value supplied to continuous scale)

Is there a way to fix this?
Thank you!

Edit:
I do not think this is the duplicate of this question:
How do I change the number of decimal places on axis labels in ggplot2?

Here, I ask for a dynamic version, that works for all y values. so a dynamic adjustment of the decimal places

Body:
It looks like you've just imprted your values are a factor variable rather than numeric. Therefor the problem really is with your data import and not ggplot. But you can maybe fix it with

ggplot(data=rExp, aes(x=samples, y=as.numeric(as.character(value))))


问:
Getting coordinates of manually drawn points
I have a graph as a result of executing ListPlot[] function.
I can manually edit this graph by moving points to a different location
and also adding new points using the Drawing Tools.

How do I get the coordinates of new and changed points from the edited graphics?

答:
I'm not sure if the following is anything like what you want,but nevertheless:

If I use ListPlot as follows:

```<code>lp1 = Labeled[
   ListPlot[Diagonal@Table[{x, y}, {x, 0, 5}, {y, 5}],
    PlotStyle -> {Directive[Red, PointSize[Large]]}], "lp1"];
</code>```

By double clicking on one of the red points twice to get the selection to the level of the points, I can then move the individual points, e.g., to make the points lie on a curve (rather than a straight line). I now want to extract these points (and say use them in a new ListPlot) [see plots below]

If I  click on the bracket of the plot graphic and use "Show Expression" (Command Shift E on a Mac), I can 'see' the coordinates of the modified points which may then be extracted.  For example:

```<code>expr = Cell[
   BoxData[GraphicsBox[{RGBColor[1, 0, 0], PointSize[Large],
      PointBox[{{0., 1.}, {0.8254488458250212,
         2.886651181634783}, {1.9301795383300084`,
         3.925201233010209}, {3.046546974446661,
         4.597525796319094}, {4., 5.}}]},
     AspectRatio -> NCache[GoldenRatio^(-1), 0.6180339887498948],
     Axes -> True, PlotRange -> Automatic,
     PlotRangeClipping -> True]], "Input",
   CellChangeTimes -> {{3.504427833788156*^9, 3.50442786823486*^9}}];
</code>```

Modifying a very useful approach originally suggested by Yaroslav Bulatov, which may be found here

```<code>modpoints = Flatten[Cases[expr, PointBox[___], Infinity][[All, 1]], {{2, 1}}]
</code>```

EDIT

As pointed out by belisarius, it is desirable to be able to extract 'manually' added points (which may be added to the generated plot using 'point' from the Drawing Tools palette). A better way of extracting (after 'Show Expression' ...) is probably the following:

```<code>modpoints = Cases[Cases[expr, PointBox[___],
  Infinity], {_?NumericQ, _?NumericQ}, Infinity]
</code>```

Of course, 'Show Expression' is not the only approach.

InputForm is another possibility. For example,

```<code>expr2 = InputForm[ListPlotGraphic]

modpoints = Cases[Cases[expr, Point[___],
  Infinity], {_?NumericQ, _?NumericQ}, Infinity]
</code>```

where "ListPlotGraphic" is the modified graphic (inserted by 'copy and paste'), will also work.

Example plots

Addendum

The above can be automated with a little notebook programming:

```<code>lp1 = Labeled[
  ListPlot[Diagonal@Table[{x, y}, {x, 0, 5}, {y, 5}],
   PlotStyle -> {Directive[Red, PointSize[Large]]}],
  Button["Print points",
   With[{nb = ButtonNotebook[]},
    SelectionMove[nb, All, CellContents];
    Print[Cases[NotebookRead[nb],
       PointBox[{{_?NumericQ, _?NumericQ} ..}] |
       PointBox[{_?NumericQ, _?NumericQ}], Infinity]]]]]
</code>```

Running the above, moving the last two original (red) points and adding a couple of extra points in blue with the drawing tools then pressing the button yields

You can see that there is a single PointBox for the original data and a new PointBox for each of the added points. Of course, by modifying the above code, you can do more than simply print out the raw point coordinates.

Body:
I'm not sure if the following is anything like what you want,but nevertheless:

If I use ListPlot as follows:

lp1 = Labeled[
   ListPlot[Diagonal@Table[{x, y}, {x, 0, 5}, {y, 5}],
    PlotStyle -> {Directive[Red, PointSize[Large]]}], "lp1"];

By double clicking on one of the red points twice to get the selection to the level of the points, I can then move the individual points, e.g., to make the points lie on a curve (rather than a straight line). I now want to extract these points (and say use them in a new ListPlot) [see plots below]

If I  click on the bracket of the plot graphic and use "Show Expression" (Command Shift E on a Mac), I can 'see' the coordinates of the modified points which may then be extracted.  For example:

expr = Cell[
   BoxData[GraphicsBox[{RGBColor[1, 0, 0], PointSize[Large],
      PointBox[{{0., 1.}, {0.8254488458250212,
         2.886651181634783}, {1.9301795383300084`,
         3.925201233010209}, {3.046546974446661,
         4.597525796319094}, {4., 5.}}]},
     AspectRatio -> NCache[GoldenRatio^(-1), 0.6180339887498948],
     Axes -> True, PlotRange -> Automatic,
     PlotRangeClipping -> True]], "Input",
   CellChangeTimes -> {{3.504427833788156*^9, 3.50442786823486*^9}}];

Modifying a very useful approach originally suggested by Yaroslav Bulatov, which may be found here

modpoints = Flatten[Cases[expr, PointBox[___], Infinity][[All, 1]], {{2, 1}}]

EDIT

As pointed out by belisarius, it is desirable to be able to extract 'manually' added points (which may be added to the generated plot using 'point' from the Drawing Tools palette). A better way of extracting (after 'Show Expression' ...) is probably the following:

modpoints = Cases[Cases[expr, PointBox[___],
  Infinity], {_?NumericQ, _?NumericQ}, Infinity]

Of course, 'Show Expression' is not the only approach.

InputForm is another possibility. For example,

expr2 = InputForm[ListPlotGraphic]

modpoints = Cases[Cases[expr, Point[___],
  Infinity], {_?NumericQ, _?NumericQ}, Infinity]

where "ListPlotGraphic" is the modified graphic (inserted by 'copy and paste'), will also work.

Example plots

Addendum

The above can be automated with a little notebook programming:

lp1 = Labeled[
  ListPlot[Diagonal@Table[{x, y}, {x, 0, 5}, {y, 5}],
   PlotStyle -> {Directive[Red, PointSize[Large]]}],
  Button["Print points",
   With[{nb = ButtonNotebook[]},
    SelectionMove[nb, All, CellContents];
    Print[Cases[NotebookRead[nb],
       PointBox[{{_?NumericQ, _?NumericQ} ..}] |
       PointBox[{_?NumericQ, _?NumericQ}], Infinity]]]]]

Running the above, moving the last two original (red) points and adding a couple of extra points in blue with the drawing tools then pressing the button yields

You can see that there is a single PointBox for the original data and a new PointBox for each of the added points. Of course, by modifying the above code, you can do more than simply print out the raw point coordinates.


问:
extend or implement simplexml to avoid DRY
Please check following class that I've create to build few XML frames..

```<code>class CommandBuilder
{
    public function __construct()
    {
        //
    }

    public function login($username, $password)
    {
        $frame = $this->frame();

        $command = $frame->addChild('command');
        $login = $command->addChild('login');
        $login->addChild('username', $username);
        $login->addChild('password', $password);
        $command->addChild('authKey', 'authkey');

        return $frame->asXML();
    }

    public function info($id)
    {
        $frame = $this->frame();

        $command = $frame->addChild('command');
        $login = $command->addChild('product');
        $login->addChild('id', $id);
        $command->addChild('authKey', 'authkey');

        return $frame->asXML();
    }

    protected function frame()
    {
        return new SimpleXMLElement(
            '<app/>'
        );
    }
}
</code>```

What's the best way to avoid duplication of $frame->addChild('command') and $command->addChild('authKey', 'authkey') without changing order of elements?

Please help to improve the code. Thanks

答:
Although the code you have could be simplified, there are complications.  The way I've done it moves the building of the frame into the frame method.  Each of the other routines builds the basis of the <command> node and passes this on, the frame method then adds the authkey bit.  This code would do the same - BUT it would have to be done on all frames...

```<code>class CommandBuilder
{
    public function __construct()
    {
        //
    }

    public function login($username, $password)
    {
        $command = new SimpleXMLElement('<command />');
        $login = $command->addChild('login');
        $login->addChild('username', $username);
        $login->addChild('password', $password);

        return $this->frame($command);
    }

    public function info($id)
    {
        $command = new SimpleXMLElement('<command />');
        $login = $command->addChild('product');
        $login->addChild('id', $id);

        return $this->frame($command);
    }

    protected function frame( $node )   {
        $node->addChild('authKey', 'authkey');
        $xml = new DOMDocument();
        $xml->loadXML('<app/>');
        // Convert SimpleXML to DOMDocument
        $fromDom = dom_import_simplexml($node);
        // Add in the $node passed in to the frame
        $xml->documentElement->appendChild($xml->importNode($fromDom, true));

        return $xml->saveXML();
    }
}
</code>```

Body:
Please check following class that I've create to build few XML frames..

class CommandBuilder
{
    public function __construct()
    {
        //
    }

    public function login($username, $password)
    {
        $frame = $this->frame();

        $command = $frame->addChild('command');
        $login = $command->addChild('login');
        $login->addChild('username', $username);
        $login->addChild('password', $password);
        $command->addChild('authKey', 'authkey');

        return $frame->asXML();
    }

    public function info($id)
    {
        $frame = $this->frame();

        $command = $frame->addChild('command');
        $login = $command->addChild('product');
        $login->addChild('id', $id);
        $command->addChild('authKey', 'authkey');

        return $frame->asXML();
    }

    protected function frame()
    {
        return new SimpleXMLElement(
            '<app/>'
        );
    }
}

What's the best way to avoid duplication of $frame->addChild('command') and $command->addChild('authKey', 'authkey') without changing order of elements?

Please help to improve the code. Thanks

Body:
Although the code you have could be simplified, there are complications.  The way I've done it moves the building of the frame into the frame method.  Each of the other routines builds the basis of the <command> node and passes this on, the frame method then adds the authkey bit.  This code would do the same - BUT it would have to be done on all frames...

class CommandBuilder
{
    public function __construct()
    {
        //
    }

    public function login($username, $password)
    {
        $command = new SimpleXMLElement('<command />');
        $login = $command->addChild('login');
        $login->addChild('username', $username);
        $login->addChild('password', $password);

        return $this->frame($command);
    }

    public function info($id)
    {
        $command = new SimpleXMLElement('<command />');
        $login = $command->addChild('product');
        $login->addChild('id', $id);

        return $this->frame($command);
    }

    protected function frame( $node )   {
        $node->addChild('authKey', 'authkey');
        $xml = new DOMDocument();
        $xml->loadXML('<app/>');
        // Convert SimpleXML to DOMDocument
        $fromDom = dom_import_simplexml($node);
        // Add in the $node passed in to the frame
        $xml->documentElement->appendChild($xml->importNode($fromDom, true));

        return $xml->saveXML();
    }
}


问:
spring-batch ItemReader for Elasticsearch scan and scroll
In spring-batch, is there any support for Elasticsearch ItemReader, using the scan and scroll functionality? I do see this extension, but that's based on the normal spring-data search queries. Would be nice to have one based on the scan and scroll feature, since the batch job mostly would need to process large batch of data. Thanks.</p>

答:
```<code>import java.util.Iterator;

import org.springframework.batch.item.data.AbstractPaginatedDataItemReader;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.query.SearchQuery;

public class ElasticsearchItemReader<T> extends AbstractPaginatedDataItemReader<T> {
    private ElasticsearchOperations elasticsearchOperations;
    private final SearchQuery searchQuery;
    private String scrollId;
    private int scrollTimeinMillis = 60000;
    private Class<T> type;

    public ElasticsearchItemReader(
        final ElasticsearchOperations elasticsearchOperations,
        final SearchQuery searchQuery,
        final Class<T> type
    ) {
        this.elasticsearchOperations = elasticsearchOperations;
        this.searchQuery = searchQuery;
        this.type = type;
    }

    @Override
    protected void doOpen() throws Exception {
        scrollId = elasticsearchOperations.scan(searchQuery, scrollTimeinMillis, false);
    }

    @Override
    protected Iterator<T> doPageRead() {
        return elasticsearchOperations.scroll(scrollId, scrollTimeinMillis, type).iterator();
   }
}
</code>```


问:
Get string between two characters SQL Server 2008R2
How do I pick abc1234 from below string?

```<code>20250-abcdef-abc1234-0123
</code>```

Note* string size varies.

答:
```<code>declare @var varchar(256) = '20250-abcdef-abc1234-0123'

select right(left(@var,len(@var) - charindex('-',reverse(@var))),charindex('-',reverse(left(@var,len(@var) - charindex('-',reverse(@var))))) - 1)
</code>```

Detailed Version

```<code>declare @var varchar(256) = '20250-abcdef-abc1234-0123'
declare @FirstHyphenFromRight int
declare @TrimedToFirstHyphen varchar(256)
declare @SecondHyphenFromRight int
declare @Result varchar(256)

select
    @FirstHyphenFromRight       =       charindex('-',reverse(@var))
    ,@TrimedToFirstHyphen       =       left(@var,len(@var) - @FirstHyphenFromRight)
    ,@SecondHyphenFromRight     =       charindex('-',reverse(@TrimedToFirstHyphen))
    ,@Result                    =       right(@TrimedToFirstHyphen, @SecondHyphenFromRight - 1)     --minus 1 for the hyphen

select
    YourString              =   @var
    ,FirstHyphenFromRight   =   @FirstHyphenFromRight
    ,TrimedToFirstHyphen    =   @TrimedToFirstHyphen
    ,SecondHyphenFromRight  =   @SecondHyphenFromRight
    ,Result                 =   @Result
</code>```

Body:
How do I pick abc1234 from below string?

20250-abcdef-abc1234-0123

Note* string size varies.

Body:
declare @var varchar(256) = '20250-abcdef-abc1234-0123'

select right(left(@var,len(@var) - charindex('-',reverse(@var))),charindex('-',reverse(left(@var,len(@var) - charindex('-',reverse(@var))))) - 1)

Detailed Version

declare @var varchar(256) = '20250-abcdef-abc1234-0123'
declare @FirstHyphenFromRight int
declare @TrimedToFirstHyphen varchar(256)
declare @SecondHyphenFromRight int
declare @Result varchar(256)

select
    @FirstHyphenFromRight       =       charindex('-',reverse(@var))
    ,@TrimedToFirstHyphen       =       left(@var,len(@var) - @FirstHyphenFromRight)
    ,@SecondHyphenFromRight     =       charindex('-',reverse(@TrimedToFirstHyphen))
    ,@Result                    =       right(@TrimedToFirstHyphen, @SecondHyphenFromRight - 1)     --minus 1 for the hyphen

select
    YourString              =   @var
    ,FirstHyphenFromRight   =   @FirstHyphenFromRight
    ,TrimedToFirstHyphen    =   @TrimedToFirstHyphen
    ,SecondHyphenFromRight  =   @SecondHyphenFromRight
    ,Result                 =   @Result


问:
Display data from array to multiple elements in HTML Angular 4
I'm trying to show a list of informations from an XML to a list using Angular 4 and Angular Material.
I have already converted the XML to JSON and the JSON I retrieve is like this:

```<code>{
    "json": {

        "0": [{
                "Name": "John",
                "Address": "5th street",
                "Phone": "555-123-456"
            }

        ],
        "1": [{
                "Name": "Mary",
                "Address": "4th street",
                "Phone": "555-654-321"
            }

        ],
        "2": [{
                "Name": "Harry",
                "Address": "3th street",
                "Phone": "555-124-231"
            }

        ]

    }
}
</code>```

this is my ts file: [i] is the id and id has dozens of entries.

```<code>for (let i = 0; i< json.length; i++){
              this.name = json[i]['Name'];
              this.address = json[i]['Address'];
              this.phone = json[i]['Phone'];
 }
</code>```

this is my html file:

```<code><mat-list>
  <h3 mat-subheader>Your info</h3>
  <mat-list-item>
    <h2 mat-line>Your name is: <b>{{name}}</b></h2>
    <p mat-line> Your address is: <b> {{address}} </b></p>
    <p mat-line> Your phone is: <b> {{phone}} </b></p>
  </mat-list-item>
  <mat-divider></mat-divider>
</mat-list>
</code>```

The thing is, the list has dozens of rows but it is showing the first only.
My intention was to have all the items loaded on page.
Already tried using *ngFor but it didn't work.

I know I might have missed something stupid but I've tried a lot and searched a lot but couldn't find a solution.

Thanks in advance

答:
Well, I guess you are not using the iterated object properties. You need to used *ngFor and assign that single iterated object to you list-item elements. As per your code snippet, you can simply paste given code:

```<code><mat-list>
  <h3 mat-subheader>Ypur info</h3>
  <mat-list-item *ngFor="let item of jsonPosicao">
    <mat-icon mat-list-icon>directions_car</mat-icon>
    <h2 mat-line>Your name is: <b>item.Name</b></h2>
    <p mat-line> Your address is: <b>item.Address</b></p>
    <p mat-line> Your phone is: <b>item.Phone</b></p>
  </mat-list-item>
  <mat-divider></mat-divider>
</mat-list>
</code>```

Main thing is you use your iterated object viz. item in this case.

Body:
I'm trying to show a list of informations from an XML to a list using Angular 4 and Angular Material.
I have already converted the XML to JSON and the JSON I retrieve is like this:

{
    "json": {

        "0": [{
                "Name": "John",
                "Address": "5th street",
                "Phone": "555-123-456"
            }

        ],
        "1": [{
                "Name": "Mary",
                "Address": "4th street",
                "Phone": "555-654-321"
            }

        ],
        "2": [{
                "Name": "Harry",
                "Address": "3th street",
                "Phone": "555-124-231"
            }

        ]

    }
}

this is my ts file: [i] is the id and id has dozens of entries.

for (let i = 0; i< json.length; i++){
              this.name = json[i]['Name'];
              this.address = json[i]['Address'];
              this.phone = json[i]['Phone'];
 }

this is my html file:

<mat-list>

Your info

  <mat-list-item>

Your name is: {{name}}

 Your address is:  {{address}}

 Your phone is:  {{phone}}

  </mat-list-item>
  <mat-divider></mat-divider>
</mat-list>

The thing is, the list has dozens of rows but it is showing the first only.
My intention was to have all the items loaded on page.
Already tried using *ngFor but it didn't work.

I know I might have missed something stupid but I've tried a lot and searched a lot but couldn't find a solution.

Thanks in advance

Body:
Well, I guess you are not using the iterated object properties. You need to used *ngFor and assign that single iterated object to you list-item elements. As per your code snippet, you can simply paste given code:

<mat-list>
  <h3 mat-subheader>Ypur info</h3>
  <mat-list-item *ngFor="let item of jsonPosicao">
    <mat-icon mat-list-icon>directions_car</mat-icon>
    <h2 mat-line>Your name is: <b>item.Name</b></h2>
    <p mat-line> Your address is: <b>item.Address</b></p>
    <p mat-line> Your phone is: <b>item.Phone</b></p>
  </mat-list-item>
  <mat-divider></mat-divider>
</mat-list>

Main thing is you use your iterated object viz. item in this case.


问:
Retrieving array value from object array
I want to retrieve the array value name under my onRegister function. But I don't think arrayFullNames.name is correct.</p>

```<code>     var arrayFullNames = [
        {name: 'David', surname: 'Jones', age: 29},
        {name: 'Jack', surname: 'Sparrow', age: 33},
        {name: 'Monkey', surname: 'Idontknow', age: 9},
        {name: 'JavaScript' , surname: 'Something', age: '6 weeks'}
    ];

    function onRegister(){
      var userQuestion = prompt("What is your name", '');

    if(userQuestion == arrayFullNames.name){
      alert('name match');
     }else{
      alert('no match');
     }
  }
</code>```

答:
You can use array#some

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

var arrayFullNames = [{ name: 'David', surname: 'Jones', age: 29 }, { name: 'Jack', surname: 'Sparrow', age: 33 }, { name: 'Monkey', surname: 'Idontknow', age: 9 }, { name: 'JavaScript', surname: 'Something', age: '6 weeks' } ];

function onRegister() {
  var userQuestion = prompt("What is your name", '');
  if (arrayFullNames.some(({name}) => name === userQuestion)) {
    alert('name match');
  } else {
    alert('no match');
  }
}
onRegister()```

Body:
I want to retrieve the array value name under my onRegister function. But I don't think arrayFullNames.name is correct.

     var arrayFullNames = [
        {name: 'David', surname: 'Jones', age: 29},
        {name: 'Jack', surname: 'Sparrow', age: 33},
        {name: 'Monkey', surname: 'Idontknow', age: 9},
        {name: 'JavaScript' , surname: 'Something', age: '6 weeks'}
    ];

    function onRegister(){
      var userQuestion = prompt("What is your name", '');

    if(userQuestion == arrayFullNames.name){
      alert('name match');
     }else{
      alert('no match');
     }
  }


问:
Swift - login in VC, allows anyone to enter not verifying username and passwords match or saved
With using firebase as well. My signup is working well and it registers users. But my login was working fine at start but now it allows anyone to go to the next view(login).

Here's my code:

SignInVC..

```<code>import UIKit
import Firebase

class SignInVC: UIViewController {
    @IBOutlet weak var emailTF: UITextField!
    @IBOutlet weak var passwordTF: UITextField!

    @IBAction func onSignInTapped(_ sender: Any) {
        guard let email = emailTF.text,
        email != "",
        let password = passwordTF.text,
        password != ""
            else {
               AlertController.showAlert(self, title: "Missing Information", message: "Please fill in username and password")
                return
        }

        Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
            guard error == nil
                else {
                    AlertController.showAlert(self, title: "Oops!", message: error!.localizedDescription)
                    return
            }
            guard let user = user else {return}
            print(user.email ?? "Missing email address")
            print(user.displayName ?? "Missing name")
            print(user.uid)

            self.performSegue(withIdentifier: "signInSegue", sender: nil)
        }
    }

    //remove keyboard
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
}
</code>```

AlerControllerVC

```<code>import UIKit
import Firebase

class AlertController {
    static func showAlert(_ inViewController: UIViewController, title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(action)
        inViewController.present(alert, animated: true, completion: nil)
    }
}
</code>```

I tried many was and rewrote it again but wont work correct again, when executed it says:

".SignInVC: 0x7fd99c208280> whose view is not in the window hierarchy!"

答: Please check if your segue is from button to ViewController or from ViewController to ViewController. if it is from button to VC then it does not depend upon the code you wrote </p>

Body:
With using firebase as well. My signup is working well and it registers users. But my login was working fine at start but now it allows anyone to go to the next view(login).

Here's my code:

SignInVC..

import UIKit
import Firebase

class SignInVC: UIViewController {
    @IBOutlet weak var emailTF: UITextField!
    @IBOutlet weak var passwordTF: UITextField!

    @IBAction func onSignInTapped(_ sender: Any) {
        guard let email = emailTF.text,
        email != "",
        let password = passwordTF.text,
        password != ""
            else {
               AlertController.showAlert(self, title: "Missing Information", message: "Please fill in username and password")
                return
        }

        Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
            guard error == nil
                else {
                    AlertController.showAlert(self, title: "Oops!", message: error!.localizedDescription)
                    return
            }
            guard let user = user else {return}
            print(user.email ?? "Missing email address")
            print(user.displayName ?? "Missing name")
            print(user.uid)

            self.performSegue(withIdentifier: "signInSegue", sender: nil)
        }
    }

    //remove keyboard
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
}

AlerControllerVC

import UIKit
import Firebase

class AlertController {
    static func showAlert(_ inViewController: UIViewController, title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(action)
        inViewController.present(alert, animated: true, completion: nil)
    }
}

I tried many was and rewrote it again but wont work correct again, when executed it says:

".SignInVC: 0x7fd99c208280> whose view is not in the window hierarchy!"


问:
How do I have mails to a specific address trigger actions on a web server?
What I'm trying to do is figure up how I can configure a mail server such that mails to a specific address will trigger certain actions- e.g. inserting the subject line into a MySQL database, etc. This is for a web app in LAMP- basically I want people to be able to add things automatically via email if they'd rather do that than use the web interface. Kind of like how e.g. with Evernote you can send a mail to your custom address to add a note that way.

I realize this is a pretty vague question, what I'm looking for is a general place to start looking and learning. I'm reasonably familiar with website tech but when it comes to mail servers I'm completely clueless.  I'm not looking for any specific implementation: Rather I just want to know what are the basics I need familiarize myself to be able to attack the problem.

答:
If you want to trigger actions "in realtime" you best work with your own mailserver and use something like procmail: Here is an example from the procmail faq how to trigger actions on incoming mails: http://porkmail.org/era/procmail/mini-faq.html#rtfm

But if you can avoid this, just let the fun stuff of mailserver work handle your provider and scan one or more mailboxes via cron-job (on linux/unix) triggered scripts. A cronjob could e.g. be a command line PHP script or a wget script that does a HTTP request on your webserver script to start the action. Your script reads the actual mails via something like http://pear.php.net/manual/en/package.networking.net-pop3.php
(Try to avoid importing the same mail twice e.g. by relying on the message id of the mail or by creating SHA1/MD5 hashes on parts or the body of the mail).

A lot of ticket systems work like this (for example OTRS: http://otrs.org/downloads).


问:
Assimp import export format error
I have some 3D model in my format and want to change them to standard formats and use them in my project, so I started to use Assimp library. My code for create aiScene is:

```<code>const aiScene* GenerateScene(int NumberOftexture, float *texture, int NumberOfVertex, double *verftex, int NumberOftri, double *tri) {

MATFile *pmat;
const char **dir;
const char *name;
int   ndir;
int   i;
aiScene* scene=new aiScene();

scene->mRootNode = new aiNode();

scene->mMaterials = new aiMaterial*[1];
scene->mMaterials[0] = nullptr;
scene->mNumMaterials = 1;

scene->mMaterials[0] = new aiMaterial();

scene->mMeshes = new aiMesh*[1];
scene->mMeshes[0] = nullptr;
scene->mNumMeshes = 1;
scene->mMeshes[0] = new aiMesh();
scene->mMeshes[0]->mMaterialIndex = 0;
scene->mRootNode->mMeshes = new unsigned int[1];
scene->mRootNode->mMeshes[0] = 0;
scene->mRootNode->mNumMeshes = 1;

auto pMesh = scene->mMeshes[0];

pMesh->mTextureCoords[0] = new aiVector3D[NumberOftexture];
pMesh->mNumUVComponents[0] = NumberOftexture;
for (int i = 0; i < NumberOftexture; i++)
    pMesh->mTextureCoords[0][i] = aiVector3D(texture[i], (float)texture[i + NumberOftexture], (float)texture[i + 2 * NumberOftexture]);

pMesh->mVertices = new aiVector3D[NumberOfVertex];
pMesh->mNumVertices = NumberOfVertex;
for (int i = 0; i < NumberOfVertex; i++)
    pMesh->mVertices[i] = aiVector3D((float)verftex[i], (float)verftex[i + NumberOfVertex], (float)verftex[i + 2 * NumberOfVertex]);

pMesh->mFaces = new aiFace[NumberOftri];
pMesh->mNumFaces = NumberOftri;

for (int i = 0; i < NumberOftri;i++) {
    aiFace& face = pMesh->mFaces[i];
    face.mIndices = new unsigned int[3];
    face.mNumIndices = 3;
    face.mIndices[0] = (int)tri[i];
    face.mIndices[1] = (int)tri[i + NumberOftri];
    face.mIndices[2] = (int)tri[i + 2* NumberOftri];
}

aiExportScene(scene, "collada", "D:\\myColladaFile.dae", 0);

return scene;}
</code>```

It runs correctly but when I am going to open file with Assimp Library I got error. My import code is

scene = aiImportFile(path, aiProcessPreset_TargetRealtime_MaxQuality);

and I got error:

```<code>Info,  T10040: Load D:\myColladaFile.dae
Info,  T10040: Found a matching importer for this file format: Collada Importer.
Info,  T10040: Import root directory is 'D:\'
Error, T10040: Collada: D:\myColladaFile.dae - Invalid data index (32500/32500) in primitive specification
Info,  T10040: Load D:\myColladaFile.dae
Info,  T10040: Found a matching importer for this file format: Collada Importer.
Info,  T10040: Import root directory is 'D:\'
Error, T10040: Collada: D:\myColladaFile.dae - Invalid data index (32500/32500) in primitive specification
Info,  T10040: Load D:\myColladaFile.dae
Info,  T10040: Found a matching importer for this file format: Collada Importer.
Info,  T10040: Import root directory is 'D:\'
Error, T10040: Collada: D:\myColladaFile.dae - Invalid data index (32500/32500) in primitive specification
</code>```

But when i export as GLTF format it is correct. so How can i export and import with correct format?

答:
This sounds like a bug the Asset-Importer-Lib for me. When the glTF-exporter is able to export the scene it shall be valid at all.
As a workaround you can try to export it as a glFT-file, import it by using blender and export it as a collada file.

Could you create an issue report on Github/assimp please? A model to reproduce the issue would be really great.

Title: Assimp import export format error

Body:
I have some 3D model in my format and want to change them to standard formats and use them in my project, so I started to use Assimp library. My code for create aiScene is:

const aiScene* GenerateScene(int NumberOftexture, float *texture, int NumberOfVertex, double *verftex, int NumberOftri, double *tri) {

MATFile *pmat;
const char **dir;
const char *name;
int   ndir;
int   i;
aiScene* scene=new aiScene();

scene->mRootNode = new aiNode();

scene->mMaterials = new aiMaterial*[1];
scene->mMaterials[0] = nullptr;
scene->mNumMaterials = 1;

scene->mMaterials[0] = new aiMaterial();

scene->mMeshes = new aiMesh*[1];
scene->mMeshes[0] = nullptr;
scene->mNumMeshes = 1;
scene->mMeshes[0] = new aiMesh();
scene->mMeshes[0]->mMaterialIndex = 0;
scene->mRootNode->mMeshes = new unsigned int[1];
scene->mRootNode->mMeshes[0] = 0;
scene->mRootNode->mNumMeshes = 1;

auto pMesh = scene->mMeshes[0];

pMesh->mTextureCoords[0] = new aiVector3D[NumberOftexture];
pMesh->mNumUVComponents[0] = NumberOftexture;
for (int i = 0; i < NumberOftexture; i++)
    pMesh->mTextureCoords[0][i] = aiVector3D(texture[i], (float)texture[i + NumberOftexture], (float)texture[i + 2 * NumberOftexture]);

pMesh->mVertices = new aiVector3D[NumberOfVertex];
pMesh->mNumVertices = NumberOfVertex;
for (int i = 0; i < NumberOfVertex; i++)
    pMesh->mVertices[i] = aiVector3D((float)verftex[i], (float)verftex[i + NumberOfVertex], (float)verftex[i + 2 * NumberOfVertex]);

pMesh->mFaces = new aiFace[NumberOftri];
pMesh->mNumFaces = NumberOftri;

for (int i = 0; i < NumberOftri;i++) {
    aiFace& face = pMesh->mFaces[i];
    face.mIndices = new unsigned int[3];
    face.mNumIndices = 3;
    face.mIndices[0] = (int)tri[i];
    face.mIndices[1] = (int)tri[i + NumberOftri];
    face.mIndices[2] = (int)tri[i + 2* NumberOftri];
}

aiExportScene(scene, "collada", "D:\\myColladaFile.dae", 0);

return scene;}

It runs correctly but when I am going to open file with Assimp Library I got error. My import code is

scene = aiImportFile(path, aiProcessPreset_TargetRealtime_MaxQuality);

and I got error:

Info,  T10040: Load D:\myColladaFile.dae
Info,  T10040: Found a matching importer for this file format: Collada Importer.
Info,  T10040: Import root directory is 'D:\'
Error, T10040: Collada: D:\myColladaFile.dae - Invalid data index (32500/32500) in primitive specification
Info,  T10040: Load D:\myColladaFile.dae
Info,  T10040: Found a matching importer for this file format: Collada Importer.
Info,  T10040: Import root directory is 'D:\'
Error, T10040: Collada: D:\myColladaFile.dae - Invalid data index (32500/32500) in primitive specification
Info,  T10040: Load D:\myColladaFile.dae
Info,  T10040: Found a matching importer for this file format: Collada Importer.
Info,  T10040: Import root directory is 'D:\'
Error, T10040: Collada: D:\myColladaFile.dae - Invalid data index (32500/32500) in primitive specification

But when i export as GLTF format it is correct. so How can i export and import with correct format?


问:
PDFKit Watermark Annotation Issue
I'm playing around with Apple's PDFKit and I'm using their sample app for adding a watermark to a pdf document.

The code works as expected apart from one pdf that I have. This particular pdf will not allow the annotation of the watermark to occur.

I have edited the pdf so that it no longer has an owner but still no annotation. The only thing I can think of is that the version of this pdf is 1.7 all other versions of pdf that I tried were previous to 1.7.

Has anyone else had this problem when working with the latest PDFKit framework?

答:
Check the properties of PDF if changes are permitted and document is not locked

You can check the properties by

Print(document.islocked),
Print(document.ischangesallowed)
Etc

Title: PDFKit Watermark Annotation Issue


问:
Evaluating list of boolean methods ruby
I have a list of methods who if any of them evaluated to true, I have to trigger an action on the model, in this case it's model audit.

So for example :

```<code>def a?
  false # in reality this is some code
end

def b?
  true # in reality this is some code
end

def c?
  true # in reality this is some code
end
</code>```

Now I can group this into like a parent method like :

```<code>def parent_method
  a? || b? || c?
end
</code>```

This will short-circuit the code, and c? will never be executed which is great. I can execute my .audit method.

But if I wanted to pass in custom message to my .audit method, and I wanted to have different message for every method how can I do that?

My first though to have a hash with keys being the methods and values being the messages or something along that line. But in that case the short circuiting doesn't work as all methods are evaluated in advance. How can I make this work better and more efficient/elegant?

答:
Instead of true your method could return a trueish value like a symbol.

```<code>def a?
  false # in reality this is some code
end

def b?
  :b # in reality this is some code
end

def c?
  :c # in reality this is some code
end
</code>```

That you still allow to short-circuit the code in

```<code>def parent_method
  a? || b? || c?
end
</code>```

But now parent_method will not only return true or false but it would return a symbol that your allow returning a message that might be stored in a hash:

```<code>key = parent_method
audit(key) if key
</code>```

Title: Evaluating list of boolean methods ruby

Body:
I have a list of methods who if any of them evaluated to true, I have to trigger an action on the model, in this case it's model audit.

So for example :

def a?
  false # in reality this is some code
end

def b?
  true # in reality this is some code
end

def c?
  true # in reality this is some code
end

Now I can group this into like a parent method like :

def parent_method
  a? || b? || c?
end

This will short-circuit the code, and c? will never be executed which is great. I can execute my .audit method.

But if I wanted to pass in custom message to my .audit method, and I wanted to have different message for every method how can I do that?

My first though to have a hash with keys being the methods and values being the messages or something along that line. But in that case the short circuiting doesn't work as all methods are evaluated in advance. How can I make this work better and more efficient/elegant?

Body:
Instead of true your method could return a trueish value like a symbol.

def a?
  false # in reality this is some code
end

def b?
  :b # in reality this is some code
end

def c?
  :c # in reality this is some code
end

That you still allow to short-circuit the code in

def parent_method
  a? || b? || c?
end

But now parent_method will not only return true or false but it would return a symbol that your allow returning a message that might be stored in a hash:

key = parent_method
audit(key) if key


问:
How to retrieve grandchild objects from a parent using linq
I have several parent > child > grandchild relationships in my db schema.  Usually, I have the parent and I want some information about the grandchildren.  For example, I have a user who has a collection of social networks which have collections of friends.  I find myself writing this code over and over again.

```<code>        var friends = new List<Friend>();
        foreach (var socialNetwork in user.UserSocialNetworks)
        {
            foreach (var friend in socialNetwork.Friends)
            {
                friends.Add(friend);
            }
        }
</code>```

Is there a more elegant way to do this with linq?

What I'd really like to be able to do is "user.Friends" but I'd have to put a foreign key to user in the friend table and that doesn't smell right.  Here is what that would look like:

```<code>User          {Id,..}
SocialNetwork {Id, UserId, ...}
Friend        {Id, SocialNetworkId, UserId, ... }
</code>```

Thoughts?

答:
I know this old, but I've recently faced the same thing, and an alternative is to go about it the opposite way. Instead of starting at user and drilling down, start at Friend and filter based on the parent (or grandparent). You would need the user's Id for this. When the hierarchy gets deeper, I find this more legible. Something like:</p>

```<code>return _db<your entities>.Friend
    .Where(f => f.SocialNetwork.User.Id == userId)
    .ToList();
</code>```

Body:
I have several parent > child > grandchild relationships in my db schema.  Usually, I have the parent and I want some information about the grandchildren.  For example, I have a user who has a collection of social networks which have collections of friends.  I find myself writing this code over and over again.

        var friends = new List<Friend>();
        foreach (var socialNetwork in user.UserSocialNetworks)
        {
            foreach (var friend in socialNetwork.Friends)
            {
                friends.Add(friend);
            }
        }

Is there a more elegant way to do this with linq?

What I'd really like to be able to do is "user.Friends" but I'd have to put a foreign key to user in the friend table and that doesn't smell right.  Here is what that would look like:

User          {Id,..}
SocialNetwork {Id, UserId, ...}
Friend        {Id, SocialNetworkId, UserId, ... }

Thoughts?

Body:
I know this old, but I've recently faced the same thing, and an alternative is to go about it the opposite way. Instead of starting at user and drilling down, start at Friend and filter based on the parent (or grandparent). You would need the user's Id for this. When the hierarchy gets deeper, I find this more legible. Something like:

return _db<your entities>.Friend
    .Where(f => f.SocialNetwork.User.Id == userId)
    .ToList();


问:
Track events in Reactjs pages and components globally
I need to listen to following events and do action accordingly

Form submit event - if the form submission is successful, I need to broadcast success event Added Name Record and submit the data along with it to 3rd party service. If not, I need to broadcast a failed event say Name submission failed along with where the error occurred.

Page visit/Route Change - Self explanatory

Click events - Can be from list item click and button click. In case of list item need to pass item details and in case of button just the name  maybe

Searches - Any searches made should fire the event sending the keyword.

I am using React - 0.13 and Reflux store.

How can I  approach towards it to handle the events at a global level and without writing code at each button click/submit event/search etc ?

What is the best approach ? Body handler won't be enough I feel for this level of customisation required!

P.S - When I say broadcast let's assume that I have a 3rd party function call to make instead.

答:
Purely React ways:

Create base components to globally handle events with extensible event handling methods:

```<code>const MyForm = ({ onSubmit, children, ...props }) => (
  <form {...props} onSubmit={evt => {
    // do global handling
    onSubmit(evt);
  }}>
    {children}
  </form>
);

//use case
const CustomForm = () => (
  <MyForm onSubmit={evt => /* custom handling */}>
    {/* CustomForm inputs and such */}
  </MyForm>
)
</code>```

Alternatively, you could take the HOC approach and wrap each handler you need:

```<code>const MyFormHOC = FormComponent => {
  return class extends React.Component {
    render() {
      const { onSubmit, ...props } = this.props;
      return (
        <FormComponent {...props} onSubmit={evt => {
          // do global handling
          onSubmit(evt);
        }}/>
    }
  }
};

//use case
let CustomForm = ({ onSubmit, ...props }) => (
  <form onSubmit={evt => onSubmit(evt)}>
    {/* CustomForm inputs and such */}
  </form>
);
CustomForm = MyForm(CustomForm);
</code>```

Downside to HOC approach is that your components need to pass along the event handler to the DOM element that will ultimately call it.

You could go one step further and create a single base component or HOC that handles all of your global events and then start using that as needed on your other components. It would need to know which props are supported by what components, though (e.g., onSubmit doesn't belong on anything besides a form).

Body:
Purely React ways:

Create base components to globally handle events with extensible event handling methods:

const MyForm = ({ onSubmit, children, ...props }) => (
  <form {...props} onSubmit={evt => {
    // do global handling
    onSubmit(evt);
  }}>
    {children}
  </form>
);

//use case
const CustomForm = () => (
  <MyForm onSubmit={evt => /* custom handling */}>
    {/* CustomForm inputs and such */}
  </MyForm>
)

Alternatively, you could take the HOC approach and wrap each handler you need:

const MyFormHOC = FormComponent => {
  return class extends React.Component {
    render() {
      const { onSubmit, ...props } = this.props;
      return (
        <FormComponent {...props} onSubmit={evt => {
          // do global handling
          onSubmit(evt);
        }}/>
    }
  }
};

//use case
let CustomForm = ({ onSubmit, ...props }) => (
  <form onSubmit={evt => onSubmit(evt)}>
    {/* CustomForm inputs and such */}
  </form>
);
CustomForm = MyForm(CustomForm);

Downside to HOC approach is that your components need to pass along the event handler to the DOM element that will ultimately call it.

You could go one step further and create a single base component or HOC that handles all of your global events and then start using that as needed on your other components. It would need to know which props are supported by what components, though (e.g., onSubmit doesn't belong on anything besides a form).


问:
Maintain data in R package with scheduled sql pulls
I have a personal, non-CRAN, R package. Its purpose is reduce the amount of repeated wrangling I need to do. The data must be pulled from sql server. This pull from SQL is done weekly. Where should I put my sql file and where should I put the R code that does a scheduled weekly sql pull?</p>

答:
Do you mean you use SQL to pull data from somewhere? What is your data source? Or do you mean you write SQL to create data?

Without knowing the specific, you have 2 options:
1. You could use RODBC package and use sqlQuery() e.g.

```<code>Data<- sqlQuery(odbcDriverConnect(...),paste("SELECT
                            *
                          FROM DTtest;"))
</code>```

to 'call' your data from your data source using SQL. More information you can find: https://www.statmethods.net/input/dbinterface.html
This way, you do not need to worry about where to save your sql file (I assume you mean the data). In this case, you only need to make sure your working directory is properly linked to your R script or at least where your R output wants to be in.

Assuming, you have a SQL script to pull data from somewhere else, you can windows scheduler or any types of scheduler to schedule and run the script and make the output saved in one folder where you also use R to grab the data from that directory.

Body:
Do you mean you use SQL to pull data from somewhere? What is your data source? Or do you mean you write SQL to create data?

Without knowing the specific, you have 2 options:
1. You could use RODBC package and use sqlQuery() e.g.

Data<- sqlQuery(odbcDriverConnect(...),paste("SELECT
                            *
                          FROM DTtest;"))

to 'call' your data from your data source using SQL. More information you can find: https://www.statmethods.net/input/dbinterface.html
This way, you do not need to worry about where to save your sql file (I assume you mean the data). In this case, you only need to make sure your working directory is properly linked to your R script or at least where your R output wants to be in.

Assuming, you have a SQL script to pull data from somewhere else, you can windows scheduler or any types of scheduler to schedule and run the script and make the output saved in one folder where you also use R to grab the data from that directory.