问:
Android binding and JUnit testing of notification
I want to test my Android view models. Especially when the setter should notify about changes or not.

The view model looks like this (with more bindable properties):

public class EditViewModel extends BaseObservable {

  private String _comment;
  @Bindable
  public String getComment() {
    return _comment;
  }

  public void setComment(String comment) {
    if (_comment == null && comment == null) {
      // No changes, both NULL
      return;
    }

    if (_comment != null && comment != null && _comment.equals(comment)) {
      //No changes, both equals
      return;
    }

    _comment = comment;
    // Notification of change
    notifyPropertyChanged(BR.comment);
  }
}
```

<p>In my UnitTest I register a listener, to get the notifications and track them with a following class:</p>

<pre class="lang-java prettyprint-override"><code>public class TestCounter {
  private int _counter = 0;
  private int _fieldId = -1;

  public void increment(){
    _counter++;
  }

  public int getCounter(){
    return _counter;
  }

  public void setFieldId(int fieldId){
    _fieldId = fieldId;
  }

  public int getFieldId(){
    return _fieldId;
  }
}
</code>```

So my test methods looks like the following:

@Test
public void setComment_RaisePropertyChange() {
  // Arrange
  EditViewModel sut = new EditViewModel(null);
  sut.setComment("One");
  final TestCounter pauseCounter = new TestCounter();
  // -- Change listener
  sut.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
    @Override
    public void onPropertyChanged(Observable sender, int propertyId) {
      pauseCounter.increment();
      pauseCounter.setFieldId(propertyId);
    }
  });
  String newComment = "two";

  // Act
  sut.setComment(newComment);

  // Assert
  assertThat(pauseCounter.getCounter(), is(1));
  assertThat(pauseCounter.getFieldId(), is(BR.comment));
  assertThat(sut.getComment(), is(newComment));
}
```

<p>If I execute the test methods alone, this approach works well. If I execute all tests at one, some fail, that the notification was <code>0</code> times called. I think, that the assertions is called before the callback could be handled.</p>

<p>I tried already following approches:</p>

<p>(1) Mock the listener with mockito as described in https://fernandocejas.com/2014/04/08/unit-testing-asynchronous-methods-with-mockito/.</p>

<pre class="lang-java prettyprint-override"><code>@Test
public void setComment_RaisePropertyChange() {
  // Arrange
  EditViewModel sut = new EditViewModel(null);
  sut.setComment("One");
  Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);

  // -- Change listener
  sut.addOnPropertyChangedCallback(listener);
  String newComment = "two";

  // Act
  sut.setComment(newComment);

  // Assert
  verify(listener, timeout(500).times(1)).onPropertyChanged(any(Observable.class), anyInt());
}
</code>```

(2) Tried to use CountDownLatch as described in several SO answers.

None of them helped me. What can I do to be able to test the binding notification?

答:
Your tests are working as a local unit tests in a sample project (link to GitHub repo here). I cannot reproduce the errors you are getting. A working rough example of a test class complete with imports is as follows - it generates 100% code coverage of your EditViewModel:

import android.databinding.Observable;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;

public class EditViewModelTest {

    @Test
    public void setNewNonNullCommentRaisesPropertyChange() {
        // Arrange
        EditViewModel sut = new EditViewModel(null);
        sut.setComment("One");
        Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);
        sut.addOnPropertyChangedCallback(listener);
        String newComment = "two";

        // Act
        sut.setComment(newComment);

        // Assert
        verify(listener).onPropertyChanged(sut, BR.comment);
    }

    @Test
    public void setNewNullCommentRaisesPropertyChange() {
        // Arrange
        EditViewModel sut = new EditViewModel(null);
        sut.setComment("One");
        Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);
        sut.addOnPropertyChangedCallback(listener);
        String newComment = null;

        // Act
        sut.setComment(newComment);

        // Assert
        verify(listener).onPropertyChanged(sut, BR.comment);
    }

    @Test
    public void setEqualCommentDoesntRaisePropertyChange() {
        // Arrange
        EditViewModel sut = new EditViewModel(null);
        sut.setComment("One");
        Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);
        sut.addOnPropertyChangedCallback(listener);
        String newComment = "One";

        // Act
        sut.setComment(newComment);

        // Assert
        verify(listener, never()).onPropertyChanged(sut, BR.comment);
    }

    @Test
    public void setNullToNullDoesntRaisePropertyChange() {
        // Arrange
        EditViewModel sut = new EditViewModel(null);
        sut.setComment(null);
        Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);
        sut.addOnPropertyChangedCallback(listener);
        String newComment = null;

        // Act
        sut.setComment(newComment);

        // Assert
        verify(listener, never()).onPropertyChanged(sut, BR.comment);
    }
}
```

<p>To diagnose the problem you are having, please make sure you have the correct dependencies as below:</p>

```dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile "org.mockito:mockito-core:+"

    androidTestCompile "org.mockito:mockito-android:+"
}
```

<p>The older setup with <code>mockito</code> and <code>dexmaker</code> is no longer valid. The most current versions of Mockito can be found on Maven Central</p>

<p>Also please check you are writing a local unit test in <code>test</code> rather than an instrumented test in <code>androidTest</code> - see this question for the difference.</p>

<p>Furthermore, such scenarios with complex logic inside a <code>ViewModel</code> are often better tested by extracting a helper object, making the object a dependency for the ViewModel passed inside the constructor, and testing against the helper object rather than against the ViewModel itself.</p>

<p>This may seem counter-intuitive because we are trained to think of Models as data objects with no dependencies. However, a ViewModel is more than a mere Model - often it ends up taking responsibilities of conversion of both model to view and view to model as in the discussion here.</p>

<p>Assume you have a tested class <code>MyDateFormat</code> with a unit test against it somewhere else in your project. You can now write a ViewModel that depends on it like this:</p>

<pre class="lang-java prettyprint-override"><code>public class UserViewModel extends BaseObservable {

    private final MyDateFormat myDateFormat;

    @Nullable private String name;
    @Nullable private Date birthDate;

    public ProfileViewModel(@NonNull MyDateFormat myDateFormat) {
        this.myDateFormat = myDateFormat;
    }

    @Bindable
    @Nullable
    public String getName() {
        return name;
    }

    @Bindable
    @Nullable
    public String getBirthDate() {
        return birthDate == null ? null : myDateFormat.format(birthDate.toDate());
    }

    public void setName(@Nullable String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }

    public void setBirthDate(@Nullable Date birthDate) {
        this.birthDate = birthDate;
        notifyPropertyChanged(BR.birthDate);
    }
}
</code>```

Body:
I want to test my Android view models. Especially when the setter should notify about changes or not.

The view model looks like this (with more bindable properties):

public class EditViewModel extends BaseObservable {

  private String _comment;
  @Bindable
  public String getComment() {
    return _comment;
  }

  public void setComment(String comment) {
    if (_comment == null && comment == null) {
      // No changes, both NULL
      return;
    }

    if (_comment != null && comment != null && _comment.equals(comment)) {
      //No changes, both equals
      return;
    }

    _comment = comment;
    // Notification of change
    notifyPropertyChanged(BR.comment);
  }
}

In my UnitTest I register a listener, to get the notifications and track them with a following class:

public class TestCounter {
  private int _counter = 0;
  private int _fieldId = -1;

  public void increment(){
    _counter++;
  }

  public int getCounter(){
    return _counter;
  }

  public void setFieldId(int fieldId){
    _fieldId = fieldId;
  }

  public int getFieldId(){
    return _fieldId;
  }
}

So my test methods looks like the following:

@Test
public void setComment_RaisePropertyChange() {
  // Arrange
  EditViewModel sut = new EditViewModel(null);
  sut.setComment("One");
  final TestCounter pauseCounter = new TestCounter();
  // -- Change listener
  sut.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
    @Override
    public void onPropertyChanged(Observable sender, int propertyId) {
      pauseCounter.increment();
      pauseCounter.setFieldId(propertyId);
    }
  });
  String newComment = "two";

  // Act
  sut.setComment(newComment);

  // Assert
  assertThat(pauseCounter.getCounter(), is(1));
  assertThat(pauseCounter.getFieldId(), is(BR.comment));
  assertThat(sut.getComment(), is(newComment));
}

If I execute the test methods alone, this approach works well. If I execute all tests at one, some fail, that the notification was 0 times called. I think, that the assertions is called before the callback could be handled.

I tried already following approches:

(1) Mock the listener with mockito as described in https://fernandocejas.com/2014/04/08/unit-testing-asynchronous-methods-with-mockito/.

@Test
public void setComment_RaisePropertyChange() {
  // Arrange
  EditViewModel sut = new EditViewModel(null);
  sut.setComment("One");
  Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);

  // -- Change listener
  sut.addOnPropertyChangedCallback(listener);
  String newComment = "two";

  // Act
  sut.setComment(newComment);

  // Assert
  verify(listener, timeout(500).times(1)).onPropertyChanged(any(Observable.class), anyInt());
}

(2) Tried to use CountDownLatch as described in several SO answers.

None of them helped me. What can I do to be able to test the binding notification?

Body:
Your tests are working as a local unit tests in a sample project (link to GitHub repo here). I cannot reproduce the errors you are getting. A working rough example of a test class complete with imports is as follows - it generates 100% code coverage of your EditViewModel:

import android.databinding.Observable;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;

public class EditViewModelTest {

    @Test
    public void setNewNonNullCommentRaisesPropertyChange() {
        // Arrange
        EditViewModel sut = new EditViewModel(null);
        sut.setComment("One");
        Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);
        sut.addOnPropertyChangedCallback(listener);
        String newComment = "two";

        // Act
        sut.setComment(newComment);

        // Assert
        verify(listener).onPropertyChanged(sut, BR.comment);
    }

    @Test
    public void setNewNullCommentRaisesPropertyChange() {
        // Arrange
        EditViewModel sut = new EditViewModel(null);
        sut.setComment("One");
        Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);
        sut.addOnPropertyChangedCallback(listener);
        String newComment = null;

        // Act
        sut.setComment(newComment);

        // Assert
        verify(listener).onPropertyChanged(sut, BR.comment);
    }

    @Test
    public void setEqualCommentDoesntRaisePropertyChange() {
        // Arrange
        EditViewModel sut = new EditViewModel(null);
        sut.setComment("One");
        Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);
        sut.addOnPropertyChangedCallback(listener);
        String newComment = "One";

        // Act
        sut.setComment(newComment);

        // Assert
        verify(listener, never()).onPropertyChanged(sut, BR.comment);
    }

    @Test
    public void setNullToNullDoesntRaisePropertyChange() {
        // Arrange
        EditViewModel sut = new EditViewModel(null);
        sut.setComment(null);
        Observable.OnPropertyChangedCallback listener = mock(Observable.OnPropertyChangedCallback.class);
        sut.addOnPropertyChangedCallback(listener);
        String newComment = null;

        // Act
        sut.setComment(newComment);

        // Assert
        verify(listener, never()).onPropertyChanged(sut, BR.comment);
    }
}

