问:
VBA Run-time error: '9'

I am trying to create a a function that takes some inputs of selected position and day and then using the day input, scan the matching sheet for data. However, passing a string to Sheets.Activate is causing me to get

runtime error 9

I am not sure why this is happening as other people did this in similar solutions on stack overflow. Here is my code

```<code>Sub GatherNames()

Dim x As Integer
Dim y As Integer
Dim rowN As Integer
Dim cell As String
Dim day As String
Dim position As String

day = ThisWorkbook.Sheets("Coverage").Range("C3")

Sheets(day).Activate

Application.ScreenUpdating = False

'Acquire entire data range
NumRows = Range("B3", Range("B3").End(xlDown)).Rows.Count
NumRows = NumRows / 2
'Start at beginning of data
rowN = 3
cell = "B" & rowN
Range(cell).Select
'Run for loop to check all rows
For y = 1 To NumRows
    'Get Rows Value
    Range(cell).End(xlToRight).Select

    'Add to list
    If (ActiveCell.Value > 1) Then
        Debug.Print ActiveCell.Value
    End If

    'Reset Cell to beginning of next Row
    rowN = rowN + 2
    cell = "B" & rowN
    Range(cell).Select
Next
Application.ScreenUpdating = True

End Sub
</code>```

I have tested all the code while excluding grabbing the day and then activating the day sheet and it works fine, but when I try and take in a string and then go to that sheet using

```<code>Sheets(day).Activate
</code>```

it causes

run time error 9 - subscript out of range

For extra detail, the value of day is "Monday" and I have a sheet called Monday.

答:
Day is a Reserved Word so you can't use it as a variable.  Change all references to that variable to something else, like myDay.

In the VB Editor, press F2 to open the Object Browser:  basically none of the listed should be used for naming objects/variables/sheets/etc, as they are reserved for VBA.

If you're still having a problem, try, on the modified line (using myDay for example), after this:

```<code>myDay = ThisWorkbook.Sheets("Coverage").Range("C3")
</code>```

...add a line:

```<code>MsgBox "--" ActiveSheet.Name & "--" & vbcrlf & "--" & myDay& "--"
</code>```

What does it say when you run the code again?

Are the 2 lines identical?

If you get an error, please include the full text or a screenshot of the error and where it is breaking the code.

Title: VBA Run-time error: '9'

Body:
I am trying to create a a function that takes some inputs of selected position and day and then using the day input, scan the matching sheet for data. However, passing a string to Sheets.Activate is causing me to get

runtime error 9

I am not sure why this is happening as other people did this in similar solutions on stack overflow. Here is my code

Sub GatherNames()

Dim x As Integer
Dim y As Integer
Dim rowN As Integer
Dim cell As String
Dim day As String
Dim position As String

day = ThisWorkbook.Sheets("Coverage").Range("C3")

Sheets(day).Activate

Application.ScreenUpdating = False

'Acquire entire data range
NumRows = Range("B3", Range("B3").End(xlDown)).Rows.Count
NumRows = NumRows / 2
'Start at beginning of data
rowN = 3
cell = "B" & rowN
Range(cell).Select
'Run for loop to check all rows
For y = 1 To NumRows
    'Get Rows Value
    Range(cell).End(xlToRight).Select

    'Add to list
    If (ActiveCell.Value > 1) Then
        Debug.Print ActiveCell.Value
    End If

    'Reset Cell to beginning of next Row
    rowN = rowN + 2
    cell = "B" & rowN
    Range(cell).Select
Next
Application.ScreenUpdating = True

End Sub

I have tested all the code while excluding grabbing the day and then activating the day sheet and it works fine, but when I try and take in a string and then go to that sheet using

Sheets(day).Activate

it causes

run time error 9 - subscript out of range

For extra detail, the value of day is "Monday" and I have a sheet called Monday.

Body:
Day is a Reserved Word so you can't use it as a variable.  Change all references to that variable to something else, like myDay.

In the VB Editor, press F2 to open the Object Browser:  basically none of the listed should be used for naming objects/variables/sheets/etc, as they are reserved for VBA.

If you're still having a problem, try, on the modified line (using myDay for example), after this:

myDay = ThisWorkbook.Sheets("Coverage").Range("C3")

...add a line:

MsgBox "--" ActiveSheet.Name & "--" & vbcrlf & "--" & myDay& "--"

What does it say when you run the code again?

Are the 2 lines identical?

If you get an error, please include the full text or a screenshot of the error and where it is breaking the code.


来源: stackexchange

问:
Cannot find pom.xml file inside allure reporter folder
I am trying to generate html reports out of allure results using mvn command. As per the documentation, it needs pom.xml file inside node_modules/jasmine-allure-reporter folder.

I saw many tutorials but when i go to that folder, pom.xml is not there. Please direct me with correct steps.

答:
I'm having the same problem.

create a pom.xml file and put this inside it,this is the file you would generate after npm install, but it is not generating more

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ru.yandex.allure</groupId>
    <artifactId>protractor-allure-plugin-generate-html</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <allure.version>1.4.15</allure.version>
        <allure.maven.version>2.2</allure.maven.version>
        <!-- Relative to the dir you're running from -->
        <allure.results_pattern>allure-results</allure.results_pattern>
    </properties>
    <dependencies>
        <dependency>
            <groupId>ru.yandex.qatools.allure</groupId>
            <artifactId>allure-report-face</artifactId>
            <version>${allure.version}</version>
            <type>war</type>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.10.v20150310</version>
                <configuration>
                    <webAppSourceDirectory>target/site/allure-maven-plugin</webAppSourceDirectory>
                    <stopKey>stop</stopKey>
                    <stopPort>2299</stopPort>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <reporting>
        <excludeDefaults>true</excludeDefaults>
        <plugins>
            <plugin>
                <groupId>ru.yandex.qatools.allure</groupId>
                <artifactId>allure-maven-plugin</artifactId>
                <version>${allure.maven.version}</version>
                <configuration>
                    <resultsPattern>${allure.results_pattern}</resultsPattern>
                    <!--<reportVersion>1.4.15</reportVersion>-->
                </configuration>
            </plugin>
        </plugins>
    </reporting>
</project>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm having the same problem.

create a pom.xml file and put this inside it,this is the file you would generate after npm install, but it is not generating more

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ru.yandex.allure</groupId>
    <artifactId>protractor-allure-plugin-generate-html</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <allure.version>1.4.15</allure.version>
        <allure.maven.version>2.2</allure.maven.version>
        <!-- Relative to the dir you're running from -->
        <allure.results_pattern>allure-results</allure.results_pattern>
    </properties>
    <dependencies>
        <dependency>
            <groupId>ru.yandex.qatools.allure</groupId>
            <artifactId>allure-report-face</artifactId>
            <version>${allure.version}</version>
            <type>war</type>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.2.10.v20150310</version>
                <configuration>
                    <webAppSourceDirectory>target/site/allure-maven-plugin</webAppSourceDirectory>
                    <stopKey>stop</stopKey>
                    <stopPort>2299</stopPort>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <reporting>
        <excludeDefaults>true</excludeDefaults>
        <plugins>
            <plugin>
                <groupId>ru.yandex.qatools.allure</groupId>
                <artifactId>allure-maven-plugin</artifactId>
                <version>${allure.maven.version}</version>
                <configuration>
                    <resultsPattern>${allure.results_pattern}</resultsPattern>
                    <!--<reportVersion>1.4.15</reportVersion>-->
                </configuration>
            </plugin>
        </plugins>
    </reporting>
</project>


问:
How to check for global variables in source code using awk, sed or grep?
I need to run a series of Python source codes against a bash script that contains logic to check for the presence of global variables. There are 2 criteria that I could use to see if a variable is global:

```<code>read file line by line
if there is an '=' (assignment sign) in the line AND no '#' in beginning of line (it is not commented out), check:
    is there a 'def' string anywhere in the text above this assignment line, e.g. def function_name()?
         if yes, variable within a function and hence not global
         else, possible global variable
</code>```

How do I do implement this pseudo code using grep, awk, or sed? I am also open to suggestions regarding better strategies of finding global variables with the bash script.

Example code:

```<code>int a = 23

def func_name():
    ...body...
</code>```

This code fails our test.

Example code 2:

```<code>def function_name():
    int a = 4
    ...
</code>```

This code passes the test.

答:
I do not think this is a good idea, but here is an literal implementation of your logic:

awk -F= '
  /^[^#]/ && NF > 1 && saw_def { print "not global:", $0; next  }
  NF > 1 { print "possibly global:", $0 }
  { saw_def = /def/ }
' file.py
```

<p>This tells awk to use <code>=</code> as a field separator on four <code>pattern {action}</code> pairs:</p>

<ol>
<li>Line starts with non-<code>#</code>, has a 2nd field (thus has a <code>=</code>), and the <code>saw_def</code> variable is set:<br>Print the line as not a global assignment; move on to next line (stop pattern matching)</li>
<li>Line otherwise has a <code>=</code>:<br>Print the line as possibly a global assignment</li>
<li>(Any line not matched by #1):<br>Set <code>saw_def</code> to a boolean representing whether "def" exists on the line</li>
</ol>

<p>Here is an example that will fail your test:</p>

<pre class="lang-py prettyprint-override"><code>def function_name():
    int a = 4
    int b = 8
</code>```

The logic you requested will note that a is not global and that b is possibly global.

This should be better:

```<code>awk '
  NF == 0 { next }
  {
    indent = match ($0, /[^ \t]/) - 1  # count of leading whitespace
    has_assign = /^[^#]*=/
  }
  $1 == "def" && !in_def { in_def = indent; next }
  indent > in_def && has_assign { print "not global:", $0; next }
  indent <= in_def { in_def = 0 }
  has_assign { print "possibly global:", $0 }
' file.py
</code>```

This attempts to parse the python code, taking advantage of the language's mandatory indentation to keep track of when you're in a function definition.  The five pattern {action} pairs are:

No fields (blank line):
Skip to next line

(Match any other line):
Set indent to the number of leading spaces and tabs before the first
Set has_assign to whether there is a variable assignment (a = exists before any #)

The first field is "def" and we're not already tracking a function:
Keep track of the current indentation level using ind_def and stop matching for this line

We're indented enough to be in a function and we have a assignment:
Report the non-global variable assignment

The indentation level is not more than the last function:
We're not in a function any more, set the function indentation level back to zero

We have a variable assignment (and no next has been triggered yet):
Report the possibly-global variable assignment

Note, I'm not sure all versions of awk understand \t so you might need a literal tab in its place. You can enter that on the command line as Ctrl+v, Tab.

 I still do not think a home-made python parser is a good idea.  If you really are parsing valid (and known-safe) python code, this similar question has answers that actually load the code, which would of course be definitive.  If you're dealing with potentially unsafe code, or python-like code, and/or you lack a python interpreter on the system you're using, my solution might be useful for quick code vetting.

Body:
I need to run a series of Python source codes against a bash script that contains logic to check for the presence of global variables. There are 2 criteria that I could use to see if a variable is global:

read file line by line
if there is an '=' (assignment sign) in the line AND no '#' in beginning of line (it is not commented out), check:
    is there a 'def' string anywhere in the text above this assignment line, e.g. def function_name()?
         if yes, variable within a function and hence not global
         else, possible global variable

How do I do implement this pseudo code using grep, awk, or sed? I am also open to suggestions regarding better strategies of finding global variables with the bash script.

Example code:

int a = 23

def func_name():
    ...body...

This code fails our test.

Example code 2:

def function_name():
    int a = 4
    ...

This code passes the test.

Body:
I do not think this is a good idea, but here is an literal implementation of your logic:

awk -F= '
  /^[^#]/ && NF > 1 && saw_def { print "not global:", $0; next  }
  NF > 1 { print "possibly global:", $0 }
  { saw_def = /def/ }
' file.py

This tells awk to use = as a field separator on four pattern {action} pairs:

Line starts with non-#, has a 2nd field (thus has a =), and the saw_def variable is set:
Print the line as not a global assignment; move on to next line (stop pattern matching)

Line otherwise has a =:
Print the line as possibly a global assignment

(Any line not matched by #1):
Set saw_def to a boolean representing whether "def" exists on the line

Here is an example that will fail your test:

def function_name():
    int a = 4
    int b = 8

The logic you requested will note that a is not global and that b is possibly global.

This should be better:

awk '
  NF == 0 { next }
  {
    indent = match ($0, /[^ \t]/) - 1  # count of leading whitespace
    has_assign = /^[^#]*=/
  }
  $1 == "def" && !in_def { in_def = indent; next }
  indent > in_def && has_assign { print "not global:", $0; next }
  indent <= in_def { in_def = 0 }
  has_assign { print "possibly global:", $0 }
' file.py

This attempts to parse the python code, taking advantage of the language's mandatory indentation to keep track of when you're in a function definition.  The five pattern {action} pairs are:

No fields (blank line):
Skip to next line

(Match any other line):
Set indent to the number of leading spaces and tabs before the first
Set has_assign to whether there is a variable assignment (a = exists before any #)

The first field is "def" and we're not already tracking a function:
Keep track of the current indentation level using ind_def and stop matching for this line

We're indented enough to be in a function and we have a assignment:
Report the non-global variable assignment

The indentation level is not more than the last function:
We're not in a function any more, set the function indentation level back to zero

We have a variable assignment (and no next has been triggered yet):
Report the possibly-global variable assignment

Note, I'm not sure all versions of awk understand \t so you might need a literal tab in its place. You can enter that on the command line as Ctrl+v, Tab.

 I still do not think a home-made python parser is a good idea.  If you really are parsing valid (and known-safe) python code, this similar question has answers that actually load the code, which would of course be definitive.  If you're dealing with potentially unsafe code, or python-like code, and/or you lack a python interpreter on the system you're using, my solution might be useful for quick code vetting.


问:
Get filenames of RAR achive via smbclient
From linux server I want to get the list of filenames in RAR archive which located in remote windows server.
Here is my command:

```<code>smbclient -U username%password '\\IP\D$\' --directory '\Backup_Logs' -c '"%programfiles(x86)%\WinRAR\unrar.exe" l file.rar'
</code>```

After running this in linux server the answer is this:

%programfiles(x86)%\WinRAR\unrar.exe: command not found

But I'm sure that I have Winrar installed on windows machine...
Where is my mistake or how I can reach my target in another way?

Thank you.

答:
There is a limited sets of operations you can use with the --command option.
They are listed under the Operations header on https://www.samba.org/samba/docs/man/manpages-3/smbclient.1.html

Try using smbmount before using the local unrar command on the Linux system.

Body:
From linux server I want to get the list of filenames in RAR archive which located in remote windows server.
Here is my command:

smbclient -U username%password '\\IP\D$\' --directory '\Backup_Logs' -c '"%programfiles(x86)%\WinRAR\unrar.exe" l file.rar'

After running this in linux server the answer is this:

%programfiles(x86)%\WinRAR\unrar.exe: command not found

But I'm sure that I have Winrar installed on windows machine...
Where is my mistake or how I can reach my target in another way?

Thank you.


问:
Is it possible to hide winform in TaskManager application tab?
I'm writing a transparent WinForms app and I want to hide the app from showing in Task Manager's applications tab. I'm OK with the fact that it will show in Processes (in fact it should).
If I set:

```<code>this.ShowInTaskbar = false;
</code>```

it only hides from taskbar.

Full code i have i have a timer made from labels

```<code>        public Form1()
    {
        InitializeComponent();
        this.BackColor = Color.LimeGreen;
        this.TransparencyKey = Color.LimeGreen;
        Timer time = new Timer();
        time.Interval = 1000;
        time.Tick += new EventHandler(time_Tick);
        time.Start();
        this.ShowInTaskbar = false;

    }

    void time_Tick(object sender, EventArgs e)
    {
        label1_hour.Text = DateTime.Now.Hour.ToString() ;
        label_minute.Text = DateTime.Now.Minute.ToString();
        label_second.Text = DateTime.Now.Second.ToString();
    }
</code>```

答:
Simply setting the form property FormBorderStyle to FixedToolWindow worked for me. On Win 10 it removes it from "Apps" in Task Manager and puts it in "Background processes"...which the OP specified (and was what I wanted also.)

In addition, it removes the form from showing in "Windows Key + Tab" listing of windows...which is what I wanted as well.

Body:
I'm writing a transparent WinForms app and I want to hide the app from showing in Task Manager's applications tab. I'm OK with the fact that it will show in Processes (in fact it should).
If I set:

this.ShowInTaskbar = false;

it only hides from taskbar.

Full code i have i have a timer made from labels

        public Form1()
    {
        InitializeComponent();
        this.BackColor = Color.LimeGreen;
        this.TransparencyKey = Color.LimeGreen;
        Timer time = new Timer();
        time.Interval = 1000;
        time.Tick += new EventHandler(time_Tick);
        time.Start();
        this.ShowInTaskbar = false;

    }

    void time_Tick(object sender, EventArgs e)
    {
        label1_hour.Text = DateTime.Now.Hour.ToString() ;
        label_minute.Text = DateTime.Now.Minute.ToString();
        label_second.Text = DateTime.Now.Second.ToString();
    }


问:
Mockito.eq matcher seems to match against list reference, not value
I have a method addToClonedList(List) in class App that calls method add(List) in class Dependency.  I want to unit test addToClonedList(List), and I want to create a mock Dependency object (called mockDependency) and verify that the method mockDependency.add(List) is called with the correct argument.  However, since the List instance referenced by clonedList gets a new element (100) added to if after the call in question, Mockito thinks that the 2-element List was passed to the mockDependency, and the test fails.  In reality, the List passed to mockDependency.add(List) only contained one element when it was called.  Is this expected Mockito behavior?  Is there a more standard way to test that I've passed the correct List to mockDependency.add(List)?

See my code structure and test output below:

main/java/App.java:

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

public class App {
  Dependency dataLayer = new Dependency();

  void addToClonedList(List<Integer> integerList) {
    List<Integer> clonedList = new ArrayList<Integer>(integerList);
    dataLayer.add(clonedList);
    clonedList.add(100);
  }
}
</code>```

main/java/Dependency.java:

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

public class Dependency {
  void add(List<Integer> integerList) {
    //
  }
}
</code>```

test/java/AppTest.java:

```<code>import java.util.*;
import org.junit.*;
import org.mockito.*;

public class AppTest {

  @InjectMocks
  App app;

  @Mock
  Dependency mockDependency;

  @Before
  public void beforeEachTest() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testWithVerify() {
    List<Integer> originalList = new ArrayList<>();
    originalList.add(1);

    app.addToClonedList(originalList);

    Mockito.verify(mockDependency).add(Mockito.eq(originalList));
  }
}
</code>```

pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.athenahealth</groupId>
  <artifactId>mockitotest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.testifyproject.mock</groupId>
      <artifactId>mockito</artifactId>
      <version>0.9.8</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>

</project>
</code>```

Test output:

```<code>Argument(s) are different! Wanted:
mockDependency.add([1]);
-> at AppTest.testWithVerify(AppTest.java:25)
Actual invocation has different arguments:
mockDependency.add([1, 100]);
-> at App.addToClonedList(App.java:8)

Comparison Failure:
Expected :mockDependency.add([1]);
Actual   :mockDependency.add([1, 100]);
</code>```

答:
As Andy Turner notes, the problem is that Mockito only keeps a reference to the value passed, without cloning it. This makes sense, because it would be wasteful for immutable value objects like String, and would be practically impossible for certain references like Thread.

However, you can write your own Answer to make that copy yourself:

```<code>List<Integer> listSnapshot;

@Test
public void testWithVerify() {
  List<Integer> originalList = new ArrayList<>();
  originalList.add(1);
  Mockito.when(mockDependency.add(any())).thenAnswer(invocation => {
    listSnapshot = new ArrayList<>((List<Integer>) (invocation.getArguments()[0]));
  });

  app.addToClonedList(originalList);

  assertEquals(originalList, listSnapshot);
}
</code>```

Body:
I have a method addToClonedList(List) in class App that calls method add(List) in class Dependency.  I want to unit test addToClonedList(List), and I want to create a mock Dependency object (called mockDependency) and verify that the method mockDependency.add(List) is called with the correct argument.  However, since the List instance referenced by clonedList gets a new element (100) added to if after the call in question, Mockito thinks that the 2-element List was passed to the mockDependency, and the test fails.  In reality, the List passed to mockDependency.add(List) only contained one element when it was called.  Is this expected Mockito behavior?  Is there a more standard way to test that I've passed the correct List to mockDependency.add(List)?

See my code structure and test output below:

main/java/App.java:

import java.util.*;

public class App {
  Dependency dataLayer = new Dependency();

  void addToClonedList(List<Integer> integerList) {
    List<Integer> clonedList = new ArrayList<Integer>(integerList);
    dataLayer.add(clonedList);
    clonedList.add(100);
  }
}

main/java/Dependency.java:

import java.util.List;

public class Dependency {
  void add(List<Integer> integerList) {
    //
  }
}

test/java/AppTest.java:

import java.util.*;
import org.junit.*;
import org.mockito.*;

public class AppTest {

  @InjectMocks
  App app;

  @Mock
  Dependency mockDependency;

  @Before
  public void beforeEachTest() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testWithVerify() {
    List<Integer> originalList = new ArrayList<>();
    originalList.add(1);

    app.addToClonedList(originalList);

    Mockito.verify(mockDependency).add(Mockito.eq(originalList));
  }
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.athenahealth</groupId>
  <artifactId>mockitotest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>org.testifyproject.mock</groupId>
      <artifactId>mockito</artifactId>
      <version>0.9.8</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
  </dependencies>

</project>

Test output:

Argument(s) are different! Wanted:
mockDependency.add([1]);
-> at AppTest.testWithVerify(AppTest.java:25)
Actual invocation has different arguments:
mockDependency.add([1, 100]);
-> at App.addToClonedList(App.java:8)

Comparison Failure:
Expected :mockDependency.add([1]);
Actual   :mockDependency.add([1, 100]);

Body:
As Andy Turner notes, the problem is that Mockito only keeps a reference to the value passed, without cloning it. This makes sense, because it would be wasteful for immutable value objects like String, and would be practically impossible for certain references like Thread.

However, you can write your own Answer to make that copy yourself:

List<Integer> listSnapshot;

@Test
public void testWithVerify() {
  List<Integer> originalList = new ArrayList<>();
  originalList.add(1);
  Mockito.when(mockDependency.add(any())).thenAnswer(invocation => {
    listSnapshot = new ArrayList<>((List<Integer>) (invocation.getArguments()[0]));
  });

  app.addToClonedList(originalList);

  assertEquals(originalList, listSnapshot);
}


问:
Fill matrix by data from pandas.DataFrame, skip NaN
I want to fill the matrix ref using pd.DataFrame xxx but skip the NaN.

```<code>print xxx
OUT >>
   intensity name  rowtype1  rowtype2
0        100    A         1       4.0
1        200    A         2       NaN
2        300    B         3       5.0
</code>```

Then I fill the matrix by ref[rowtype,col] = intensity where I have 2 rowtype.

```<code>ref = np.zeros(shape=(7,4))
for idx, inte, name, r1, r2 in xxx.itertuples():
    ref[r1,idx] = inte
    ref[r2,idx] = inte # error because of NaN in rowtype2

print ref
</code>```

How can I skip NaN here?
I know one way to use drop.na() but it has to create new dataframe which has rowtype2 and intensity. I would like to have quick simple way, like just jump across NaN with intensity = 200 to next rowtype2 = 5 with intensity = 300.

Additional info:

1) Here is how to create xxx

```<code>prot = ['A','A','B']
calc_m = [1,2,3]
calc_m2 = [4, np.nan,5]
inte = [100,200,300]
xxx = pd.DataFrame({'name' : pd.Series(prot),
                    'rowtype1': pd.Series(calc_m),
                    'rowtype2': pd.Series(calc_m2),
                    'intensity': pd.Series(inte)
                    })
</code>```

答:
You could use this option using melt, and then setting the index of ref using numpy's indexing vs. using a for loop

```<code>set = xxx.reset_index().melt(['intensity','index'],['rowtype1','rowtype2']).dropna()

ref[set.value.astype(int).values,set['index'].values] = set.intensity.values
</code>```

which gives you

```<code>array([[   0.,    0.,    0.,    0.],
       [ 100.,    0.,    0.,    0.],
       [   0.,  200.,    0.,    0.],
       [   0.,    0.,  300.,    0.],
       [ 100.,    0.,    0.,    0.],
       [   0.,    0.,  300.,    0.],
       [   0.,    0.,    0.,    0.]])
</code>```

Body:
I want to fill the matrix ref using pd.DataFrame xxx but skip the NaN.

print xxx
OUT >>
   intensity name  rowtype1  rowtype2
0        100    A         1       4.0
1        200    A         2       NaN
2        300    B         3       5.0

Then I fill the matrix by ref[rowtype,col] = intensity where I have 2 rowtype.

ref = np.zeros(shape=(7,4))
for idx, inte, name, r1, r2 in xxx.itertuples():
    ref[r1,idx] = inte
    ref[r2,idx] = inte # error because of NaN in rowtype2

print ref

How can I skip NaN here?
I know one way to use drop.na() but it has to create new dataframe which has rowtype2 and intensity. I would like to have quick simple way, like just jump across NaN with intensity = 200 to next rowtype2 = 5 with intensity = 300.

Additional info:

1) Here is how to create xxx

prot = ['A','A','B']
calc_m = [1,2,3]
calc_m2 = [4, np.nan,5]
inte = [100,200,300]
xxx = pd.DataFrame({'name' : pd.Series(prot),
                    'rowtype1': pd.Series(calc_m),
                    'rowtype2': pd.Series(calc_m2),
                    'intensity': pd.Series(inte)
                    })

Body:
You could use this option using melt, and then setting the index of ref using numpy's indexing vs. using a for loop

set = xxx.reset_index().melt(['intensity','index'],['rowtype1','rowtype2']).dropna()

ref[set.value.astype(int).values,set['index'].values] = set.intensity.values

which gives you

array([[   0.,    0.,    0.,    0.],
       [ 100.,    0.,    0.,    0.],
       [   0.,  200.,    0.,    0.],
       [   0.,    0.,  300.,    0.],
       [ 100.,    0.,    0.,    0.],
       [   0.,    0.,  300.,    0.],
       [   0.,    0.,    0.,    0.]])


问:
JavaScript - Adding two numbers (which still strings) in one textbox
I'm currently making a bot for some reason, i wanted to add a command that will do math when some user typed <command> 1 + 2 and bot will answers 3. And when it's <command> 2 * 3, it will reply 6. (Let's just use textbox for this case, if I typed 1 + 2 in textbox, theres an alert that shows "3").

My question is, is it possible, by any chance to make this kind of command?
If so, I'd like to know how. Since I've learned a little about JavaScript RegEx and i think if i use it, it'll work out.

答:
Here's a quick example that picks up an expression from a text box when the button is clicked, and performs a calculation. It uses a regex to separate out the numbers/operator, and a switch to test the operator cases. Very simple.

const input = document.querySelector('input');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);

function handleClick() {
  const txt = input.value;
  const expr = txt.match(/(\d+)\s?([\+\-\*\/])\s?(\d+)/);
  const first = Number(expr[1]);
  const operator = expr[2];
  const second = Number(expr[3]);
  switch (operator) {
    case '+':
      console.log(first + second);
      break;
    case '-':
      console.log(first - second);
      break;
    case '*':
      console.log(first * second);
      break;
    case '/':
      console.log(first / second);
      break;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input/><button>Submit</button></code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's a quick example that picks up an expression from a text box when the button is clicked, and performs a calculation. It uses a regex to separate out the numbers/operator, and a switch to test the operator cases. Very simple.

const input = document.querySelector('input');
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);

function handleClick() {
  const txt = input.value;
  const expr = txt.match(/(\d+)\s?([\+\-\*\/])\s?(\d+)/);
  const first = Number(expr[1]);
  const operator = expr[2];
  const second = Number(expr[3]);
  switch (operator) {
    case '+':
      console.log(first + second);
      break;
    case '-':
      console.log(first - second);
      break;
    case '*':
      console.log(first * second);
      break;
    case '/':
      console.log(first / second);
      break;
  }
}

<input/><button>Submit</button>


问:
How would I clear all rails sessions?
Here is my code:

```<code>if session[:firsttimestart].nil?
else
  @firsttime = false
end

if @firsttime == true
  initglobals()
end
session[:firsttimestart]=false
</code>```

The problem is when I turn off the server and come back to the application, the  session[:firsttimestart] is still false. It somehow stores this variable in my system without an expiration date so the iniglobals() is not called. I tried to use rake tmp:clear and it didn't work. How can I clear all the sessions that am using in my system each time I restart my server?

答:
In Rails 5 if using ActiveRecord:

ActiveRecord::SessionStore::Session.delete_all

or for more granular:

```<code># For example schedule this once a day`
ActiveRecord::SessionStore::Session.where(["updated_at < ?", 2.weeks.ago]).delete_all
</code>```

Title: How would I clear all rails sessions?

Body:
Here is my code:

if session[:firsttimestart].nil?
else
  @firsttime = false
end

if @firsttime == true
  initglobals()
end
session[:firsttimestart]=false

The problem is when I turn off the server and come back to the application, the  session[:firsttimestart] is still false. It somehow stores this variable in my system without an expiration date so the iniglobals() is not called. I tried to use rake tmp:clear and it didn't work. How can I clear all the sessions that am using in my system each time I restart my server?

Body:
In Rails 5 if using ActiveRecord:

ActiveRecord::SessionStore::Session.delete_all

or for more granular:

# For example schedule this once a day`
ActiveRecord::SessionStore::Session.where(["updated_at < ?", 2.weeks.ago]).delete_all


问:
How do you determine how far to normalize a database?
When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance?</p>

答: I believe starting with an un-normalized database and moving toward normalized as you progress is usually easiest to get started.  To the question of how far to normalize, my philosophy is to normalize until is starts to hurt.  That may sound a little flippant, but it generally is a good way to gauge how far to take it.</p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: GrizzlyGuru


问:
Valgrind finds a leak in my code, could anybody help me find it?
I have the following code for a function.
It reads a file, line per line, without knowing the size in advance.

It is a learning exercise in my school. I have run the valgrind command on it and I have this output (the full log is here => valgrind log):

```<code>==21166== 44 bytes in 1 blocks are definitely lost in loss record 14   of 42
==21166==    at 0x1000CB606: malloc (in /Users/cbaillat/.brew/Cellar/valgrind/3.13.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==21166==    by 0x100000F0C: ft_strnew (in ./get_next_line)
==21166==    by 0x10000061C: get_next_line (get_next_line.c:71)
==21166==    by 0x10000058A: main (main.c:31)
</code>```

I don't know where that could come from. Here is the function that provokes the leak:

```<code>#include "get_next_line.h"

/*
** If newline is null, it means it hasn't found a new line in the string.
** It means we have reach the end of line.
*/

static int  ft_copy_leftover(char **line, char fd_buffer[BUFF_SIZE], char *nl)
{
    if (nl == NULL)
        return (1);
    ft_strcpy(fd_buffer, &nl[1]);
    (*line)[nl - (*line)] = '\0';
    return (1);
}

/*
** 1- We keep reading unless we find a new line or we reach the end of file
** 2- We reallocate the old pointer with buffer size
** 3- As long as there are characters to read and we haven't encountered a
**  new line, we keep copying the data into line
**  We store the buffer in line, and then erase it
** 4- If we have already reached the end of file, we do not need to copy the
**  buffer. Otherwise we copy it to line.
*/

static int  read_line(const int fd, char fd_buffer[BUFF_SIZE], char **line)
{
    int32_t     status;
    char        *newline;
    uint32_t    len;

    while (((newline = ft_strchr(*line, '\n')) == NULL)
        && ((status = read(fd, fd_buffer, BUFF_SIZE)) > FILE_READ))
    {
        len = ft_strlen(*line) + 1;
        if ((*line = ft_realloc(*line, len, len + BUFF_SIZE)) == NULL)
            return (ERROR);
        ft_strcat(*line, fd_buffer);
        ft_bzero(fd_buffer, BUFF_SIZE);
    }
    if ((**line != '\0') && (status >= FILE_READ))
        return (ft_copy_leftover(line, fd_buffer, newline));
    return (status);
}

/*
** 1- If the buffer is not empty, we allocate a new string and copy the buffer
**  contents
** 2- We loop in the buffer in case we have multiple new lines inside
*/

int         get_next_line(const int fd, char **line)
{
    static char fd_array[ULIMIT_N][BUFF_SIZE + 1];
    int8_t      status;

    if (fd < 0 || fd > ULIMIT_N || line == NULL
        || !(*line = ft_strnew(BUFF_SIZE + 1)))
        return (ERROR);
    if (fd_array[fd][0] != '\0')
        *line = ft_strcpy(*line, fd_array[fd]);
    ft_bzero(fd_array[fd], BUFF_SIZE + 1);
    status = read_line(fd, fd_array[fd], line);
    return (status);
}
</code>```

The function 'ft_strnew' just mallocs memory for a string and memsets it to 0:

```<code>#include "libft.h"

char    *ft_strnew(size_t size)
{
    char    *str;

    if ((str = (char *)malloc(sizeof(*str) * (size + 1))) == NULL)
        return (NULL);
    ft_memset((void *)str, (int)'\0', (size + 1));
    return (str);
}
</code>```

Could anybody help me find it?
By the way, this is how I call my function in the main:

```<code>int main(int ac, char **av)
{
    int32_t i;
    int32_t fd;
    int32_t status;
    char    *line_read;

    if (ac <= 1)
        return (0);
    fd = open(av[1], O_RDONLY);
    i = 0;
    line_read = NULL;
    while (1)
    {
        status = get_next_line(fd, &line_read);
        // printf("status: %d\n", status);
        if (status == ERROR)
            return (ERROR);
        if (status == FILE_READ)
            return (SUCCESS);
        ft_putstr(line_read);
        free (line_read);
    }
    return (SUCCESS);
}
</code>```

I free the malloc line (ft_strnew) everytime I call the function, so I am at a loss. If you need more information to help, I'd be glap to provide it. It is my first question on stack, I hope it is clear enough.

Thanks to all of you!

EDIT:

I simply forgot to free the line in the while loop of my main, when returning some values. Adding a couple of free solved my problem! Thanks to all of you!

```<code>while (1)
    {
        status = get_next_line(fd, &line_read);
        // printf("status: %d\n", status);
        if (status == ERROR)
        {
            free (line_read);
            return (ERROR);
        }
        if (status == FILE_READ)
        {
            free (line_read);
            return (SUCCESS);
        }
        ft_putstr(line_read);
        free (line_read);
    }
</code>```

答:
There is a couple of possibilities. Firstly in your while loop, if you get certain values of status you exit without freeing line_read. That will only cause one block to be lost though.

Secondly, you overwrite the value of *line with this code

```<code>*line = ft_strcpy(*line, fd_array[fd])
</code>```

which looks like the most likely candidate if you're allocating more memory in there. If you were changing it to a different point within that block, you'd get entirely different errors when you tried to free it.

Body:
I have the following code for a function.
It reads a file, line per line, without knowing the size in advance.

It is a learning exercise in my school. I have run the valgrind command on it and I have this output (the full log is here => valgrind log):

==21166== 44 bytes in 1 blocks are definitely lost in loss record 14   of 42
==21166==    at 0x1000CB606: malloc (in /Users/cbaillat/.brew/Cellar/valgrind/3.13.0/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==21166==    by 0x100000F0C: ft_strnew (in ./get_next_line)
==21166==    by 0x10000061C: get_next_line (get_next_line.c:71)
==21166==    by 0x10000058A: main (main.c:31)

I don't know where that could come from. Here is the function that provokes the leak:

#include "get_next_line.h"

/*
** If newline is null, it means it hasn't found a new line in the string.
** It means we have reach the end of line.
*/

static int  ft_copy_leftover(char **line, char fd_buffer[BUFF_SIZE], char *nl)
{
    if (nl == NULL)
        return (1);
    ft_strcpy(fd_buffer, &nl[1]);
    (*line)[nl - (*line)] = '\0';
    return (1);
}

/*
** 1- We keep reading unless we find a new line or we reach the end of file
** 2- We reallocate the old pointer with buffer size
** 3- As long as there are characters to read and we haven't encountered a
**  new line, we keep copying the data into line
**  We store the buffer in line, and then erase it
** 4- If we have already reached the end of file, we do not need to copy the
**  buffer. Otherwise we copy it to line.
*/

static int  read_line(const int fd, char fd_buffer[BUFF_SIZE], char **line)
{
    int32_t     status;
    char        *newline;
    uint32_t    len;

    while (((newline = ft_strchr(*line, '\n')) == NULL)
        && ((status = read(fd, fd_buffer, BUFF_SIZE)) > FILE_READ))
    {
        len = ft_strlen(*line) + 1;
        if ((*line = ft_realloc(*line, len, len + BUFF_SIZE)) == NULL)
            return (ERROR);
        ft_strcat(*line, fd_buffer);
        ft_bzero(fd_buffer, BUFF_SIZE);
    }
    if ((**line != '\0') && (status >= FILE_READ))
        return (ft_copy_leftover(line, fd_buffer, newline));
    return (status);
}

/*
** 1- If the buffer is not empty, we allocate a new string and copy the buffer
**  contents
** 2- We loop in the buffer in case we have multiple new lines inside
*/

int         get_next_line(const int fd, char **line)
{
    static char fd_array[ULIMIT_N][BUFF_SIZE + 1];
    int8_t      status;

    if (fd < 0 || fd > ULIMIT_N || line == NULL
        || !(*line = ft_strnew(BUFF_SIZE + 1)))
        return (ERROR);
    if (fd_array[fd][0] != '\0')
        *line = ft_strcpy(*line, fd_array[fd]);
    ft_bzero(fd_array[fd], BUFF_SIZE + 1);
    status = read_line(fd, fd_array[fd], line);
    return (status);
}

The function 'ft_strnew' just mallocs memory for a string and memsets it to 0:

#include "libft.h"

char    *ft_strnew(size_t size)
{
    char    *str;

    if ((str = (char *)malloc(sizeof(*str) * (size + 1))) == NULL)
        return (NULL);
    ft_memset((void *)str, (int)'\0', (size + 1));
    return (str);
}

Could anybody help me find it?
By the way, this is how I call my function in the main:

int main(int ac, char **av)
{
    int32_t i;
    int32_t fd;
    int32_t status;
    char    *line_read;

    if (ac <= 1)
        return (0);
    fd = open(av[1], O_RDONLY);
    i = 0;
    line_read = NULL;
    while (1)
    {
        status = get_next_line(fd, &line_read);
        // printf("status: %d\n", status);
        if (status == ERROR)
            return (ERROR);
        if (status == FILE_READ)
            return (SUCCESS);
        ft_putstr(line_read);
        free (line_read);
    }
    return (SUCCESS);
}

I free the malloc line (ft_strnew) everytime I call the function, so I am at a loss. If you need more information to help, I'd be glap to provide it. It is my first question on stack, I hope it is clear enough.

Thanks to all of you!

EDIT:

I simply forgot to free the line in the while loop of my main, when returning some values. Adding a couple of free solved my problem! Thanks to all of you!

while (1)
    {
        status = get_next_line(fd, &line_read);
        // printf("status: %d\n", status);
        if (status == ERROR)
        {
            free (line_read);
            return (ERROR);
        }
        if (status == FILE_READ)
        {
            free (line_read);
            return (SUCCESS);
        }
        ft_putstr(line_read);
        free (line_read);
    }

Body:
There is a couple of possibilities. Firstly in your while loop, if you get certain values of status you exit without freeing line_read. That will only cause one block to be lost though.

Secondly, you overwrite the value of *line with this code

*line = ft_strcpy(*line, fd_array[fd])

which looks like the most likely candidate if you're allocating more memory in there. If you were changing it to a different point within that block, you'd get entirely different errors when you tried to free it.


问:
Recursion - javascript
I am trying to solve an extra credit problem using recursion. Basically there is a "tree" that has matching "leaves" and I need to use recursion to check those matching leaves and return true if they match and return false if they do not.

I have no idea how to do this and no materials I can find are helping me understand recursion any better. This is for an online program to learn how to program.

Any help would be appreciated!

```<code>Psuedo:

    // initialize some value
      // initialize some flag.. boolean
      // initialize some helper function and pass obj...leaf checker recursive function
        // check all the keys ...for loop/forEach
          // if a key is an object && value is undefined
            // assign value
            // return
          // if a value is an object ==> recurse
          // if a value is found and it doesn't match our initial value
          // trip our flag to false
          // return
      // return true or false

 const checkMatchingLeaves = (obj) => {

};
</code>```

My attempt:

```<code>const checkMatchingLeaves = (obj) => {
  // return true if every property on `obj` is the same
  // otherwise return false
  let  checker = Object.values(obj);
  if (Object.values(obj).length === 1) return true;
    if (checker.map(checker[i] === checker[i + 1])) {
      i > checker.length; i++;
    }
};
</code>```

答:
This isn't exactly what (I think) you're asking for, but you should be able to use it as a template to figure out what to do:

```<code>// searchTree takes a value to try to match and an array/primitive
// value.
function searchTree(val, node) {
  // Check if it's a value or an array. If it's a value we can
  // do the test and return, otherwise we recursively call
  // searchTree on all the children.
  // Array.some returns true if any of the function calls return
  // true. This is a shorthand for your boolean flag: it lets us
  // return early as soon as we find a match.
  return Array.isArray(node) ?
    node.some(child => searchTree(val, child)) : // recursive call
    val === node;
}

searchTree(3, [1, 2, [8], [[[3]]]]);      // true
searchTree('abc', 'a');                   // false
searchTree('abc', ['ab', 'bc', ['abc']]); // true
</code>```

This is a DFS search implementation.

Title: Recursion - javascript

Body:
I am trying to solve an extra credit problem using recursion. Basically there is a "tree" that has matching "leaves" and I need to use recursion to check those matching leaves and return true if they match and return false if they do not.

I have no idea how to do this and no materials I can find are helping me understand recursion any better. This is for an online program to learn how to program.

Any help would be appreciated!

Psuedo:

    // initialize some value
      // initialize some flag.. boolean
      // initialize some helper function and pass obj...leaf checker recursive function
        // check all the keys ...for loop/forEach
          // if a key is an object && value is undefined
            // assign value
            // return
          // if a value is an object ==> recurse
          // if a value is found and it doesn't match our initial value
          // trip our flag to false
          // return
      // return true or false

 const checkMatchingLeaves = (obj) => {

};

My attempt:

const checkMatchingLeaves = (obj) => {
  // return true if every property on `obj` is the same
  // otherwise return false
  let  checker = Object.values(obj);
  if (Object.values(obj).length === 1) return true;
    if (checker.map(checker[i] === checker[i + 1])) {
      i > checker.length; i++;
    }
};

Body:
This isn't exactly what (I think) you're asking for, but you should be able to use it as a template to figure out what to do:

// searchTree takes a value to try to match and an array/primitive
// value.
function searchTree(val, node) {
  // Check if it's a value or an array. If it's a value we can
  // do the test and return, otherwise we recursively call
  // searchTree on all the children.
  // Array.some returns true if any of the function calls return
  // true. This is a shorthand for your boolean flag: it lets us
  // return early as soon as we find a match.
  return Array.isArray(node) ?
    node.some(child => searchTree(val, child)) : // recursive call
    val === node;
}

searchTree(3, [1, 2, [8], [[[3]]]]);      // true
searchTree('abc', 'a');                   // false
searchTree('abc', ['ab', 'bc', ['abc']]); // true

This is a DFS search implementation.


问:
Pushing a 2d array onto a C++ STL stack?
```<code>int test[5][5];
stack<int**> mystack;
mystack.push(test);
</code>```

I get the error:

no matching function for call to ‘std::stack > >::push(int [5][5])’
  /usr/include/c++/4.4/bits/stl_stack.h:182: note: candidates are: void std::stack<_Tp, _Sequence>::push(const typename _Sequence::value_type&) [with _Tp = int**, _Sequence = std::deque >]

I've never really used stacks before so I would appreciate any help. If I declare test as a one-dimensional array and stack as int*, it works fine.

Edit: I'm trying to implement backtracing for a sudokusolver. I have the sudoku grid as a 9x9 array of set objects (objects that hold the solution or possible solutions). I have to push the current state of the puzzle onto the stack, and then from there try guess and check. If a guess creates a contradiction (ie violates the rules of a sudoku), then I would pop from the stack to recover the puzzle before the invalid guess.

答: An int ** is not the same as a 2D array. A pointer to int test[5][5] would be int (*)[5], so you need a stack<int (*)[5]>. There's a good explanation of this here: Arrays and pointers in C.

Body:
int test[5][5];
stack<int**> mystack;
mystack.push(test);

I get the error:

no matching function for call to ‘std::stack > >::push(int [5][5])’
  /usr/include/c++/4.4/bits/stl_stack.h:182: note: candidates are: void std::stack<_Tp, _Sequence>::push(const typename _Sequence::value_type&) [with _Tp = int**, _Sequence = std::deque >]

I've never really used stacks before so I would appreciate any help. If I declare test as a one-dimensional array and stack as int*, it works fine.

Edit: I'm trying to implement backtracing for a sudokusolver. I have the sudoku grid as a 9x9 array of set objects (objects that hold the solution or possible solutions). I have to push the current state of the puzzle onto the stack, and then from there try guess and check. If a guess creates a contradiction (ie violates the rules of a sudoku), then I would pop from the stack to recover the puzzle before the invalid guess.


问:
How can I send a variable to a function when calling it?
How can I send the variable message to the function callmessage when it is called?

```<code><script>
var message = 'hello and this is your message'

callmessage(); // how can i send the variable 'message' to the function when I call it

function callmessage() {
   console.log(the text sent when the function was called)
}
</script>
</code>```

答:
You send it as an argument to the function like:

var message = 'hello and this is your message'
callmessage(message); // how can i send the message variable
function callmessage(themessage) {
  console.log(themessage)
}```

I would highly recommend reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

OwnerDisplayName: anon

Body:
You send it as an argument to the function like:

var message = 'hello and this is your message'
callmessage(message); // how can i send the message variable
function callmessage(themessage) {
  console.log(themessage)
}

I would highly recommend reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions


答:
```<code><script>
var message = 'hello and this is your message'

callmessage(message);

function callmessage(x) {
   console.log(x);
}
</script>
</code>```

If you're just getting into javascript, I highly recommend looking at a few things that will help you write better code:

https://eslint.org/

https://github.com/airbnb/javascript

ES6 features like modules, arrow functions, etc. and how https://babeljs.io/ can be used to transpile ES6 to ES5 for use in browsers now

Title: How can I send a variable to a function when calling it?

Body: How can I send the variable message to the function callmessage when it is called?

Body:
<script>
var message = 'hello and this is your message'

callmessage(message);

function callmessage(x) {
   console.log(x);
}
</script>

If you're just getting into javascript, I highly recommend looking at a few things that will help you write better code:

https://eslint.org/

https://github.com/airbnb/javascript

ES6 features like modules, arrow functions, etc. and how https://babeljs.io/ can be used to transpile ES6 to ES5 for use in browsers now


问:
Overwrite a variable within FOR loop
In my Python code I am trying to iterate a Gaussian function.

I am defining a variable x0 = 2, then I do maths on it with a For loop and then I am trying to overwrite the value of x0 with the value of x_test. I want to loop it over many times in order to get the shape of the Gaussian function (so I guess like Monte Carlo method).

What I cannot do is figure out how to overwrite the value of x0 with the value of x_test after each iteration.

Could anyone give me some pointers here please? As I just can't find the answer to that. Any help would be much appreciated!

Thank you!

My code:

```<code>from random import random
import random
from math import exp, pow
import math
from random import randint

amp = 0.85
x0 = 2.0

def overwrite(x):
    global x0
    x0 = x

for n in iter(overwrite, 10000):
    uniform = random.uniform(0, 1)
    if uniform < 0.5:
        sigma_int = 1
    else:
        sigma_int = -1
    sigma_uni = round(random.uniform(0, 1),5)
    x_test = foobar(2.0) + sigma_int * amp
    P = (exp(-pow(x_test, 2))) / (exp(-pow(x0, 2)))
    if (P > sigma_uni):
        f = open('pyton.txt', 'a')
        f.write("%s %s\n" % (float(x_test), float(P)))
        f.close()
</code>```

答:
Since you are defining  global x0, you can call it in the loop itself. After observing your code I think you are not assigning the value of 'x_test' to 'x0'. So just do it inside the loop.
To confirm if its working or no, you can put a debug statement like:
print(x0) after substituting the value which will give you idea if its working or no. Trying with print debug is the best way to check the problem. </p>

Title: Overwrite a variable within FOR loop

Body:
In my Python code I am trying to iterate a Gaussian function.

I am defining a variable x0 = 2, then I do maths on it with a For loop and then I am trying to overwrite the value of x0 with the value of x_test. I want to loop it over many times in order to get the shape of the Gaussian function (so I guess like Monte Carlo method).

What I cannot do is figure out how to overwrite the value of x0 with the value of x_test after each iteration.

Could anyone give me some pointers here please? As I just can't find the answer to that. Any help would be much appreciated!

Thank you!

My code:

from random import random
import random
from math import exp, pow
import math
from random import randint

amp = 0.85
x0 = 2.0

def overwrite(x):
    global x0
    x0 = x

for n in iter(overwrite, 10000):
    uniform = random.uniform(0, 1)
    if uniform < 0.5:
        sigma_int = 1
    else:
        sigma_int = -1
    sigma_uni = round(random.uniform(0, 1),5)
    x_test = foobar(2.0) + sigma_int * amp
    P = (exp(-pow(x_test, 2))) / (exp(-pow(x0, 2)))
    if (P > sigma_uni):
        f = open('pyton.txt', 'a')
        f.write("%s %s\n" % (float(x_test), float(P)))
        f.close()


问:
Are dynamic mysql queries with sql escaping just as secure as prepared statements?
I have an application which would greatly benefit by using dynamic mysql queries in combination with mysql (mysqli) real escape string. If I ran all data received from the user through mysql real escape would it be just as secure as using mysql prepared statements?</p>

答:
Yes, but a qualified yes.

You need to properly escape 100% of the input.  And you need to properly set character sets (If you're using the C API, you need to call the mysql_set_character_set() instead of SET NAMES).  If you miss one tiny thing, you're vulnerable.  So it's yes, as long as you do everything right...

And that's the reason a lot of people will recommend prepared queries.  Not because they are any safer.  But because they are more forgiving...


问:
Converting Grayscale values from .csv to BufferedImage
I'm attempting to convert a .csv file containing grayscale values to an image using BufferedImage.
The csv is read into pixArray[] initially, in which all values are doubles.

I am attempting to use BufferedImage to create a 100x100px output image with the code

```<code>                BufferedImage image = new BufferedImage(width,height,BufferedImage.
                    TYPE_BYTE_GRAY);
            for(int x = 0; x < width; x++)
            {
                for(int y = 0; y < height; y++)
                {
                    image.setRGB(x, y, (int)Math.round(pixArray[y]));
                }
            }

            File file_out = new File("output.png");
            try {
                ImageIO.write(image, "png", file_out);
            } catch (IOException e) {
                e.printStackTrace();
            }
</code>```

but all I have as output is a 100x100 black square.

I've tried alternatives to TYPE_BYTE_GRAY with no success, as well as the png format for outout, and can't find what is producing this error.

答:
It should be

```<code>int g = (int)Math.round(pixArray[y]);
image.setRGB(x,y,new Color(g,g,g).getRGB());
</code>```

What your current code is doing is setting the alpha to the pixel value but leaving the color components all zero.

Body:
I'm attempting to convert a .csv file containing grayscale values to an image using BufferedImage.
The csv is read into pixArray[] initially, in which all values are doubles.

I am attempting to use BufferedImage to create a 100x100px output image with the code

                BufferedImage image = new BufferedImage(width,height,BufferedImage.
                    TYPE_BYTE_GRAY);
            for(int x = 0; x < width; x++)
            {
                for(int y = 0; y < height; y++)
                {
                    image.setRGB(x, y, (int)Math.round(pixArray[y]));
                }
            }

            File file_out = new File("output.png");
            try {
                ImageIO.write(image, "png", file_out);
            } catch (IOException e) {
                e.printStackTrace();
            }

but all I have as output is a 100x100 black square.

I've tried alternatives to TYPE_BYTE_GRAY with no success, as well as the png format for outout, and can't find what is producing this error.

Body:
It should be

int g = (int)Math.round(pixArray[y]);
image.setRGB(x,y,new Color(g,g,g).getRGB());

What your current code is doing is setting the alpha to the pixel value but leaving the color components all zero.


问:
How to delete specific elements in a vector using struct data type
i'm new to C++. My program is a quiz game which user can choose category and level for the questions. At first, i use the struct data type

```<code>struct QuestionInfo
{
   string category;
   string level;
   string question;
   string answer;
};
</code>```

then

```<code>vector<QuestionInfo> vec;
</code>```

The idea of this part is to store the info of the question include (category, level, question and answer) to each element.
Then after building menu and the output questions UI, i go to the filters

```<code>void category_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (category_choice != vec[i].category)
         vec.erase(vec.begin() + i );
   }
}
Void level_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (level_choice != vec[i].level)
         vec.erase(vec.begin() + i );
   }
}
</code>```

So the idea of the filters is to delete the elements which not contain the matched category and level. But the output questions did not match with the category and the level i had choose before.  I'm not sure what I'm doing wrong.

答: As mentioned by others, the remove_if + erase is a standard and expressive way to achieve what you want. But you may also consider non-destructive filtering with a copy_if into a new container, or even without using any additional storage with Boost.Range adaptor boost::adaptors::filtered or boost::filter_iterator. Look here for examples.

Body:
i'm new to C++. My program is a quiz game which user can choose category and level for the questions. At first, i use the struct data type

struct QuestionInfo
{
   string category;
   string level;
   string question;
   string answer;
};

then

vector<QuestionInfo> vec;

The idea of this part is to store the info of the question include (category, level, question and answer) to each element.
Then after building menu and the output questions UI, i go to the filters

void category_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (category_choice != vec[i].category)
         vec.erase(vec.begin() + i );
   }
}
Void level_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (level_choice != vec[i].level)
         vec.erase(vec.begin() + i );
   }
}

So the idea of the filters is to delete the elements which not contain the matched category and level. But the output questions did not match with the category and the level i had choose before.  I'm not sure what I'm doing wrong.


问:
TFS, is there a variable for the artifact zip file name?
Is there a way to get the artifact file name easily? Looks like TFS already knows this as shown in the log below:</p>

```<code>No path specified for search pattern: *.zip defaulting to: F:\TFS2017_Release_Agent\_work\r1\a

2017-12-08T16:38:36.8519067Z Searching for: *.zip under directory: F:\TFS2017_Release_Agent\_work\r1\a

2017-12-08T16:38:36.8519067Z Found: 1 files to extract:

2017-12-08T16:38:36.8519067Z F:\TFS2017_Release_Agent\_work\r1\a\ZFJ0_ServiceSearchPlusBuildDefn\BETALink.Service.SearchPlus\ZFJ0_BETALink10.4 DevOps_BETALink.Service.SearchPlus_1.0.0_886.zip

2017-12-08T16:38:36.8519067Z Creating destination folder: F:\TFS2017_Release_Agent\_work\r1\a\48

2017-12-08T16:38:36.8519067Z Extracting file: F:\TFS2017_Release_Agent\_work\r1\a\ZFJ0_ServiceSearchPlusBuildDefn\BETALink.Service.SearchPlus\ZFJ0_BETALink10.4 DevOps_BETALink.Service.SearchPlus_1.0.0_886.zip

2017-12-08T16:38:36.8519067Z [command]F:\TFS2017_Release_Agent\_work\_tasks\ExtractFiles_5e1e3830-fbfb-11e5-aab1-090c92bc4988\1.112.1\7zip\7z.exe x -oF:\TFS2017_Release_Agent\_work\r1\a\48 F:\TFS2017_Release_Agent\_work\r1\a\ZFJ0_ServiceSearchPlusBuildDefn\BETALink.Service.SearchPlus\ZFJ0_BETALink10.4 DevOps_BETALink.Service.SearchPlus_1.0.0_886.zip

2017-12-08T16:38:36.8987827Z
</code>```

答:
An artifact isn't "a file". In your specific case, it is. But in general, an artifact can contain any number of files.

There is no way to retrieve the files present in an artifact, since an artifact can also be a pointer to a UNC share.

Body:
Is there a way to get the artifact file name easily? Looks like TFS already knows this as shown in the log below:

No path specified for search pattern: *.zip defaulting to: F:\TFS2017_Release_Agent\_work\r1\a

2017-12-08T16:38:36.8519067Z Searching for: *.zip under directory: F:\TFS2017_Release_Agent\_work\r1\a

2017-12-08T16:38:36.8519067Z Found: 1 files to extract:

2017-12-08T16:38:36.8519067Z F:\TFS2017_Release_Agent\_work\r1\a\ZFJ0_ServiceSearchPlusBuildDefn\BETALink.Service.SearchPlus\ZFJ0_BETALink10.4 DevOps_BETALink.Service.SearchPlus_1.0.0_886.zip

2017-12-08T16:38:36.8519067Z Creating destination folder: F:\TFS2017_Release_Agent\_work\r1\a\48

2017-12-08T16:38:36.8519067Z Extracting file: F:\TFS2017_Release_Agent\_work\r1\a\ZFJ0_ServiceSearchPlusBuildDefn\BETALink.Service.SearchPlus\ZFJ0_BETALink10.4 DevOps_BETALink.Service.SearchPlus_1.0.0_886.zip

2017-12-08T16:38:36.8519067Z [command]F:\TFS2017_Release_Agent\_work\_tasks\ExtractFiles_5e1e3830-fbfb-11e5-aab1-090c92bc4988\1.112.1\7zip\7z.exe x -oF:\TFS2017_Release_Agent\_work\r1\a\48 F:\TFS2017_Release_Agent\_work\r1\a\ZFJ0_ServiceSearchPlusBuildDefn\BETALink.Service.SearchPlus\ZFJ0_BETALink10.4 DevOps_BETALink.Service.SearchPlus_1.0.0_886.zip

2017-12-08T16:38:36.8987827Z


问:
SpriteKit linearDamping - maximum?
Note that Apple's doco asserts

https://developer.apple.com/documentation/spritekit/skphysicsbody/1519796-lineardamping

This property is used to simulate fluid or air friction forces on the body. The property must be a value between 0.0 and 1.0. The default value is 0.1. If the value is 0.0, no linear damping is applied to the object.

In fact: you can set values higher than one - so, "10.0" and "20.0" work perfectly; 1, 10 and 20 are all very clearly different.

has anyone probed in to this and discovered if there is actually a maximum?  (If it just asymptotes away, what's the realistic range?)

答:
The Apple doco is simply wrong.

Just to answer my own question, in iOS:

The actual documentation:

This property is used to simulate fluid or air friction forces on the body. The property must be a value between 0.0 and 1.0. The default value is 0.1. If the value is 0.0, no linear damping is applied to the object.

is simply wrong.

A value of about 10 to 15 is typical when you want typical "strong damping" like in many physics scenes.

I very often use values of 2 or 3.  And "10" is our value for "very thick honey".

Title: SpriteKit linearDamping - maximum?


问:
How to actually use meta tags to share data through social networks?
So I'm trying to do a website that has multiple images with their own content and allow users to click on a dropdown next to an image and share that image and the content to: Twitter, Facebook, LinkedIn, and Email.

What I've looked into is creating a separate URL for each image with it's content. Then in each page setting it's description, image, etc. in the meta tags. So on the landing page when they click to share it's actually pulling a separate page.

My question is...how do I share meta tag information to Twitter, Facebook, LinkedIn, and Email?

I've tried for Twitter:

```<code><a rel="nofollow" class="share-twitter sd-button share-icon no-text" href="http://twitter.com/share?text=Textgoeshere&url=https://www.landingpage.com/&hashtags=example" target="_blank" title="Click to share on Twitter"><span></span><span class="sharing-screen-reader-text">Click to share on Twitter (Opens in new window)</span></a>
</code>```

This seems like a lot of text that I would have to then write for each image. Plus it doesn't pull the image, author, etc. Isn't there a way to grab the meta tag information to share to Twitter here?

I mean I have the meta tags present (below) but no idea how to actually use them to share.

```<code><meta name="twitter:card" content="Here's Twitter Card"/>
<meta name="twitter:site" content="@author"/>
<meta name="twitter:domain" content="@author"/>
<meta name="twitter:url" content="http://www.mainpage.com">
<meta name="twitter:title" content="Twitter Title">
<meta name="twitter:description" content="Here is the Twitter Description">
<meta name="twitter:image" content="link to image">
</code>```

Found the following for Facebook:
https://developers.facebook.com/docs/plugins/share-button#

Found the following for Twitter:
https://publish.twitter.com/#

答:
Okay here is what I'll do for you because I am not sure what answer you are looking for here. We are going to write some javacript that can do this for you.

Here you have your HTML tag. It's important that you give every div the class "twitter-input-card" and you give them an onload function of "updateCards()".

HTML here:

```<code><div class="twitter-input-cards" onload="updateCards(tCard1)"> </div>
</code>```

Now here is your js....:

```<code>    //this function creates your object
function twitterCards(twitterCard, twitterAuthor1, twitterAuthor2, twitterURL, twitterTitle, twitterDes, twitterImg) {
    //this will be twitter:card
    this.twitterCard = twitterCard;
    //this will be twitter:site
    this.twitterAuthor1 = twitterAuthor1;
    //this will be twitter:domain
    this.twitterAuthor2 = twitterAuthor2;
    //this will be twitter:url
    this.twitterURL = twitterURL;
    //this will be twitter:title
    this.twitterTitle = twitterTitle;
    //this will be twitter:description
    this.twitterDes = twitterDes;
    //this will be twitter:image
    this.twitterImg = twitterImg;

}

//this isn't as important but i am not familiar with twitter cards so if there are more meta tags you can define them here.
var tcard = 'twitter:card';
var tsite = 'twitter:site';
var tdomain = 'twitter:domain';
var turl = 'twitter:url';
var ttitle = 'twitter:title';
var tdes = 'twitter:description';
var timg = 'twitter:image';

//this function will update the card with information
  function  updateCards(selectCard){
    cardSelect = selectCard;

    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tcard + "' content = '" + twitterCard + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tsite + "' content = '" + twitterAuthor1 + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tdomain + "' content = '" + twitterAuthor2 + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + turl + "' content = '" + twitterURL + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + ttitle + "' content = '" + twitterTitle + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tdes + "' content = '" + twitterDes + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + timg + "' content = '" + twitterImg + "'/>"

  }

//this is where you define your cards info
var tCard1 = new twitterCards (
    //this will be twitter:card
    "Here is a new card",
    //this will be twitter:site
    "here is an author",
    //this will be twitter:domain
    "here is another aurthor",
    //this will be twitter:url
    "here is the page",
    //this will be twitter:title
    "here is the title",
    //this will be twitter:description
    "here is the description",
    //this will be twitter:img
    "img.jpg"

)
</code>```

Body:
So I'm trying to do a website that has multiple images with their own content and allow users to click on a dropdown next to an image and share that image and the content to: Twitter, Facebook, LinkedIn, and Email.

What I've looked into is creating a separate URL for each image with it's content. Then in each page setting it's description, image, etc. in the meta tags. So on the landing page when they click to share it's actually pulling a separate page.

My question is...how do I share meta tag information to Twitter, Facebook, LinkedIn, and Email?

I've tried for Twitter:

Click to share on Twitter (Opens in new window)

This seems like a lot of text that I would have to then write for each image. Plus it doesn't pull the image, author, etc. Isn't there a way to grab the meta tag information to share to Twitter here?

I mean I have the meta tags present (below) but no idea how to actually use them to share.

<meta name="twitter:card" content="Here's Twitter Card"/>
<meta name="twitter:site" content="@author"/>
<meta name="twitter:domain" content="@author"/>
<meta name="twitter:url" content="http://www.mainpage.com">
<meta name="twitter:title" content="Twitter Title">
<meta name="twitter:description" content="Here is the Twitter Description">
<meta name="twitter:image" content="link to image">

Found the following for Facebook:
https://developers.facebook.com/docs/plugins/share-button#

Found the following for Twitter:
https://publish.twitter.com/#

Body:
Okay here is what I'll do for you because I am not sure what answer you are looking for here. We are going to write some javacript that can do this for you.

Here you have your HTML tag. It's important that you give every div the class "twitter-input-card" and you give them an onload function of "updateCards()".

HTML here:

<div class="twitter-input-cards" onload="updateCards(tCard1)"> </div>

Now here is your js....:

    //this function creates your object
function twitterCards(twitterCard, twitterAuthor1, twitterAuthor2, twitterURL, twitterTitle, twitterDes, twitterImg) {
    //this will be twitter:card
    this.twitterCard = twitterCard;
    //this will be twitter:site
    this.twitterAuthor1 = twitterAuthor1;
    //this will be twitter:domain
    this.twitterAuthor2 = twitterAuthor2;
    //this will be twitter:url
    this.twitterURL = twitterURL;
    //this will be twitter:title
    this.twitterTitle = twitterTitle;
    //this will be twitter:description
    this.twitterDes = twitterDes;
    //this will be twitter:image
    this.twitterImg = twitterImg;

}

//this isn't as important but i am not familiar with twitter cards so if there are more meta tags you can define them here.
var tcard = 'twitter:card';
var tsite = 'twitter:site';
var tdomain = 'twitter:domain';
var turl = 'twitter:url';
var ttitle = 'twitter:title';
var tdes = 'twitter:description';
var timg = 'twitter:image';

//this function will update the card with information
  function  updateCards(selectCard){
    cardSelect = selectCard;

    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tcard + "' content = '" + twitterCard + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tsite + "' content = '" + twitterAuthor1 + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tdomain + "' content = '" + twitterAuthor2 + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + turl + "' content = '" + twitterURL + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + ttitle + "' content = '" + twitterTitle + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + tdes + "' content = '" + twitterDes + "'/>"
    document.getElementsByClassName("twitter-input-cards").innerHTML = "<meta name=" + "'" + timg + "' content = '" + twitterImg + "'/>"

  }

//this is where you define your cards info
var tCard1 = new twitterCards (
    //this will be twitter:card
    "Here is a new card",
    //this will be twitter:site
    "here is an author",
    //this will be twitter:domain
    "here is another aurthor",
    //this will be twitter:url
    "here is the page",
    //this will be twitter:title
    "here is the title",
    //this will be twitter:description
    "here is the description",
    //this will be twitter:img
    "img.jpg"

)


问:
Workflow (i.e. Directed Graph) Browser Based Editors
I want to provide a WYSIWYG tool, preferably JavaScript based, for workflow diagramming (i.e. directed graphs). I need commercial software friendly licensing, which can include paying a fee to OEM. If there's a necessary server side piece I'd need it in Java or ColdFusion because I'm integrating with an existing product.

My workflow graphs can have more than one start vertex, but only one end vertex, and edges are directed. Beyond WYSIWYG editing, I'm looking for a tool that can assist with the following:

Ability to export the drawing so it can be:

persisted

parsed by a programming language (I'm assuming XML, but other formats are just fine).

edited again (preserving layout information)

Associate arbitrary data with edges and vertices including ability to define view/edit panes.

Nice to have:

Detection if any vertices are unable to reach the end.

Automatically layout vertices and edges if no plotting information is provided.

I've looked at mxGraph, which seems promising, but am hoping an answerer here can provide some additional direction before I jump down the rabbit hole.

答:
Have you checked out the JavaScript InfoVis Toolkit yet (http://thejit.org/)? It might not have everything you need, but it does force-directed graph layouts, and allows interactive editing. Since it's rendering into a JavaScript canvas, you should be able to save the results as an image file.

Here are some demos of the graph-layout functionality:
http://thejit.org/static/v20/Jit/Examples/ForceDirected/example2.html


问:
ECS / CES shared and dependent components and cache locality
I have been trying to wrap my head around how ECS works when there are components which are shared or dependent. I've read numerous articles on ECS and can't seem to find a definitive answer to this.

Assume the following scenario:

I have an entity which has a ModelComponent (or MeshComponent), a PositionComponent and a ParticlesComponent (or EmitterComponent).

The ModelRenderSystem needs both the ModelComponent and the PositionComponent.

The ParticleRenderSystem needs ParticlesComponent and the PositionComponent.

In the ModelRenderSystem, for cache efficiency / locality, I would like run through all the ModelComponents which are in a compact array and render them, however for each model I need to pull the PositionComponent. I haven't even started thinking about how to deal with the textures, shaders etc for each model (which will definitely blow the cache).

A similar issue with the ParticleRenderSystem.. I need both the ParticlesComponent as well as the PositionComponent, and I want to be able to run through all ParticlesComponents in a cache efficient / friendly manner.

I considered having ModelComponent and ParticlesComponent each having their own position, but they will need to be synched every time the models position changes (imagine a particle effect on a character). This adds another entity or component which needs to track and synch components or values (and potentially negates any cache efficiency).

How does everyone else handle these kinds of dependency issues?

答:
One way to reduce the complexity could be to invert flow of data.

Consider that your ModelRenderSystem has a listener callback that allows the entity framework to inform it that an entity has been added to the simulation that contains both a position and model component.  During this callback, the system could register a callback on the position component or the system that owns that component allowing the ModelRenderSystem to be informed when that position object changes.

As the change events from the position changes come in, the ModelRenderSystem can queue up a list of modifications it must replicate during its update phase and then during update, its really a simple lookup each modifications model and set the position to the value in the event.

The benefit is that per frame, you're only ever replicating position changes that actually changed during the frame and you minimize lookups needed to replicate the data.  While the update of the position propagates to various systems of interest may not be as cache friendly, the gains you observe otherwise out weigh that.

Lastly, don't forget that systems do not necessarily need to iterate over the components proper.  The components in your entity system exist to allow you to toggle plug-able behavior easily.  The systems can always manage a more cache friendly data structure and using the above callback approach, allows you to do that and manage data replication super easily with minimal coupling.


问:
Inheriting from a template class using the inheriting class
When I inherit from a class the compiler has to know the definition of the base class in order to create it. But when I inherit from a template class using oneself (the inheriting class), how can the compiler create the code? It does not know the size of the class yet.

```<code>#include <iostream>

template <class T> class IFoo
{
public:
     virtual T addX(T foo, double val) = 0;
     // T memberVar; // uncomment for error
};

class Foo : public IFoo<Foo>
{
public:
    Foo(double value)
        : m_value(value) {}

    Foo addX(Foo foo, double b) override
    {
        return Foo(foo.m_value + b);
    }

    double m_value;
};

int main()
{
    Foo foo1(1);
    Foo foo2 = foo1.addX(foo1, 1);

    std::cout << foo2.m_value;
}
</code>```

First I thought it works because it's an interface but it also works with a regular class.

When I store the template as a member i get an error that Foo is undefined, just as I expected.

答:
The general concept here is called the Curiously Recurring Template Pattern or CRTP. Searching on that will get lots of hits. see: https://stackoverflow.com/questions/tagged/crtp .

However there is a simple explanation that likely answers your question without getting too much into CRTP. The following is allowed in C and C++:

```<code>struct foo {
    struct foo *next;
    ...
};
</code>```

or with two types:

```<code>struct foo;
struct bar;

struct foo {
    struct bar *first;
    ...
};

struct bar {
    struct foo *second;
    ...
};
</code>```

So long as only a pointer to a struct or class is used, a complete definition of the type doesn't have to be available. One can layer templates on top of this in a wide variety of ways and one must be clear to reason separately about the type parameterizing the template and its use within the template. Adding in SFINAE (Substitution Failure Is Not An Error), one can even make templates that do no get instantiated because things cannot be done with a given type.

Body:
When I inherit from a class the compiler has to know the definition of the base class in order to create it. But when I inherit from a template class using oneself (the inheriting class), how can the compiler create the code? It does not know the size of the class yet.

#include <iostream>

template <class T> class IFoo
{
public:
     virtual T addX(T foo, double val) = 0;
     // T memberVar; // uncomment for error
};

class Foo : public IFoo<Foo>
{
public:
    Foo(double value)
        : m_value(value) {}

    Foo addX(Foo foo, double b) override
    {
        return Foo(foo.m_value + b);
    }

    double m_value;
};

int main()
{
    Foo foo1(1);
    Foo foo2 = foo1.addX(foo1, 1);

    std::cout << foo2.m_value;
}

First I thought it works because it's an interface but it also works with a regular class.

When I store the template as a member i get an error that Foo is undefined, just as I expected.

Body:
The general concept here is called the Curiously Recurring Template Pattern or CRTP. Searching on that will get lots of hits. see: https://stackoverflow.com/questions/tagged/crtp .

However there is a simple explanation that likely answers your question without getting too much into CRTP. The following is allowed in C and C++:

struct foo {
    struct foo *next;
    ...
};

or with two types:

struct foo;
struct bar;

struct foo {
    struct bar *first;
    ...
};

struct bar {
    struct foo *second;
    ...
};

So long as only a pointer to a struct or class is used, a complete definition of the type doesn't have to be available. One can layer templates on top of this in a wide variety of ways and one must be clear to reason separately about the type parameterizing the template and its use within the template. Adding in SFINAE (Substitution Failure Is Not An Error), one can even make templates that do no get instantiated because things cannot be done with a given type.


问:
linq lambda multiple group joins
I am trying to get a list of product along with its rating, comments and views. PID is product ID column without foreign key relationship.

Product -

```<code>Id  Name
1   P1
2   P2
</code>```

Rating -

```<code>Id  PID Rating
1   1   5
2   1   4
3   2   3
</code>```

Comments -

```<code>Id  PID Comment
1   1   Good
2   1   Average
3   2   Bad
</code>```

Views -

```<code>Id  PID View
1   1   500
2   1   200
3   2   10
</code>```

My class would look like this –

```<code>Public Class Product{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Rating> Ratings{ get; set; }
    public List<Comments> Comments{ get; set; }
    public List<Views> Views{ get; set; }
}
</code>```

I am trying to get this information using Linq group join, so that I get child collection.

```<code>IEnumerable<Product> _products = _context.Product.GroupJoin(_context.Rating, p=>p.id, r=>r.PID, (Product, Rating) => new Product(){
    //fill fields here
});
</code>```

But how to group other tables as well into single database query.

Thanks

答:
Instead of a GroupJoin, you can just look up the matches directly to construct the Product object:

```<code>IEnumerable<Product> _products = _context.Product.Select(product => new Product() {
    Id = product.id,
    Name = product.name,
    Ratings = _context.Rating.Where(r => r.PID == product.id).ToList(),
    // ... other lists similar
});
</code>```

As pointed out in comments, the above query could generate three sub-queries for every product.

You can use GroupJoin if you create anonymous objects to hold the intermediate results:

```<code>var _products = _context.Product.GroupJoin(_context.Rating, p => p.id, r => r.PID, (p, rs) => new { p, rs })
                                .GroupJoin(_context.Comment, prs => prs.p.id, c => c.PID, (prs, cs) => new { prs.p, prs.rs, cs })
                                .GroupJoin(_context.View, prs => prs.p.id, v => v.PID, (prscs, vs) => new Product() {
                                    Id = prscs.p.id,
                                    Name = prscs.p.name,
                                    Ratings = prscs.rs.ToList(),
                                    Comments = prscs.cs.ToList(),
                                    Views = vs.ToList()
                                });
</code>```

Title: linq lambda multiple group joins

Body:
I am trying to get a list of product along with its rating, comments and views. PID is product ID column without foreign key relationship.

Product -

Id  Name
1   P1
2   P2

Rating -

Id  PID Rating
1   1   5
2   1   4
3   2   3

Comments -

Id  PID Comment
1   1   Good
2   1   Average
3   2   Bad

Views -

Id  PID View
1   1   500
2   1   200
3   2   10

My class would look like this –

Public Class Product{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Rating> Ratings{ get; set; }
    public List<Comments> Comments{ get; set; }
    public List<Views> Views{ get; set; }
}

I am trying to get this information using Linq group join, so that I get child collection.

IEnumerable<Product> _products = _context.Product.GroupJoin(_context.Rating, p=>p.id, r=>r.PID, (Product, Rating) => new Product(){
    //fill fields here
});

But how to group other tables as well into single database query.

Thanks

Body:
Instead of a GroupJoin, you can just look up the matches directly to construct the Product object:

IEnumerable<Product> _products = _context.Product.Select(product => new Product() {
    Id = product.id,
    Name = product.name,
    Ratings = _context.Rating.Where(r => r.PID == product.id).ToList(),
    // ... other lists similar
});

As pointed out in comments, the above query could generate three sub-queries for every product.

You can use GroupJoin if you create anonymous objects to hold the intermediate results:

var _products = _context.Product.GroupJoin(_context.Rating, p => p.id, r => r.PID, (p, rs) => new { p, rs })
                                .GroupJoin(_context.Comment, prs => prs.p.id, c => c.PID, (prs, cs) => new { prs.p, prs.rs, cs })
                                .GroupJoin(_context.View, prs => prs.p.id, v => v.PID, (prscs, vs) => new Product() {
                                    Id = prscs.p.id,
                                    Name = prscs.p.name,
                                    Ratings = prscs.rs.ToList(),
                                    Comments = prscs.cs.ToList(),
                                    Views = vs.ToList()
                                });


答:
Not 100% clear on what you actually want (e.g. what is "num < 10", which num? Id1_num or id2_num?), but the below should get you close I believe.

first -- group df2 and format it into the date intervals:

```<code>df2_grouped = df2.groupby(['ID1', 'ID2']).\
    apply(lambda x: pd.Series([x['Date'].min(), x['Date'].max(),
                               x['id2_num'].count()],
                              index=['StartDate2', 'EndDate2', 'ID1Date1Count']))
df2_grouped = df2_grouped.reset_index()

print(df2_grouped)

    ID1 ID2 StartDate2  EndDate2    ID1Date1Count
0   111 10  1/1/2017    4/1/2017    3
1   112 20  2/1/2017    4/1/2017    1
2   113 20  1/1/2017    2/1/2017    2
3   114 30  2/1/2017    4/1/2017    2
4   115 30  4/1/2017    5/1/2017    2
</code>```

Then -- merge it with your df1:

```<code>df1[['ID1', 'StartDate1', 'EndDate1']].merge(df2_grouped, on='ID1')
df1 = df1.sort_values(by=['StartDate2'])

print(df1)

    ID1 StartDate1  EndDate1    ID2 StartDate2  EndDate2    ID1Date1Count
0   111 1/1/2017    3/1/2017    10  1/1/2017    4/1/2017    3
2   113 1/1/2017    2/1/2017    20  1/1/2017    2/1/2017    2
1   112 2/1/2017    3/1/2017    20  2/1/2017    4/1/2017    1
3   114 2/1/2017    4/1/2017    30  2/1/2017    4/1/2017    2
4   115 4/1/2017    5/1/2017    30  4/1/2017    5/1/2017    2
</code>```

Again, the output doesn't exactly match your desired output, but its close.

Title: Joining 2 df through look up in Python using Pandas

Body:
I'm having a headache with performing a join on data frames through look up:

df1,

Name ID1    StartDate1  EndDate1    StartDate2  EndDate2
ab   111    1/1/2017    3/1/2017    2/1/2017    4/1/2017
bc   112    2/1/2017    3/1/2017    2/1/2017    4/1/2017
cd   113    1/1/2017    2/1/2017    2/1/2017    4/1/2017
df   114    2/1/2017    4/1/2017    2/1/2017    4/1/2017
fe   115    4/1/2017    5/1/2017    2/1/2017    4/1/2017

df2,

ID1 ID2 Date     Id1_num  id2_num
111 10  1/1/2017    10      11
111 10  2/1/2017            10
111 10  3/1/2017    13      13
111 10  4/1/2017    15      13
112 20  2/1/2017    11      19
112 20  3/1/2017    12
112 20  4/1/2017            19
113 20  1/1/2017    17       5
113 20  2/1/2017    17      14
114 30  2/1/2017    11      13
114 30  3/1/2017    10
114 30  4/1/2017    18      13
115 30  4/1/2017    7        5
115 30  5/1/2017    13      19

I want my result df3,

Name   ID1    ID2   StartDate1  EndDate1    StartDate2  EndDate2    ID1Date1Count   ID1Date1Average   ID1Date2Count    ID1Date2Average    ID2Date1Count    ID2Date1Average    ID2Date2Count    ID2Date2Average
ab     111    10    1/1/2017    3/1/2017    2/1/2017    4/1/2017    2               11.5              2                14                 3                11.33              3                12
bc     112    20    2/1/2017    3/1/2017    2/1/2017    4/1/2017    2               11.5              2                11.5               1                19                 2                19
cd     113    20    1/1/2017    2/1/2017    2/1/2017    4/1/2017    2               17                1                17                 1                14                 1                14
df     114    30    2/1/2017    4/1/2017    2/1/2017    4/1/2017    3               13                3                13                 2                13                 2                13
fe     115    30    4/1/2017    5/1/2017    2/1/2017    4/1/2017    1               19                0                0                  1                19                 0                0

Where
ID1Date1Count is the entries count from the date interval [StartDate1, EndDate1],
ID1Date2Count is the entries count from the date interval [StartDate2, EndDate2]
ID2Date1Count is the entries count from the date interval [StartDate1, EndDate1]
ID2Date2Count is the entries count from the date interval [StartDate2, EndDate2]
Along with their average.
The extra condition here is that we do not include num if num < 10.

Thanks a bunch!

Body:
Not 100% clear on what you actually want (e.g. what is "num < 10", which num? Id1_num or id2_num?), but the below should get you close I believe.

first -- group df2 and format it into the date intervals:

df2_grouped = df2.groupby(['ID1', 'ID2']).\
    apply(lambda x: pd.Series([x['Date'].min(), x['Date'].max(),
                               x['id2_num'].count()],
                              index=['StartDate2', 'EndDate2', 'ID1Date1Count']))
df2_grouped = df2_grouped.reset_index()

print(df2_grouped)

    ID1 ID2 StartDate2  EndDate2    ID1Date1Count
0   111 10  1/1/2017    4/1/2017    3
1   112 20  2/1/2017    4/1/2017    1
2   113 20  1/1/2017    2/1/2017    2
3   114 30  2/1/2017    4/1/2017    2
4   115 30  4/1/2017    5/1/2017    2

Then -- merge it with your df1:

df1[['ID1', 'StartDate1', 'EndDate1']].merge(df2_grouped, on='ID1')
df1 = df1.sort_values(by=['StartDate2'])

print(df1)

    ID1 StartDate1  EndDate1    ID2 StartDate2  EndDate2    ID1Date1Count
0   111 1/1/2017    3/1/2017    10  1/1/2017    4/1/2017    3
2   113 1/1/2017    2/1/2017    20  1/1/2017    2/1/2017    2
1   112 2/1/2017    3/1/2017    20  2/1/2017    4/1/2017    1
3   114 2/1/2017    4/1/2017    30  2/1/2017    4/1/2017    2
4   115 4/1/2017    5/1/2017    30  4/1/2017    5/1/2017    2

Again, the output doesn't exactly match your desired output, but its close.


问:
Dynamically Load Vue Component from a variable
I was building a very large enterprise application where components load on demand , i use to work with require.js and i am able to do require(stringVar){..}

but i am not able to do this in webpack i thought webpack was better in everything

```<code>var URL ="./components/async.vue";
      console.log(typeof(URL));
      Vue.component("async", function(resolve) {
        // Master Loader
        require([URL], resolve);
      });
</code>```

everything i change the value of require(["./components/async.vue"], resolve); to  require([URL], resolve); it throws

```<code>Critical dependency: the request of a dependency is an expression
</code>```

答:
I do this a lot in our app though NOT in this specific way. However, I think resolve should send back the component's definition.

You c(/sh)ould try:

```<code>resolve(require(URL))
</code>```

DOUBT: Is URL mentioned above a resource hit on the server / just relative path between the two components ?

Body:
I was building a very large enterprise application where components load on demand , i use to work with require.js and i am able to do require(stringVar){..}

but i am not able to do this in webpack i thought webpack was better in everything

var URL ="./components/async.vue";
      console.log(typeof(URL));
      Vue.component("async", function(resolve) {
        // Master Loader
        require([URL], resolve);
      });

everything i change the value of require(["./components/async.vue"], resolve); to  require([URL], resolve); it throws

Critical dependency: the request of a dependency is an expression

Body:
I do this a lot in our app though NOT in this specific way. However, I think resolve should send back the component's definition.

You c(/sh)ould try:

resolve(require(URL))

DOUBT: Is URL mentioned above a resource hit on the server / just relative path between the two components ?