To diagnose the problem you are having, please make sure you have the correct dependencies as below:

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

    testCompile "org.mockito:mockito-core:+"

    androidTestCompile "org.mockito:mockito-android:+"
}

The older setup with mockito and dexmaker is no longer valid. The most current versions of Mockito can be found on Maven Central

Also please check you are writing a local unit test in test rather than an instrumented test in androidTest - see this question for the difference.

Furthermore, such scenarios with complex logic inside a ViewModel are often better tested by extracting a helper object, making the object a dependency for the ViewModel passed inside the constructor, and testing against the helper object rather than against the ViewModel itself.

This may seem counter-intuitive because we are trained to think of Models as data objects with no dependencies. However, a ViewModel is more than a mere Model - often it ends up taking responsibilities of conversion of both model to view and view to model as in the discussion here.

Assume you have a tested class MyDateFormat with a unit test against it somewhere else in your project. You can now write a ViewModel that depends on it like this:

public class UserViewModel extends BaseObservable {

    private final MyDateFormat myDateFormat;

    @Nullable private String name;
    @Nullable private Date birthDate;

    public ProfileViewModel(@NonNull MyDateFormat myDateFormat) {
        this.myDateFormat = myDateFormat;
    }

    @Bindable
    @Nullable
    public String getName() {
        return name;
    }

    @Bindable
    @Nullable
    public String getBirthDate() {
        return birthDate == null ? null : myDateFormat.format(birthDate.toDate());
    }

    public void setName(@Nullable String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }

    public void setBirthDate(@Nullable Date birthDate) {
        this.birthDate = birthDate;
        notifyPropertyChanged(BR.birthDate);
    }
}


来源: stackexchange

问:
Notepad++ remove text between string+bracket and another bracket
So, I've seen that you can remove between two characters and remove between two strings but I haven't been able to find a system that works between a string and a character.

I need to remove the numbers between the two brackets in...

```<code>provinces= {
        923 6862 9794 9904 11751 11846 11882
}
</code>```

Keep in mind that these files also contains other brackets which are needed. I've looked around for a solution for this but none seem to work :/

Thanks for the help.

答:
This one will do the job:

Ctrl+H

Find what: \b(provinces\s*=\s*\{)[^}]+(\})

Replace with: $1$2

Replace all

Explanation:

```<code>\b          : a word boundary
(           : start group 1
  provinces : literally "provinces"
  \s*       : 0 or more spaces
  =         : equal sign
  \s*       : 0 or more spaces
  \{        : an open curly bracket, must be escaped because it has special meaning in regex
)           : end group 1
[^}]+       : any character that is not a close curly bracket
(\})        : group 2, a close curly bracket, escaped.
</code>```

Replacement:

```<code>$1$2        : group 1 then group 2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So, I've seen that you can remove between two characters and remove between two strings but I haven't been able to find a system that works between a string and a character.

I need to remove the numbers between the two brackets in...

provinces= {
        923 6862 9794 9904 11751 11846 11882
}

Keep in mind that these files also contains other brackets which are needed. I've looked around for a solution for this but none seem to work :/

Thanks for the help.

Body:
This one will do the job:

Ctrl+H

Find what: \b(provinces\s*=\s*\{)[^}]+(\})

Replace with: $1$2

Replace all

Explanation:

\b          : a word boundary
(           : start group 1
  provinces : literally "provinces"
  \s*       : 0 or more spaces
  =         : equal sign
  \s*       : 0 or more spaces
  \{        : an open curly bracket, must be escaped because it has special meaning in regex
)           : end group 1
[^}]+       : any character that is not a close curly bracket
(\})        : group 2, a close curly bracket, escaped.

Replacement:

$1$2        : group 1 then group 2


问:
Nested loop to fill a vector of vector of int in C++
I want to generate an std::vector of std::vector of int in order to represent k vectors each of which contains q integers in the following manner:

Vector 0: {0,1}

Vector 1: {2,3}

Vector 2: {4,5}

and so no. For this case k=3 and q=2, but they can be any integers >= 1. Due to the fact that this code belongs to a bigger project I have used a lot of declarations among which the following:

```<code>typedef int BlockId;
typedef vector< BlockId > ParallelClassIds;
</code>```

Let's say that each collection represent the notion of a "parallel class" and each integer the IDs of its elements what I call "blocks". I have implemented the following function that tries to create the above structure (k, q are private variables visible within the C++ class I declared)

```<code>vector< ParallelClassIds > generateResolutionIds(){

    //The variable to be returned
    vector< ParallelClassIds > ret(k, vector< BlockId >(q));

    for (int i = 0; i < k; i++){
        for(int j = 0; j < q; j++){
            printf("Current parallel class size %ld\n", ret.at(i).size());
            ret.at(i).push_back(i*q+j);
        }
    }

    return ret;
}
</code>```

But there are a lot of problems with this functions. First, the printf() sometimes print 2, sometimes 3 where I was expecting it to always print q==2. Also, instead of the above structure (I checked this by printing the returned structure) it seems to create something like this:

Vector 0: {0,0,0,1}

Vector 1: {0,0,2,3}

Vector 2: {0,0,4,5}

I really have no idea why this behavior is happening.

答:
You can also get the expected result only by replacing this line:

```<code>ret.at(i).push_back(i*q+j);
</code>```

with this:

```<code>ret[i][j] = i*q+j;
</code>```

Body:
I want to generate an std::vector of std::vector of int in order to represent k vectors each of which contains q integers in the following manner:

Vector 0: {0,1}

Vector 1: {2,3}

Vector 2: {4,5}

and so no. For this case k=3 and q=2, but they can be any integers >= 1. Due to the fact that this code belongs to a bigger project I have used a lot of declarations among which the following:

typedef int BlockId;
typedef vector< BlockId > ParallelClassIds;

Let's say that each collection represent the notion of a "parallel class" and each integer the IDs of its elements what I call "blocks". I have implemented the following function that tries to create the above structure (k, q are private variables visible within the C++ class I declared)

vector< ParallelClassIds > generateResolutionIds(){

    //The variable to be returned
    vector< ParallelClassIds > ret(k, vector< BlockId >(q));

    for (int i = 0; i < k; i++){
        for(int j = 0; j < q; j++){
            printf("Current parallel class size %ld\n", ret.at(i).size());
            ret.at(i).push_back(i*q+j);
        }
    }

    return ret;
}

But there are a lot of problems with this functions. First, the printf() sometimes print 2, sometimes 3 where I was expecting it to always print q==2. Also, instead of the above structure (I checked this by printing the returned structure) it seems to create something like this:

Vector 0: {0,0,0,1}

Vector 1: {0,0,2,3}

Vector 2: {0,0,4,5}

I really have no idea why this behavior is happening.

Body:
You can also get the expected result only by replacing this line:

ret.at(i).push_back(i*q+j);

with this:

ret[i][j] = i*q+j;


问:
How to make an existing Android app implement a master-detail layout
So I've built an application where you enter a bunch of information, click a button and it opens a new activity that graphs all the results.

I would like the interface and graph activities to be side-by-side on tablet devices, e.g. master-detail layout.

I've been through all the tutorials and understand it has something to do with Fragments, but don't need the tutorials lists or RecyclerView type approaches.

Can someone point me in the right direction? Reading more tutorials on lists and RecyclerView's isn't helping :(

答:
You do need to use fragments so learning how to use fragments is a good place to start.

I searched github for you and found this Master-Detail sample, with a link to his blog where he explains it in detail.
https://github.com/lurbas/MaterialMasterDetail

Android Studio will also provide you with a master-detail template. Create a new project and when you get to the screen that says "Add an Activity to Mobile," select the "Master/Detail Flow" activity. Study this bit of code and understand what it is doing.


问:
how to chain the START command in cmd?
My goal is to be able to chain START commands in a single cmd line.

Lets say I have a cmd window (lets call it starter). With a single line I want to start a new cmd window (lets call it cmd1) that will echo 1 and start another cmd window (lets call it cmd2) that will echo 2 and wait (with pause), after cmd1 called cmd2 (without waiting for it to finish) it will wait as well (with pause), after starter called cmd1 (without waiting for it to finish) it will close (or do nothing)

In the end I should end up with 2 cmd windows (cmd1 with "1" printed, cmd2 with 2 printed) and both are waiting for ENTER.

Running scheme:

```<code>--- Starter
    +--- Start cmd1 (Non-blocking)
    |    +--- Start cmd2 (Non-blocking)
    |    |    +--- Echo 2
    |    |    \--- Pause (Blocking cmd2)
    |    +--- Echo 1
    |    \--- Pause (Blocking cmd1)
    \---Do nothing (Starter, Incase running from bat file starter will exit)
</code>```

I wrote this cmd line in a bat file:

```<code>title starter
start cmd.exe /c start cmd.exe /c "echo 2 & pause" & echo 1 & pause
                       \----------cmd2-----------/
      \---------------------------cmd1----------------------------/
</code>```

(the "title starter" is just for understanding which window is opened and should not be included in the final line)

with that cmd line, starter is the one that prints 2 and waits, and cmd1 just exits after calling cmd2.

The running scheme of that line:

```<code>--- Starter
    +--- Start cmd1 (Non-blocking)
    |    \--- Start cmd2 (Non-blocking)
    |         +--- Echo 2
    |         \--- Pause (Blocking cmd2)
    +--- Echo 1
    +--- Pause (Blocking Starter)
    \---Do nothing (Starter, Incase running from bat file starter will exit)
</code>```

I tried some other variations of this line with no success.

```<code>title starter
start "cmd.exe /c start cmd.exe /c "echo 2 & pause" & echo 1 & pause"
start cmd.exe /c "start cmd.exe /c "echo 2 & pause" & echo 1 & pause"
start cmd.exe /c "start cmd.exe /c ""echo 2 & pause"" & echo 1 & pause"
</code>```

(important to note that I can open the 2 cmds (cmd1, cmd2) from the first cmd (starter) and the result of this will be the final result of my wanted running scheme, but it is important that cmd1 will be the one that creates cmd2)

So, does anyone know how may I achieve the running scheme that I want?

答:
I hope, I understood your requirements right...

```<code>title Starter
start "one" cmd.exe /c "start "two" cmd.exe /c "echo 2 ^& pause" & echo 1 &pause"
</code>```

The trick is proper escaping of & to pass it through the first pass of parsing to get then parsed with the second step.

I added titles to all windows.

Title: how to chain the START command in cmd?

Body:
My goal is to be able to chain START commands in a single cmd line.

Lets say I have a cmd window (lets call it starter). With a single line I want to start a new cmd window (lets call it cmd1) that will echo 1 and start another cmd window (lets call it cmd2) that will echo 2 and wait (with pause), after cmd1 called cmd2 (without waiting for it to finish) it will wait as well (with pause), after starter called cmd1 (without waiting for it to finish) it will close (or do nothing)

In the end I should end up with 2 cmd windows (cmd1 with "1" printed, cmd2 with 2 printed) and both are waiting for ENTER.

Running scheme:

--- Starter
    +--- Start cmd1 (Non-blocking)
    |    +--- Start cmd2 (Non-blocking)
    |    |    +--- Echo 2
    |    |    \--- Pause (Blocking cmd2)
    |    +--- Echo 1
    |    \--- Pause (Blocking cmd1)
    \---Do nothing (Starter, Incase running from bat file starter will exit)

I wrote this cmd line in a bat file:

title starter
start cmd.exe /c start cmd.exe /c "echo 2 & pause" & echo 1 & pause
                       \----------cmd2-----------/
      \---------------------------cmd1----------------------------/

(the "title starter" is just for understanding which window is opened and should not be included in the final line)

with that cmd line, starter is the one that prints 2 and waits, and cmd1 just exits after calling cmd2.

The running scheme of that line:

--- Starter
    +--- Start cmd1 (Non-blocking)
    |    \--- Start cmd2 (Non-blocking)
    |         +--- Echo 2
    |         \--- Pause (Blocking cmd2)
    +--- Echo 1
    +--- Pause (Blocking Starter)
    \---Do nothing (Starter, Incase running from bat file starter will exit)

I tried some other variations of this line with no success.

title starter
start "cmd.exe /c start cmd.exe /c "echo 2 & pause" & echo 1 & pause"
start cmd.exe /c "start cmd.exe /c "echo 2 & pause" & echo 1 & pause"
start cmd.exe /c "start cmd.exe /c ""echo 2 & pause"" & echo 1 & pause"

(important to note that I can open the 2 cmds (cmd1, cmd2) from the first cmd (starter) and the result of this will be the final result of my wanted running scheme, but it is important that cmd1 will be the one that creates cmd2)

So, does anyone know how may I achieve the running scheme that I want?

Body:
I hope, I understood your requirements right...

title Starter
start "one" cmd.exe /c "start "two" cmd.exe /c "echo 2 ^& pause" & echo 1 &pause"

The trick is proper escaping of & to pass it through the first pass of parsing to get then parsed with the second step.

I added titles to all windows.


问:
Selenium explicit wait for LinkedIn spinning circles
I am using Selenium and its Python bindings to webscrape from LinkedIn for a research project. I webscrape people's profiles.

In LinkedIn, when you load a person profile, the site puts spinning circles until the experiences and the education are fully loaded.
I want Selenium to wait until the spinning circles disappear, in order to get, in the HTML source code, the experience and the education sections.

So my question is: How can I code an explicit wait for the LinkedIn spinning circles?

EDIT: a more precise question would be: How can I get a locator for the spinning circles?
There is no time to do that from the browser development tools. They disappear too fast

EDIT 2: Another point. A person may or may not have an education section. So clicking or otherwise checking for the education section to be present is not a solution. The education section may not be present either because there is no education section (the person did not put any information on LinkedIn, which therefore is not putting an education section in the DOM) or because it is not loaded yet (there is a spinning circle). I want to know which one it is. If it is the second reason (there is a spinning circle), I want to wait. (the section is a div with a class named education-section). The same applies for the experiences

Here is the core of the project for the purpose of this question.

These are 2 functions inside of a class. self.getBrowser() return a WebDriver object. For the sake of clarity and brevity I have cut the non-interesting parts, including code inside the 2 functions, so the arguments which seems to not be used in reality are. I hope the remaining variables are self-explaining.

```<code>def waitForPresenceCondition(self, by, value, sleep = True, check_for_404 = True):
    try:
        condition = EC.visibility_of_element_located((by, value))
        WebDriverWait(self.getBrowser(), self.wait_timeout).until(condition)
    except TimeoutException:
        logging.critical("Timed out waiting for page element. Fatal. Exiting")
        raise
    except:
        logging.error("Unexpected exception waiting for page element. Exiting")
        raise
    else:
        logging.debug("Element found in URL")

# Scrape an organization
def scrape(self, url):
   self.getBrowser().get(url)
   try:
       self.waitForPresenceCondition(By.CLASS_NAME, "pv-profile-wrapper")
   except Error404:
       logging.info("waitForPresenceCondition raised 404 error. Returning False")
       return False
    #INSERT HERE EXPLICIT WAIT FOR THE SPINNING CIRCLES
</code>```

答:
The spinning wheels have a class named artdeco-spinner

I have found it by inserting a breakpoint in Chrome DevTools

Follow this guide and insert a breakpoint on "Animation" events

Then as suggested by @Andersson I have used Selenium invisibility_of_element_located function, which waits for a locator to be either invisible or not attached anymore to the DOM. I don't need to distinguish the 2 cases

```<code>def waitForInvisibility(self, by, value):
    condition_str = "(" + str(by) + "," + value + ")"
    url = self.getBrowserURL()
    msg = "Waiting for in-visibility of "
    msg += condition_str
    msg += " in URL='" + url + "'"
    logging.info(msg)
    try:
        condition = EC.invisibility_of_element_located((by, value))
        WebDriverWait(self.getBrowser(), self.wait_timeout).until(condition)
    except TimeoutException:
        logging.critical("Timed out waiting for element invisibility. Exiting")
        raise
    except:
        logging.error("Unexpected exception waiting for element invisibility. Exiting")
        raise
    else:
        logging.debug("Element " + condition_str + " is now invisible in URL='" + url + "'")
</code>```

Body:
I am using Selenium and its Python bindings to webscrape from LinkedIn for a research project. I webscrape people's profiles.

In LinkedIn, when you load a person profile, the site puts spinning circles until the experiences and the education are fully loaded.
I want Selenium to wait until the spinning circles disappear, in order to get, in the HTML source code, the experience and the education sections.

So my question is: How can I code an explicit wait for the LinkedIn spinning circles?

EDIT: a more precise question would be: How can I get a locator for the spinning circles?
There is no time to do that from the browser development tools. They disappear too fast

EDIT 2: Another point. A person may or may not have an education section. So clicking or otherwise checking for the education section to be present is not a solution. The education section may not be present either because there is no education section (the person did not put any information on LinkedIn, which therefore is not putting an education section in the DOM) or because it is not loaded yet (there is a spinning circle). I want to know which one it is. If it is the second reason (there is a spinning circle), I want to wait. (the section is a div with a class named education-section). The same applies for the experiences

Here is the core of the project for the purpose of this question.

These are 2 functions inside of a class. self.getBrowser() return a WebDriver object. For the sake of clarity and brevity I have cut the non-interesting parts, including code inside the 2 functions, so the arguments which seems to not be used in reality are. I hope the remaining variables are self-explaining.

def waitForPresenceCondition(self, by, value, sleep = True, check_for_404 = True):
    try:
        condition = EC.visibility_of_element_located((by, value))
        WebDriverWait(self.getBrowser(), self.wait_timeout).until(condition)
    except TimeoutException:
        logging.critical("Timed out waiting for page element. Fatal. Exiting")
        raise
    except:
        logging.error("Unexpected exception waiting for page element. Exiting")
        raise
    else:
        logging.debug("Element found in URL")

# Scrape an organization
def scrape(self, url):
   self.getBrowser().get(url)
   try:
       self.waitForPresenceCondition(By.CLASS_NAME, "pv-profile-wrapper")
   except Error404:
       logging.info("waitForPresenceCondition raised 404 error. Returning False")
       return False
    #INSERT HERE EXPLICIT WAIT FOR THE SPINNING CIRCLES

Body:
The spinning wheels have a class named artdeco-spinner

I have found it by inserting a breakpoint in Chrome DevTools

Follow this guide and insert a breakpoint on "Animation" events

Then as suggested by @Andersson I have used Selenium invisibility_of_element_located function, which waits for a locator to be either invisible or not attached anymore to the DOM. I don't need to distinguish the 2 cases

def waitForInvisibility(self, by, value):
    condition_str = "(" + str(by) + "," + value + ")"
    url = self.getBrowserURL()
    msg = "Waiting for in-visibility of "
    msg += condition_str
    msg += " in URL='" + url + "'"
    logging.info(msg)
    try:
        condition = EC.invisibility_of_element_located((by, value))
        WebDriverWait(self.getBrowser(), self.wait_timeout).until(condition)
    except TimeoutException:
        logging.critical("Timed out waiting for element invisibility. Exiting")
        raise
    except:
        logging.error("Unexpected exception waiting for element invisibility. Exiting")
        raise
    else:
        logging.debug("Element " + condition_str + " is now invisible in URL='" + url + "'")


问:
gwt intellij 10 plugin does not generate javascript output
With IntelliJ 10, I can easily create a module with a GWT sample application (MySampleApplication.gwt.xml), using the built-in GWT plugin.
This runs fine in hosted mode and I can step through the Java code.

But, I don't see any build options to have it generate the actual output javascript files that are generated by the gwt compiler (which is of course the point of gwt).

Do I have to fiddle with the ant or maven files myself?  Presumably there must be a way to get this intellij gwt plugin to make the gwt compiler run.

答:
GWT compiler is invoked when you build the artifact containing GWT Compiler output element. Such artifact is added automatically by IDEA for the new projects created via the wizard.

To build such artifact use Build | Build 'artifact name' Artifact. Note that you can configure IDEA to build artifacts on Build | Make automatically, but it's not recommended for GWT as it would invoke GWT compiler and take considerable time on every Make.

ContentLicense: CC BY-SA 2.5


问:
$http.post() method not working in angular js
I am trying to insert data's into db using spring, angularjs and hibernet.
in app.js file Controller method
$http.post(urlBase + '/angular/insert/' +$scope.Name+'/'+$scope.City)
was not working I don't know what is the mistake i have done.

AngularDate.jsp

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html ng-app="taskManagerApp">

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>AngularJS Task Manager</title>
        <script data-require="angular.js@*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
        <script src="<c:url value=" /resources/js/app.js "/>"></script>
    </head>

    <body>
        <div ng-controller="taskManagerController">
            <span>Add Task</span>
            <div>
                <div>
                    <table>
                        <tr>
                            <td> Name:</td>
                            <td>
                                <input type="text" ng-model="Name" />
                            </td>
                        </tr>
                        <tr>
                            <td>City:</td>
                            <td>
                                <input type="text" ng-model="City" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <button ng-click="addTask()" class="btn-panel-big">Add New Task</button>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </body>

</html>
</code>```

app.js

```<code>var taskManagerModule = angular.module('taskManagerApp', []);
var t = angular.module('taskManagerController', []);

taskManagerModule.controller('taskManagerController', function ($scope, $http) {
    var urlBase = "http://localhost:8081/logistics";
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

    //get all tasks and display initially
    //add a new task
    $scope.addTask = function addTask() {
        if ($scope.Name == "" || $scope.City == "") {
            alert("Insufficient Data! Please provide values for  name and city");
        }
        else {
            alert("else");
            $http.post(urlBase + '/angular/insert/' + $scope.Name + '/' + $scope.City).success(function (data) {
                 alert("Task added");
                 // $scope.tasks = data;
                 $scope.Name = "";
                 $scope.City = "";
                 //$scope.toggle='!toggle';
             });
        }
    };

    // Archive Completed Tasks
});

//Angularjs Directive for confirm dialog box
</code>```

Can anyone help me fix my issue?

答:
The $http post expects the POST body so if you have it then replace this

```<code>$http.post(urlBase + '/angular/insert/' +$scope.Name+'/'+$scope.City)
</code>```

with

```<code>//JSON data to post
var postData = {
  ...
  ...
 }
$http.post(urlBase + '/angular/insert/' +$scope.Name+'/'+$scope.City, postData).success(
function(data) {
    //success code
 })
</code>```

or if you do not have any post data then simply send an empty JSON object like

```<code> $http.post(urlBase + '/angular/insert/' +$scope.Name+'/'+$scope.City,{}).success(
    function(data) {
        //success code
     })
</code>```

Body:
I am trying to insert data's into db using spring, angularjs and hibernet.
in app.js file Controller method
$http.post(urlBase + '/angular/insert/' +$scope.Name+'/'+$scope.City)
was not working I don't know what is the mistake i have done.

AngularDate.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>AngularJS Task Manager</title>

            Add Task

                             Name:

                                <input type="text" ng-model="Name" />

                            City:

                                <input type="text" ng-model="City" />

                                <button ng-click="addTask()" class="btn-panel-big">Add New Task</button>

app.js

var taskManagerModule = angular.module('taskManagerApp', []);
var t = angular.module('taskManagerController', []);

taskManagerModule.controller('taskManagerController', function ($scope, $http) {
    var urlBase = "http://localhost:8081/logistics";
    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

    //get all tasks and display initially
    //add a new task
    $scope.addTask = function addTask() {
        if ($scope.Name == "" || $scope.City == "") {
            alert("Insufficient Data! Please provide values for  name and city");
        }
        else {
            alert("else");
            $http.post(urlBase + '/angular/insert/' + $scope.Name + '/' + $scope.City).success(function (data) {
                 alert("Task added");
                 // $scope.tasks = data;
                 $scope.Name = "";
                 $scope.City = "";
                 //$scope.toggle='!toggle';
             });
        }
    };

    // Archive Completed Tasks
});

//Angularjs Directive for confirm dialog box

Can anyone help me fix my issue?

Body:
The $http post expects the POST body so if you have it then replace this

$http.post(urlBase + '/angular/insert/' +$scope.Name+'/'+$scope.City)

with

//JSON data to post
var postData = {
  ...
  ...
 }
$http.post(urlBase + '/angular/insert/' +$scope.Name+'/'+$scope.City, postData).success(
function(data) {
    //success code
 })

or if you do not have any post data then simply send an empty JSON object like

 $http.post(urlBase + '/angular/insert/' +$scope.Name+'/'+$scope.City,{}).success(
    function(data) {
        //success code
     })


问:
Is it relevant to have a single inline function alone in a C file?
I am seeing this example where I have a crc32.c file which contains:

```<code>inline int32_t crc32_compute(int32_t *buffer, size_t size) {
   ...
}
</code>```

In the header file I find:

```<code>extern inline int32_t crc32_compute(int32_t *buffer, size_t size);
</code>```

To me the inline keyword has no effect because the function should be declared on the header file not on the C file. Is it that correct?

答:
They forgot a magic word static. Now if compiled by gcc it will be ignored and the compiler will  decide if and how to implement this function. Anyway even if there is no inline keyword the compiler (and the linker if link time optimisation is on) decides how to implement the function invocation - by inlining or traditional call.

If you want to make sure that the function will be inlined or not - you should use proper compiler attributes or pragmas.

where to place and how to declare inline functions depends on compiler, optimisation, link time optimisation and another factors.

Answering your question, if the function should be only visible in the scope of the particular .c file - yes it is - but without the static keyword it will be placed in the object file as well.

Body:
I am seeing this example where I have a crc32.c file which contains:

inline int32_t crc32_compute(int32_t *buffer, size_t size) {
   ...
}

In the header file I find:

extern inline int32_t crc32_compute(int32_t *buffer, size_t size);

To me the inline keyword has no effect because the function should be declared on the header file not on the C file. Is it that correct?


问:
Iterate through JSON using Python
I have the following JSON object and I wish to iterate through it:

```<code> {
    "odata.metadata": "https://aaa/_api/$metadata#TimesheetActualData",
    "value": [{
        "PROJ_UID": "39bf6bca-8939-4df6-aa81-8a6c3b23c979",
        "TASK_UID": "48dae88e-59ec-e611-80d4-00155d002a1c",
        "ASSN_UID": "4ac8a599-59ec-e611-80d4-00155d002a1c",
        "RES_UID": "e4a6a30d-5da2-e611-80cd-00155d00b80f",
        "PERIOD_UID": "9a08cd04-7f1c-41f1-9a42-cf9b8b3479ea",
        "TS_UID": null,
        "PROJ_NAME": "001 - Module Training Project 1",
        "TASK_NAME": "Approve new or changed Services",
        "TASK_TREE": "> Sample AMS project schedule > Service Strategy > Service Portfolio Management > Approve new or changed Services",
        "TASK_TYPE": "Billable",
        "TASK_CLIENTID": 9,
        "START": "2017-03-05T00:00:00",
        "END": "2017-03-05T00:00:00",
        "PLANNED_WORK": "0.00",
        "PPM_ACTUAL": "0.00",
        "TS_ACTUAL": null,
        "COMMENT": null,
        "SYNC_FLAG": 0,
        "APPROVAL_FLAG": null,
        "CREATED_DATE": "2017-03-17T12:04:38.53",
        "MOD_DATE": "2017-06-09T01:01:42.177",
        "ToBeDeleted": 0,
        "Incident_No": null,
        "Sync_Mod_Date": "2017-06-08T19:31:40",
        "TASK_START_DATE": "2017-02-14T08:00:00",
        "TASK_FINISH_DATE": "2017-03-10T17:00:00",
        "NON_ACTUAL_TASK_FLAG": 0,
        "InvoiceMasterId": 0,
        "Invoice_Status": "0",
        "Billing_Hours": "0.00",
        "Billing_Hours_Flag": null,
        "Final_Amount": "0.00",
        "ProjectCode": null,
        "WORKDAY": 0
    }, {
        "PROJ_UID": "39bf6bca-8939-4df6-aa81-8a6c3b23c979",
        "TASK_UID": "48dae88e-59ec-e611-80d4-00155d002a1c",
        "ASSN_UID": "4ac8a599-59ec-e611-80d4-00155d002a1c",
        "RES_UID": "e4a6a30d-5da2-e611-80cd-00155d00b80f",
        "PERIOD_UID": "9a08cd04-7f1c-41f1-9a42-cf9b8b3479ea",
        "TS_UID": null,
        "PROJ_NAME": "001 - Module Training Project 1",
        "TASK_NAME": "Approve new or changed Services",
        "TASK_TREE": "> Sample AMS project schedule > Service Strategy > Service Portfolio Management > Approve new or changed Services",
        "TASK_TYPE": "Billable",
        "TASK_CLIENTID": 9,
        "START": "2017-03-06T00:00:00",
        "END": "2017-03-06T00:00:00",
        "PLANNED_WORK": "0.00",
        "PPM_ACTUAL": "0.00",
        "TS_ACTUAL": null,
        "COMMENT": null,
        "SYNC_FLAG": 0,
        "APPROVAL_FLAG": null,
        "CREATED_DATE": "2017-03-17T12:04:38.7",
        "MOD_DATE": "2017-06-09T01:01:42.177",
        "ToBeDeleted": 0,
        "Incident_No": null,
        "Sync_Mod_Date": "2017-06-08T19:31:40",
        "TASK_START_DATE": "2017-02-14T08:00:00",
        "TASK_FINISH_DATE": "2017-03-10T17:00:00",
        "NON_ACTUAL_TASK_FLAG": 0,
        "InvoiceMasterId": 0,
        "Invoice_Status": "0",
        "Billing_Hours": "0.00",
        "Billing_Hours_Flag": null,
        "Final_Amount": "0.00",
        "ProjectCode": null,
        "WORKDAY": 0
    }],
    "odata.nextLink": "https://aaaa/_api/TimesheetActualData?$skip=1000"
 }
</code>```

But somehow, the code is just not working:

```<code>header={'content-type': 'application/json'}
response=requests.get(url,headers=header)
jjj=json.dumps(str(response.content))
d=json.loads(jjj)
print(d['values'])
</code>```

答:
You don't have to explicitly pass response.content to the json module to parse it, since requests has a function to do this:

```<code>d = response.json()
</code>```

You can then iterate over its values:

```<code>for value in d['value']:
    ...
</code>```

Title: Iterate through JSON using Python

Body:
I have the following JSON object and I wish to iterate through it:

 {
    "odata.metadata": "https://aaa/_api/$metadata#TimesheetActualData",
    "value": [{
        "PROJ_UID": "39bf6bca-8939-4df6-aa81-8a6c3b23c979",
        "TASK_UID": "48dae88e-59ec-e611-80d4-00155d002a1c",
        "ASSN_UID": "4ac8a599-59ec-e611-80d4-00155d002a1c",
        "RES_UID": "e4a6a30d-5da2-e611-80cd-00155d00b80f",
        "PERIOD_UID": "9a08cd04-7f1c-41f1-9a42-cf9b8b3479ea",
        "TS_UID": null,
        "PROJ_NAME": "001 - Module Training Project 1",
        "TASK_NAME": "Approve new or changed Services",
        "TASK_TREE": "> Sample AMS project schedule > Service Strategy > Service Portfolio Management > Approve new or changed Services",
        "TASK_TYPE": "Billable",
        "TASK_CLIENTID": 9,
        "START": "2017-03-05T00:00:00",
        "END": "2017-03-05T00:00:00",
        "PLANNED_WORK": "0.00",
        "PPM_ACTUAL": "0.00",
        "TS_ACTUAL": null,
        "COMMENT": null,
        "SYNC_FLAG": 0,
        "APPROVAL_FLAG": null,
        "CREATED_DATE": "2017-03-17T12:04:38.53",
        "MOD_DATE": "2017-06-09T01:01:42.177",
        "ToBeDeleted": 0,
        "Incident_No": null,
        "Sync_Mod_Date": "2017-06-08T19:31:40",
        "TASK_START_DATE": "2017-02-14T08:00:00",
        "TASK_FINISH_DATE": "2017-03-10T17:00:00",
        "NON_ACTUAL_TASK_FLAG": 0,
        "InvoiceMasterId": 0,
        "Invoice_Status": "0",
        "Billing_Hours": "0.00",
        "Billing_Hours_Flag": null,
        "Final_Amount": "0.00",
        "ProjectCode": null,
        "WORKDAY": 0
    }, {
        "PROJ_UID": "39bf6bca-8939-4df6-aa81-8a6c3b23c979",
        "TASK_UID": "48dae88e-59ec-e611-80d4-00155d002a1c",
        "ASSN_UID": "4ac8a599-59ec-e611-80d4-00155d002a1c",
        "RES_UID": "e4a6a30d-5da2-e611-80cd-00155d00b80f",
        "PERIOD_UID": "9a08cd04-7f1c-41f1-9a42-cf9b8b3479ea",
        "TS_UID": null,
        "PROJ_NAME": "001 - Module Training Project 1",
        "TASK_NAME": "Approve new or changed Services",
        "TASK_TREE": "> Sample AMS project schedule > Service Strategy > Service Portfolio Management > Approve new or changed Services",
        "TASK_TYPE": "Billable",
        "TASK_CLIENTID": 9,
        "START": "2017-03-06T00:00:00",
        "END": "2017-03-06T00:00:00",
        "PLANNED_WORK": "0.00",
        "PPM_ACTUAL": "0.00",
        "TS_ACTUAL": null,
        "COMMENT": null,
        "SYNC_FLAG": 0,
        "APPROVAL_FLAG": null,
        "CREATED_DATE": "2017-03-17T12:04:38.7",
        "MOD_DATE": "2017-06-09T01:01:42.177",
        "ToBeDeleted": 0,
        "Incident_No": null,
        "Sync_Mod_Date": "2017-06-08T19:31:40",
        "TASK_START_DATE": "2017-02-14T08:00:00",
        "TASK_FINISH_DATE": "2017-03-10T17:00:00",
        "NON_ACTUAL_TASK_FLAG": 0,
        "InvoiceMasterId": 0,
        "Invoice_Status": "0",
        "Billing_Hours": "0.00",
        "Billing_Hours_Flag": null,
        "Final_Amount": "0.00",
        "ProjectCode": null,
        "WORKDAY": 0
    }],
    "odata.nextLink": "https://aaaa/_api/TimesheetActualData?$skip=1000"
 }

But somehow, the code is just not working:

header={'content-type': 'application/json'}
response=requests.get(url,headers=header)
jjj=json.dumps(str(response.content))
d=json.loads(jjj)
print(d['values'])

Body:
You don't have to explicitly pass response.content to the json module to parse it, since requests has a function to do this:

d = response.json()

You can then iterate over its values:

for value in d['value']:
    ...


问:
Hardware encoding with nanopi2 fire under linux
I am trying to encode raw frames with nanoPi 2 fire board computer.
I have founded api for it:
https://github.com/friendlyarm/nexell_linux_platform

Accroding to nx_video_api.h I need to open device, init it, alocate memory for input and output frame, and then push encoding with "NX_VidEncJpegRunFrame".

However that is the problem, can anyone help me with alocating memory for this structure "NX_VID_ENC_IN"?
How to put raw frame there? What pixel format it should be?
How to read data back from "NX_VID_ENC_OUT"?

I cannot find any sample or tutorial for hw encoding on that chip, so any example would be greatly appriciated.

答:
From the Github project in the question theser is a sample that show how to use NX_VidEncJpegRunFrame (in NXJpegHWEnc.cpp).

You can allocate the structure NX_VID_ENC_OUT on the stack, the output buffer will be allocated by NX_VidEncJpegRunFrame :

```<code>NX_VID_ENC_OUT encOut;
NX_VidEncJpegRunFrame(hEnc, &memInfo, &encOut);
</code>```

Next you can access to buffer encOut.outBuf of encOut.bufSize.

Body:
From the Github project in the question theser is a sample that show how to use NX_VidEncJpegRunFrame (in NXJpegHWEnc.cpp).

You can allocate the structure NX_VID_ENC_OUT on the stack, the output buffer will be allocated by NX_VidEncJpegRunFrame :

NX_VID_ENC_OUT encOut;
NX_VidEncJpegRunFrame(hEnc, &memInfo, &encOut);

Next you can access to buffer encOut.outBuf of encOut.bufSize.


问:
Javascript remove elements by class name
How we can remove the all div by same name of class.</p>

```<code> <input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]">
</code>```

答:
With jQuery:

```<code>$(".form-control").remove();
</code>```

Without jQuery:

```<code>var elems = document.querySelectorAll(".form-control");
elems.forEach(function(element) {
  element.parentNode.removeChild(element);
});
</code>```

Body:
How we can remove the all div by same name of class.

 <input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]"><input class="form-control" type="text" name="option[]">

Body:
With jQuery:

$(".form-control").remove();

Without jQuery:

var elems = document.querySelectorAll(".form-control");
elems.forEach(function(element) {
  element.parentNode.removeChild(element);
});


问:
Disable hover on specific ceils
I would like to avoid the hover on the 4 middle ceils in my table when the user make the hover on the entire line.

Initial state:

Hover state:

Expected result: Keep the 4 middle ceils in the initial state when hover.

HTML :

```<code><tr class="gradeX odd" role="row">
   <td class="" tabindex="0"> CD-5-CZ-TOS-110.21 </td>
   <td class=""> OS6450-P24 </td>
   <td class="supportedClass"> Supported </td>
   <td class="supportedClass"> Supported </td>
   <td class="notSupportedClass"> Not supported </td>
   <td class="mediumClass"> Within 90 days of end of support </td>
   <td class=""> 2c:fa:a2:2e:15:c4 </td>
   <td class=""> T5184190 </td>
   <td class=""> 6.7.2.49.R01 </td>
</tr>
</code>```

CSS (bootstrap)

```<code>.table-hover>tbody>tr:hover, .table-hover>tbody>tr:hover>td {
    background: #f3f4f6!important;
}

.table-hover>tbody>tr:hover, .table>tbody>tr.active>td, .table>tbody>tr.active>th, .table>tbody>tr>td.active, .table>tbody>tr>th.active, .table>tfoot>tr.active>td, .table>tfoot>tr.active>th, .table>tfoot>tr>td.active, .table>tfoot>tr>th.active, .table>thead>tr.active>td, .table>thead>tr.active>th, .table>thead>tr>td.active, .table>thead>tr>th.active {
    background-color: #eef1f5;
}
</code>```

答:
Using class is not a good idea until you are not using loop, so I have made a solution that will select only first and last three element as you want.

.table-hover > tbody > tr:hover > td:nth-child(-n+5):not(:nth-child(n+2)), .table-hover > tbody > tr:hover > td:nth-child(n+6) {
    background: red !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-striped table-hover">
 <thead>
  <tr>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
  </tr>
 </thead>
 <tbody>
   <tr>
    <td>Column</td>
    <td class="bg-danger">Column</td>
    <td class="bg-success">Column</td>
    <td class="bg-info">Column</td>
    <td class="bg-warning">Column</td>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
   </tr>
   <tr>
    <td>Column</td>
    <td class="bg-danger">Column</td>
    <td class="bg-success">Column</td>
    <td class="bg-info">Column</td>
    <td class="bg-warning">Column</td>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
   </tr>
   <tr>
    <td>Column</td>
    <td class="bg-danger">Column</td>
    <td class="bg-success">Column</td>
    <td class="bg-info">Column</td>
    <td class="bg-warning">Column</td>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
   </tr>
 </tbody>
</table></code>```

Title: Disable hover on specific ceils

Body:
I would like to avoid the hover on the 4 middle ceils in my table when the user make the hover on the entire line.

Initial state:

Hover state:

Expected result: Keep the 4 middle ceils in the initial state when hover.

HTML :

    CD-5-CZ-TOS-110.21
    OS6450-P24
    Supported
    Supported
    Not supported
    Within 90 days of end of support
    2c:fa:a2:2e:15:c4
    T5184190
    6.7.2.49.R01

CSS (bootstrap)

.table-hover>tbody>tr:hover, .table-hover>tbody>tr:hover>td {
    background: #f3f4f6!important;
}

.table-hover>tbody>tr:hover, .table>tbody>tr.active>td, .table>tbody>tr.active>th, .table>tbody>tr>td.active, .table>tbody>tr>th.active, .table>tfoot>tr.active>td, .table>tfoot>tr.active>th, .table>tfoot>tr>td.active, .table>tfoot>tr>th.active, .table>thead>tr.active>td, .table>thead>tr.active>th, .table>thead>tr>td.active, .table>thead>tr>th.active {
    background-color: #eef1f5;
}

Body:
Using class is not a good idea until you are not using loop, so I have made a solution that will select only first and last three element as you want.

.table-hover > tbody > tr:hover > td:nth-child(-n+5):not(:nth-child(n+2)), .table-hover > tbody > tr:hover > td:nth-child(n+6) {
    background: red !important;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table class="table table-striped table-hover">
 <thead>
  <tr>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
   <th>Column</th>
  </tr>
 </thead>
 <tbody>
   <tr>
    <td>Column</td>
    <td class="bg-danger">Column</td>
    <td class="bg-success">Column</td>
    <td class="bg-info">Column</td>
    <td class="bg-warning">Column</td>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
   </tr>
   <tr>
    <td>Column</td>
    <td class="bg-danger">Column</td>
    <td class="bg-success">Column</td>
    <td class="bg-info">Column</td>
    <td class="bg-warning">Column</td>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
   </tr>
   <tr>
    <td>Column</td>
    <td class="bg-danger">Column</td>
    <td class="bg-success">Column</td>
    <td class="bg-info">Column</td>
    <td class="bg-warning">Column</td>
    <td>Column</td>
    <td>Column</td>
    <td>Column</td>
   </tr>
 </tbody>
</table>


问:
React Native equivalent to mousedown
If I'm making a website, I can use a mousedown event to trigger something when the mouse button is pressed (and not yet released).

In React Native, I've got a TouchableHighlight and can register an onPress callback, but this only triggers when I release my finger from the button.

Is there a way to trigger as soon as a finger touches a button, rather than only when the finger is released?

答:
Solved shortly afterwards! The onResponderStart prop is what I needed. This isn't actually documented in the gesture responder system docs, but it seems  to work for me!

```<code><View onStartShouldSetResponder={() => true}
      onResponderStart={calledWhenTheTouchStarts}>

    <Text>Press Me!</Text>

</View>
</code>```

Title: React Native equivalent to mousedown

Body:
Solved shortly afterwards! The onResponderStart prop is what I needed. This isn't actually documented in the gesture responder system docs, but it seems  to work for me!

<View onStartShouldSetResponder={() => true}
      onResponderStart={calledWhenTheTouchStarts}>

    <Text>Press Me!</Text>

</View>


问:
Not Replace @TFYID Variable with value in SQL Query
```<code>set @TFYID=7
print @TFYID

set @SQL =N'select @ETotal=sum(ExemptionProduce)
            from   tbl_Income_Exemption
            where  EmployeeID='''+@EmpID+'''  and (TDSSettingsDetailID) in
                  ('+@ConcatString+''') and FinancialYearID='+@TFYID+''

exec sp_executesql @SQL
</code>```

output :

```<code>7
Msg 245, Level 16, State 1, Line 73
Conversion failed when converting the nvarchar value '
select @ETotal=sum(ExemptionProduce)
from   tbl_Income_Exemption
where  EmployeeID='00402060'  and (TDSSettingsDetailID) in
       ('24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36')
       and FinancialYearID=' to data type int.
</code>```

This Query not showing me properly output.
it's give me some error.
Please Help me.

答:
The way you have written the query you need to convert the value to a string:

```<code>set @SQL =N'select @ETotal=sum(ExemptionProduce)
            from   tbl_Income_Exemption
            where  EmployeeID='''+cast(@EmpID as varchar(255))+'''  and (TDSSettingsDetailID) in
                  ('+@ConcatString+''') and FinancialYearID='+cast(@TFYID as varchar(255))+''

exec sp_executesql @SQL
</code>```

However, the correct way to write the query is to use parameters -- at least where you can:

```<code>declare @ETotal decimal(18, 4);  -- or whatever

set @SQL = N'
select @ETotal = sum(ExemptionProduce)
from tbl_Income_Exemption
where EmployeeID = @EmpID and
      TDSSettingsDetailID in (' + @ConcatString + ') and
      FinancialYearID = @TFYID';

exec sp_executesql @SQL,
     N'@ETotal decimal(18, 4) output, @EmpId int, @TFYID int',
     @ETotal = @ETotal output, @EmpId = @EmpId, @TFYID = @TFYID;
</code>```

You cannot pass the in list as a single parameter, so munging the query string is a viable option.

Whether this works or not depends on the values and types of things that you haven't explained in the question.  But you should be able to get the right idea.

Body:
set @TFYID=7
print @TFYID

set @SQL =N'select @ETotal=sum(ExemptionProduce)
            from   tbl_Income_Exemption
            where  EmployeeID='''+@EmpID+'''  and (TDSSettingsDetailID) in
                  ('+@ConcatString+''') and FinancialYearID='+@TFYID+''

exec sp_executesql @SQL

output :

7
Msg 245, Level 16, State 1, Line 73
Conversion failed when converting the nvarchar value '
select @ETotal=sum(ExemptionProduce)
from   tbl_Income_Exemption
where  EmployeeID='00402060'  and (TDSSettingsDetailID) in
       ('24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36')
       and FinancialYearID=' to data type int.

This Query not showing me properly output.
it's give me some error.
Please Help me.

Body:
The way you have written the query you need to convert the value to a string:

set @SQL =N'select @ETotal=sum(ExemptionProduce)
            from   tbl_Income_Exemption
            where  EmployeeID='''+cast(@EmpID as varchar(255))+'''  and (TDSSettingsDetailID) in
                  ('+@ConcatString+''') and FinancialYearID='+cast(@TFYID as varchar(255))+''

exec sp_executesql @SQL

However, the correct way to write the query is to use parameters -- at least where you can:

declare @ETotal decimal(18, 4);  -- or whatever

set @SQL = N'
select @ETotal = sum(ExemptionProduce)
from tbl_Income_Exemption
where EmployeeID = @EmpID and
      TDSSettingsDetailID in (' + @ConcatString + ') and
      FinancialYearID = @TFYID';

exec sp_executesql @SQL,
     N'@ETotal decimal(18, 4) output, @EmpId int, @TFYID int',
     @ETotal = @ETotal output, @EmpId = @EmpId, @TFYID = @TFYID;

You cannot pass the in list as a single parameter, so munging the query string is a viable option.

Whether this works or not depends on the values and types of things that you haven't explained in the question.  But you should be able to get the right idea.


答:
change

```<code>jjj=json.dumps(str(response.content))
d=json.loads(jjj)
</code>```

To

```<code>d = json.loads(response.text)
</code>```

What is the difference between 'content' and 'text'

r.text is the content of the response in unicode, and r.content is
  thecontent of the response in bytes

Title: Iterate through JSON using Python

Body:
change

jjj=json.dumps(str(response.content))
d=json.loads(jjj)

To

d = json.loads(response.text)

What is the difference between 'content' and 'text'

r.text is the content of the response in unicode, and r.content is
  thecontent of the response in bytes


问:
Is it bad practice to dynamically set/change event handlers?
I am trying to replace confirm() boxes with bootstrap modals for save/delete operations in a page.There is a button(call it action-button) for each of these operation which then triggers the respective modal. On clicking the confirm button on the modal,the respective function is triggered.

Instead of writing modals for each of these operations,I was thinking if I could use just one confirm modal and change the event handler when the "action-button" is clicked.
Like this:

$("#confirm-button").attr('onclick',save_all());

when save_all button is clicked.
Is it bad practice?And what are some alternatives to this? Thanks!

答:
It will not even do what you intend, because you call save_all at the moment you set the attribute, and it will be the function's return value that is stored in the onclick attribute, converted to string if it is not yet a string. This most probably is not what you intended to do.

Even if the attribute value would be correct, it is not the best practice, because:

That attribute value needs to be evaluated/parsed, which means you can get late syntax errors

It replaces the previous value of the onclick attribute, which might be an undesired effect (although I understand in your case that is what you want)

Instead bind event handlers the jQuery way and make sure you don't call the function, but pass its reference:

```<code>$("#confirm-button").on('click', save_all);
</code>```

If the purpose is to replace any previous click handler, then chain in an off call:

```<code>$("#confirm-button").off('click').on('click', save_all);
</code>```

Body:
It will not even do what you intend, because you call save_all at the moment you set the attribute, and it will be the function's return value that is stored in the onclick attribute, converted to string if it is not yet a string. This most probably is not what you intended to do.

Even if the attribute value would be correct, it is not the best practice, because:

That attribute value needs to be evaluated/parsed, which means you can get late syntax errors

It replaces the previous value of the onclick attribute, which might be an undesired effect (although I understand in your case that is what you want)

Instead bind event handlers the jQuery way and make sure you don't call the function, but pass its reference:

$("#confirm-button").on('click', save_all);

If the purpose is to replace any previous click handler, then chain in an off call:

$("#confirm-button").off('click').on('click', save_all);


问:
C# Elegant way to handle checking for an item in a collection
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

```<code>TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }
</code>```

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

答:
May be this</p>

```<code>termStore.Any() && termStore.Groups.Any() && termStore.Groups[groupName] == null
</code>```

Body:
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

Body:
May be this

termStore.Any() && termStore.Groups.Any() && termStore.Groups[groupName] == null


问:
Error using sub2ind (line 52) Out of range subscript Matlab
I used the same code for two  different input matrices,
In both cases i will call it "the input matrix A"

The first case is a 7000X4

The second case is a 29500X12

I need to split a selected column in windows
and then for each window
i need to calculate the std and store the value inside a std_vals  matrix

I took care to change the value of my input variables.

In the first case my goal was to analyze the 4th column,
in the second case my goal was to analyze the 12th column

In the first case the code worked

In the second case the code returned me an error message

I tried to analyze all the steps in the code, but i dind't find the error.

Could you please help me to understand better?

```<code>column_length=size(A,1);
Amod= mod(column_length,100);
if Amod~=0
    A=A(1:(size(A,1)-Amod),:);
    end
newlenght=size(A);

%selected column vector to analyze
columnselected=4;
%window dimension
window_size=200;

%overlap between two windows
overlap=0;

%increment needed
step=window_size - overlap;

%std threshold
soglia=2;
std_vals= NaN(size(A,1),1);
devstd=std(A(:,4));

stdInds=bsxfun(@plus,1:step:(size(A,1)-overlap),(0:(window_size-1)).');

%In the first case size(stdInds)=200X35
%In the second case size(stdInds)=200X148
%In the first case size(repmat(columnselected,size(stdInds))=   200X35
%In the second case size(repmat(columnselected,size(stdInds))=  200X148
%In the first case size(A)=7000X4
%In the second case size(A)=29500X12
  std_vals=std(A(sub2ind(size(A),stdInds,repmat(columnselected,size(stdInds)))));

highStdWindows=find(std_vals>soglia);
</code>```

I am self taught. To understand better my error first i rewrite on a piece of paper the code, then i analyzed every step, and studied the output. I took me more than 4 hours.

I also tried to put in the second case a 7000X12 vector, but the code returned me the same error.

I think my method is not very efficent.

答:
The error you're getting from sub2ind isn't caused by the size of the arguments, but rather by their values - so the best way to debug it would be to look at those arguments e.g. by plotting them.

Here's a theory about what's happening, though it doesn't explain everything you've reported (it suggests the 7000x12 array should have worked):

I think the problem here is that the first part of your code crops the input so its height is a multiple of 100.  However your window size is 200 and these numbers should have been the same (for 0 overlap).  This is because you calculate the start points of your windows with 1:step:(size(A,1)-overlap) = 1:200:size(A,1) which will produce a final window which does not fit within A unless size(A,1) is a multiple of 200.

Considering the array sizes you've tried:

7000x4: 7000 is a multiple of 200 so this works

29500x12: 29500 is not a multiple of 200 so this fails (the final element of 1:200:29500 is 29401, so the last window is 29401:29600)

102047x12: 102047 gets truncated to 102000 which is a multiple of 200 so this works

7000x12: this should work in the same way as 7000x4 - which is inconsistent with what you've seen!

Body:
I used the same code for two  different input matrices,
In both cases i will call it "the input matrix A"

The first case is a 7000X4

The second case is a 29500X12

I need to split a selected column in windows
and then for each window
i need to calculate the std and store the value inside a std_vals  matrix

I took care to change the value of my input variables.

In the first case my goal was to analyze the 4th column,
in the second case my goal was to analyze the 12th column

In the first case the code worked

In the second case the code returned me an error message

I tried to analyze all the steps in the code, but i dind't find the error.

Could you please help me to understand better?

column_length=size(A,1);
Amod= mod(column_length,100);
if Amod~=0
    A=A(1:(size(A,1)-Amod),:);
    end
newlenght=size(A);

%selected column vector to analyze
columnselected=4;
%window dimension
window_size=200;

%overlap between two windows
overlap=0;

%increment needed
step=window_size - overlap;

%std threshold
soglia=2;
std_vals= NaN(size(A,1),1);
devstd=std(A(:,4));

stdInds=bsxfun(@plus,1:step:(size(A,1)-overlap),(0:(window_size-1)).');

%In the first case size(stdInds)=200X35
%In the second case size(stdInds)=200X148
%In the first case size(repmat(columnselected,size(stdInds))=   200X35
%In the second case size(repmat(columnselected,size(stdInds))=  200X148
%In the first case size(A)=7000X4
%In the second case size(A)=29500X12
  std_vals=std(A(sub2ind(size(A),stdInds,repmat(columnselected,size(stdInds)))));

highStdWindows=find(std_vals>soglia);

I am self taught. To understand better my error first i rewrite on a piece of paper the code, then i analyzed every step, and studied the output. I took me more than 4 hours.

I also tried to put in the second case a 7000X12 vector, but the code returned me the same error.

I think my method is not very efficent.


问:
Laravel 5 sending information using get request
In my project I use www.example.com/test?prevUrl=test/3/home this is working fine in development when inside my controller I do $request->prevUrl but doesn't work in production(returns null). can someone help?

edit= "The query_string is not being properly set i-e (?prevUrl=something ) and for that reason my paginator is also not working properly

答:
You can do like it...

In web.php:

```<code>Route::get('test','YourController@yourMethod');
</code>```

In Controller:

```<code>public function yourMethod(){

//or return $request->query('prevUrl');
return $request->input('prevUrl');

}
</code>```

Body:
You can do like it...

In web.php:

Route::get('test','YourController@yourMethod');

In Controller:

public function yourMethod(){

//or return $request->query('prevUrl');
return $request->input('prevUrl');

}


问:
How to stop AWS SES Spamming my gmail email?
Gmail gets flooded with spam emails from AWS Ses

After my spam email folder gets full the gmail is not getting any more emails. How can I report to AWS Ses not to send me an email from a specific AWS Ses Account.

Here is the details. I have contacted the company who is sending the emails. They are unable to solve the issue. ( In 3 years cant cope with change ).

I was once a permitted receiver but not anymore. Help would be appreciated.

Delivered-To: rifaterdemsahin@gmail.com Received: by 10.100.151.140
  with SMTP id q12csp736984pja;
          Thu, 22 Jun 2017 18:55:26 -0700 (PDT) X-Received: by 10.200.47.87 with SMTP id k23mr6662116qta.11.1498182926606;
          Thu, 22 Jun 2017 18:55:26 -0700 (PDT) ARC-Seal: i=1; a=rsa-sha256; t=1498182926; cv=none;
          d=google.com; s=arc-20160816;
          b=VjPlf2DSOO/X+jFewPovx0GPtS81NriE988G1yhFs0sWUAULrnp31pIDjiI3v/MC2h
           VOJDD6IkKpp+gsU4gYLo8BRoS71ZiHtB6O7Yk1z5Nc7QKxk+FjBuGK75Y8qM3dObxCKU
           FpZ3vwZrmwHbL8etRznU/DwfcN5f60GP45eINzKe7QYS+HOquiISKfFI6Kjac5/GvHqu
           fRL2zdFHu5E2aIXGUMUK4EdVsFjMQUsJUqBJC0OSoqLesyLdoyqV4oTAunH8BwYKWEY4
           /JTNP2zR6+6wucgfEVVPUQ5W6ocKVWPlJnHDw+vP1y6JkKMNaNj9mYl0LORMKHU71ptN
           f8Ig== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
          h=feedback-id:date:message-id:content-transfer-encoding:mime-version
           :subject:to:from:dkim-signature:arc-authentication-results;
          bh=Y7pVjQ5emAE4pdcubLwi7473vY3OWUVV5NusExrVNc8=;
          b=DlgSuorHXVeVtWhKM/csFcSeADLzJCLSuzCwZEsHVT7XLtmwSQERCwlIDHyabl8Ffa
           NNXx8CCYYfrAu0mbg3vGnAvG8SmusEwfBe0cAaa7D1bGf2fM/hGJzsQX21e3rbyQzvnu
           GSTZjwpW48sFkWzN863wLai5Z2Ne+eR/7lyzfEO/mIIJL0f3uvVmV32kFYMWHxYz0x8/
           r8GpiLqfD6nxMqvpxn04a/KYgo97/TxyB9AFaKEN08ih1d7+qLE5isq+BJI2NjCJLHnW
           vqlM1ideeygoN20cgTaz6ZQpYOQAsO0SIZQkoOtkT/6eb0DNCEa1RO45AmMgC9ZJ4rkc
           PYKQ== ARC-Authentication-Results: i=1; mx.google.com;
         dkim=pass header.i=@amazonses.com header.b=WNeDQXRK;
         spf=pass (google.com: domain of 0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  designates 54.240.9.109 as permitted sender)
  smtp.mailfrom=0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  Return-Path:
  <0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com>
  Received: from a9-109.smtp-out.amazonses.com
  (a9-109.smtp-out.amazonses.com. [54.240.9.109])
          by mx.google.com with ESMTPS id h186si1190862qkc.200.2017.06.22.18.55.26
          for
          (version=TLS1 cipher=ECDHE-RSA-AES128-SHA bits=128/128);
          Thu, 22 Jun 2017 18:55:26 -0700 (PDT) Received-SPF: pass (google.com: domain of
  0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  designates 54.240.9.109 as permitted sender) client-ip=54.240.9.109;
  Authentication-Results: mx.google.com;
         dkim=pass header.i=@amazonses.com header.b=WNeDQXRK;
         spf=pass (google.com: domain of 0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  designates 54.240.9.109 as permitted sender)
  smtp.mailfrom=0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@amazonses.com
  DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/simple;
  s=224i4yxa5dv7c2xz3womw6peuasteono; d=amazonses.com; t=1498182926;
  h=From:To:Subject:MIME-Version:Content-Type:Content-Transfer-Encoding:Message-ID:Date:Feedback-ID;
  bh=VCZKg8hFUb63lOKDitSw+wHccKQ7iJdOqT+3v5T9kMM=;
  b=WNeDQXRKVjREfsyiCHuwazQD7AXWRfZc3UcrwH1AghtaCnavxJ6CBSLTUsIqc5GF
  m6/uRCDItr6crWjplYgl14Dq2mbGHMFtB+vZHh0PPNmO4n3+/8PevleQbEYInRWmlec
  ZbFX57QHhrNXtEyUc4qaM3ZtjpcwjaPzOXe2liB8= From: No-Reply
   To: rifaterdemsahin@gmail.com Subject:
  Performance Warning(3x) IP: 192.168.30.40 Method:
  Broadage.Common.Tools.Email MIME-Version: 1.0 Content-Type: text/html;
  charset=UTF-8 Content-Transfer-Encoding: quoted-printable Message-ID:
  <0100015cd2a93eb9-85164c9c-6cfb-46ec-a985-02909a4b6b0c-000000@email.amazonses.com>
  Date: Fri, 23 Jun 2017 01:55:26 +0000 X-SES-Outgoing:
  2017.06.23-54.240.9.109 Feedback-ID: 1.us-east-1.SIJlVA2xTbAVdBXctlUaxBDeEU1mquOgueuof7Nldbc=:AmazonSES

Performans Uyar=C4=B1s=C4=B1
Mak= ine Ip =3D>  192.168.30.40
Uygulama Ad=C4=B1 =3D>
Method Name =3D>  Broadage.Common= .Tools.Email
=C4=B0stenilen Performans S=C3=BCresi =3D>
  250 ms elapsed time

Harcanan S=C3=BCre=
  =3D> 786.708 ms elapsed time

答:
I think your best option is to automatically delete the emails in the gmail, through setting up a filter. I think this page explains how to setup the filter: https://www.businessinsider.com.au/automatically-delete-unwanted-gmail-2014-1

I don't think you can interact with their setup of AWS SES. If you were able to it would be a security vulnerability of SES.

It could be possible to setup a gmail custom script that could delete the emails, but in affect it would be doing the same thing as the filter. Except the filter is easier.

I think the business sending unwanted information is probably against an anti-spam act. So what they are doing is probably illegal, or at least probably negligent.

I hope that helps.


问:
How to change a table name using an SQL query?
How can I in change the table name using a query statement?

I used the following syntax but I couldn't find the rename keyword in SQL server 2005.

```<code>Alter table Stu_Table rename to Stu_Table_10
</code>```

答:
rename table name :

```<code>RENAME TABLE old_tableName TO new_tableName;
</code>```

for example:

```<code>RENAME TABLE company_name TO company_master;
</code>```

OwnerDisplayName: siva

Body:
How can I in change the table name using a query statement?

I used the following syntax but I couldn't find the rename keyword in SQL server 2005.

Alter table Stu_Table rename to Stu_Table_10

Body:
rename table name :

RENAME TABLE old_tableName TO new_tableName;

for example:

RENAME TABLE company_name TO company_master;


问:
Stop LastPass filling out a form
Is there a way to prevent the LastPass browser extension from filling out a HTML-based form with an input field with the name "username"?

This is an hidden field, so I don't want any software to use this field for their purposes:

```<code><input type="text" name="username" id="checkusername" maxlength="9" value="1999" class="longinput" style="display:none">
</code>```

The solution should not be like "rename the input field".

答:
Adding

```<code>data-lpignore="true"
</code>```

to an input field disabled the grey LastPass [...] box for me.

Sourced from LastPass.com

ContentLicense: CC BY-SA 4.0

Title: Stop LastPass filling out a form

Body:
Is there a way to prevent the LastPass browser extension from filling out a HTML-based form with an input field with the name "username"?

This is an hidden field, so I don't want any software to use this field for their purposes:

<input type="text" name="username" id="checkusername" maxlength="9" value="1999" class="longinput" style="display:none">

The solution should not be like "rename the input field".

Body:
Adding

data-lpignore="true"

to an input field disabled the grey LastPass [...] box for me.

Sourced from LastPass.com


问:
Fatal error: Call to undefined function oci_connect() in wamp server 3.0 with oracle 10g running on windows 10
I have a 64 bit Windows 10 PC, on which i want to install wamp server which is to be connected with oracle 10g. I have installed oracle 10g, oracle client for 10g. Also, i have downloaded the php_oci8.dll and copied it to ext/ directory of wamp. I also made the changes in the php.ini file i.e. added extension=php_oci8.dll. I have tried installing wamp server3.0 32 bit as well as 64 bit, yet i am not able to connect my php application with my database as it keeps on giving error message : "Fatal error: Call to undefined function oci_connect() in line number 23". But i am able to connect to my database with sqldeveloper.

Any help....

答: I was able to resolve the issue by installing wamp 2.5 for 32 bit on windows 10 machine. It works fine with oracle 10g</p>


问:
How can I show a div, then hide the other divs when a link is clicked?
I am right now trying to hide six divs while showing only one of the divs.  I've tried JavaScript and in jQuery, but nothing seems to work!  Click here to get to the website.

I would like to know if it has to do with my CSS, jQuery, or the HTML.  Or is there an easier way of doing this?

HTML:

```<code><div id="resourceLinks">
  <a href="#" name="resource" id="resource1">General Information</a><br />
  <a href="#" name="resource" id="resource2">Automatic 401(k)</a><br />
  <a href="#" name="resource" id="resource3">Consumer Fraud</a><br />
  <a href="#" name="resource" id="resource4">Direct Deposit</a><br />
  <a href="#" name="resource" id="resource5">Diversity</a><br />
  <a href="#" name="resource" id="resource6">Women</a><br />
  <a href="#" name="resource" id="resource7">Young Adults (20s - 40s)</a>
  </div>

<div id="resource1></div>
<div id="resource2></div>
<div id="resource3></div>
<div id="resource4></div>
<div id="resource5></div>
<div id="resource6></div>
<div id="resource7></div>
</code>```

CSS:

```<code>#resource1, #resource2, #resource3, #resource4, #resource5, #resource6, #resource7 {
    position: absolute;
    margin-left: 400px;
    margin-top: -10px;
    width: 300px;
    padding-bottom: 120px;
}

#resourceLinks {
    position: fixed;
    margin-left: -450px;
    z-index: 3;
    margin-top: 180px;
    font-size: 16px;
}
</code>```

jQuery:

```<code>$(document).ready(function(){

  $('#resourceLinks a').click(function (selected) {

    var getName = $(this).attr("id");
    var projectImages = $(this).attr("name");

    $(function() {
      $(".resource").hide().removeClass("current");
      $("#" + projectImages ).show("normal").addClass("current");
    });
  });
});
</code>```

答:
How about something like this one</p>

```<code><div id="resourceLinks">
    <a href="#" name="resource" id="resource1">General Information</a><br />
    <a href="#" name="resource" id="resource2">Automatic 401(k)</a><br />
    <a href="#" name="resource" id="resource3">Consumer Fraud</a><br />
    <a href="#" name="resource" id="resource4">Direct Deposit</a><br />
    <a href="#" name="resource" id="resource5">Diversity</a><br />
    <a href="#" name="resource" id="resource6">Women</a><br />
    <a href="#" name="resource" id="resource7">Young Adults (20s - 40s)</a>
</div>

<div class="resource" id="resource1_info"></div>
<div class="resource" id="resource2_info"></div>
<div class="resource" id="resource3_info"></div>
<div class="resource" id="resource4_info"></div>
<div class="resource" id="resource5_info"></div>
<div class="resource" id="resource6_info"></div>
<div class="resource" id="resource7_info"></div>

$(document).ready(function(){
     $("div.resource:gt(0)").hide();  // to hide all div except for the first one
     $('#resourceLinks a').click(function(selected) {
        var getID = $(this).attr("id");
        var projectImages = $(this).attr("name");

        $("div.resource").hide();
        $("#" + getID + "_info" ).show();
    });
});
</code>```

Body:
I am right now trying to hide six divs while showing only one of the divs.  I've tried JavaScript and in jQuery, but nothing seems to work!  Click here to get to the website.

I would like to know if it has to do with my CSS, jQuery, or the HTML.  Or is there an easier way of doing this?

HTML:

  General Information

  Automatic 401(k)

  Consumer Fraud

  Direct Deposit

  Diversity

  Women

  Young Adults (20s - 40s)

CSS:

#resource1, #resource2, #resource3, #resource4, #resource5, #resource6, #resource7 {
    position: absolute;
    margin-left: 400px;
    margin-top: -10px;
    width: 300px;
    padding-bottom: 120px;
}

#resourceLinks {
    position: fixed;
    margin-left: -450px;
    z-index: 3;
    margin-top: 180px;
    font-size: 16px;
}

jQuery:

$(document).ready(function(){

  $('#resourceLinks a').click(function (selected) {

    var getName = $(this).attr("id");
    var projectImages = $(this).attr("name");

    $(function() {
      $(".resource").hide().removeClass("current");
      $("#" + projectImages ).show("normal").addClass("current");
    });
  });
});

Body:
How about something like this one

<div id="resourceLinks">
    <a href="#" name="resource" id="resource1">General&nbsp;Information</a><br />
    <a href="#" name="resource" id="resource2">Automatic&nbsp;401(k)</a><br />
    <a href="#" name="resource" id="resource3">Consumer&nbsp;Fraud</a><br />
    <a href="#" name="resource" id="resource4">Direct&nbsp;Deposit</a><br />
    <a href="#" name="resource" id="resource5">Diversity</a><br />
    <a href="#" name="resource" id="resource6">Women</a><br />
    <a href="#" name="resource" id="resource7">Young&nbsp;Adults&nbsp;(20s&nbsp;-&nbsp;40s)</a>
</div>

<div class="resource" id="resource1_info"></div>
<div class="resource" id="resource2_info"></div>
<div class="resource" id="resource3_info"></div>
<div class="resource" id="resource4_info"></div>
<div class="resource" id="resource5_info"></div>
<div class="resource" id="resource6_info"></div>
<div class="resource" id="resource7_info"></div>

$(document).ready(function(){
     $("div.resource:gt(0)").hide();  // to hide all div except for the first one
     $('#resourceLinks a').click(function(selected) {
        var getID = $(this).attr("id");
        var projectImages = $(this).attr("name");

        $("div.resource").hide();
        $("#" + getID + "_info" ).show();
    });
});


问:
How to build a framework for all platforms in single Xcode project?
Previously to build a framework for particular platform(macOS, iOS), I used to maintain different projects in Xcode and build separately.

My code mostly depends on sqlite3.h and a wrapper class written in Swift.

Is there a way to maintain all the frameworks under one xcode project?

I searched but I didn't get any tutorials on the web.

Thank you.

答:
yes of course xcode can handle this for a long time. you simply create your framework project and then add targets for iOS, macOS, tvOS and watchOS.

the plus sign below the target pane allows you to add more target. or just duplicate your existing target and change sdk and platform settings.


问:
how to set variable using fetched array in php
I have a query that fetches values from a database and I'd like to store an instance of the value 'current' into a variable for reuse.

My fetch is currently:

```<code>function updateTable() {
if(isset($_POST['submit'])) {
global $connection;
$sql = "SELECT * FROM myTable";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "current: " . $row["current"];
    }
} else {
    echo "0 results";
}
}}
</code>```

As you can see I have been able to confirm the values are being fetched by echoing out the array. What I'd like to do now is to store the first instance of the array into a new variable called $total.

I have been able to separate the array and echo values using:

```<code>while ($row = mysqli_fetch_array($result)) {

    $value = $row ['current'];
    if($row['id'] == 2){
    echo $value;
    }
                }
</code>```

I had thought storing the value would be similar but I can't get it to work.

Any help appreciated.
Thanks
James

答:
```<code>if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

        echo "current: " . $row["current"];
    }
}
</code>```

instead of

```<code>if ($result->num_rows > 0) {
$i = 1;
    while($row = $result->fetch_assoc()) {
        $$current.$i = $row["current"];

    }
    echo $$current1;
    echo $$current2;
}
</code>```

Body:
I have a query that fetches values from a database and I'd like to store an instance of the value 'current' into a variable for reuse.

My fetch is currently:

function updateTable() {
if(isset($_POST['submit'])) {
global $connection;
$sql = "SELECT * FROM myTable";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "current: " . $row["current"];
    }
} else {
    echo "0 results";
}
}}

As you can see I have been able to confirm the values are being fetched by echoing out the array. What I'd like to do now is to store the first instance of the array into a new variable called $total.

I have been able to separate the array and echo values using:

while ($row = mysqli_fetch_array($result)) {

    $value = $row ['current'];
    if($row['id'] == 2){
    echo $value;
    }
                }

I had thought storing the value would be similar but I can't get it to work.

Any help appreciated.
Thanks
James

Body:
if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {

        echo "current: " . $row["current"];
    }
}

instead of

if ($result->num_rows > 0) {
$i = 1;
    while($row = $result->fetch_assoc()) {
        $$current.$i = $row["current"];

    }
    echo $$current1;
    echo $$current2;
}


问:
ng-model value does not get updated on ngModelCtrl.$commitViewValue();
I have a directive where I have a template and I am trying to update the ng-model when a user clicks enter. I am able to catch the event and trying to update the value. I have a watcher on the element in a controller but the watcher function never gets triggered after commitViewValue

(function() {
    'use strict';

    angular.module('aa')
        .directive('ss', [
            function() {

                return {
                    restrict: 'EA',
                    replace: true,
                    transclude: true,
                    scope: {
                        placeholder: '@'
                    },
                    require: 'ngModel',
                    template: '
' +

                        '<input type="text" ng-model="ngModel" ng-model-options="{updateOn:\'change blur\'}" />' +
                        '
',

                link: function (scope, elem, attrs, ngModelCtrl) {
                    elem.bind("keyup",function(e) {
                        if (e.keyCode === 13) {
                            e.stopImmediatePropagation();
                            ngModelCtrl.$commitViewValue();
                            scope.$apply(ngModelCtrl.$setTouched);
                        }
                    });
                }

                }
            }
        ]);
})();

 $scope.$watch('pr', function(newValue,oldValue){
                console.log('val>>' + newValue);
            });
```

<pre class="lang-html prettyprint-override"><code><ss ng-model="pr"></ss>
</code>```

答:
Use $setViewValue to move the data from the isolate scope to the parent scope:

```<code>  link: function (scope, elem, attrs, ngModelCtrl) {
        elem.bind("keyup",function(e) {
            if (e.keyCode === 13) {
                e.stopImmediatePropagation();
                 ̶n̶g̶M̶o̶d̶e̶l̶C̶t̶r̶l̶.̶$̶c̶o̶m̶m̶i̶t̶V̶i̶e̶w̶V̶a̶l̶u̶e̶(̶)̶;̶
                //USE $setViewValue
                ngModelCtrl.$setViewValue(scope.ngModel);
                //scope.$apply(ngModelCtrl.$setTouched);
            }
        });
</code>```

Also use one-way < binding if you want the parent controller able to set the model.

```<code>scope: {ngModel: '<'}
</code>```

The DEMO on PLNKR

For more information, see

StackOverflow - Implementing custom form controls (using ngModel)

AngularJS Developer Guide - Implementing custom form controls (using ngModel)

AngularJS Developer Guide - Component-based application architecture

Body:
I have a directive where I have a template and I am trying to update the ng-model when a user clicks enter. I am able to catch the event and trying to update the value. I have a watcher on the element in a controller but the watcher function never gets triggered after commitViewValue

(function() {
    'use strict';

    angular.module('aa')
        .directive('ss', [
            function() {

                return {
                    restrict: 'EA',
                    replace: true,
                    transclude: true,
                    scope: {
                        placeholder: '@'
                    },
                    require: 'ngModel',
                    template: '
' +

                        '<input type="text" ng-model="ngModel" ng-model-options="{updateOn:\'change blur\'}" />' +
                        '
',

                link: function (scope, elem, attrs, ngModelCtrl) {
                    elem.bind("keyup",function(e) {
                        if (e.keyCode === 13) {
                            e.stopImmediatePropagation();
                            ngModelCtrl.$commitViewValue();
                            scope.$apply(ngModelCtrl.$setTouched);
                        }
                    });
                }

                }
            }
        ]);
})();

 $scope.$watch('pr', function(newValue,oldValue){
                console.log('val>>' + newValue);
            });

<ss ng-model="pr"></ss>

Body:
Use $setViewValue to move the data from the isolate scope to the parent scope:

  link: function (scope, elem, attrs, ngModelCtrl) {
        elem.bind("keyup",function(e) {
            if (e.keyCode === 13) {
                e.stopImmediatePropagation();
                 ̶n̶g̶M̶o̶d̶e̶l̶C̶t̶r̶l̶.̶$̶c̶o̶m̶m̶i̶t̶V̶i̶e̶w̶V̶a̶l̶u̶e̶(̶)̶;̶
                //USE $setViewValue
                ngModelCtrl.$setViewValue(scope.ngModel);
                //scope.$apply(ngModelCtrl.$setTouched);
            }
        });

Also use one-way < binding if you want the parent controller able to set the model.

scope: {ngModel: '<'}

The DEMO on PLNKR

For more information, see

StackOverflow - Implementing custom form controls (using ngModel)

AngularJS Developer Guide - Implementing custom form controls (using ngModel)

AngularJS Developer Guide - Component-based application architecture