问:
How to repeat actions in cypress and get the result of each action
I am trying to repeat a certain action in cypress defined in doTheAction and then get the results of those repeated actions. When I try Promise.all it immediately resolves to an array of undefined

```<code>describe("some test", () => {
  it("for each", () => {
    const data = { a: 1, b: 2 };
    Promise.all(
      Object.entries(data.en).map(([key, value]) =>
        doTheAction(value).then(result => [key, result])
      )
    ).then(result => {
      debugger;
      // array of undefined before the browser did anything
      console.log(result);
    });
  });
});
const doTheAction = text => {
  cy.visit(
    "https://my.site"
  );
  cy.get("some input").type(text);
  return cy
    .get("the result")
    .then(result => result[0].innerText);
};
</code>```

When I try to chain the actions I get undefined for results when the second action is finished:

```<code>describe("some test", () => {
  it("for each", () => {
    const data = { a: 1, b: 2 };
    Object.entries(data).reduce(
      (results, [key, value]) =>
        results.then(results =>
          doTheAction(value).then(
            result =>
              //results is undefined after the second action
              results.concat([[key, result]]) //current result
          )
        ),
      Promise.resolve([]) //initial results
    );
  }).then(results => {
    //never gets here
    console.log(results);
  });
});
const doTheAction = text => {
  cy.visit("https://my.site");
  cy.get("some input").type(text);
  return cy
    .get("the result")
    .then(result => result[0].innerText);
};
</code>```

Either with Promise.all or chaining the promises the actions will run in the correct order (cypress schedules them and runs them in order) but I don't see how it's possible to get a result out of it.

答:
Data driven tests are quite easy, one generalized pattern is

const arrayOfTestData = [...];
const arrayOfExpectedResults = [...];

const functionContainingSingleTest = (dataItem, index) => {

  // Commands that use dataItem, and check arrayOfExpectedResults[index]

}

arrayOfTestData.forEach((dataItem, index) =>
  functionContainingSingleTest(dataItem, index)
);
// After loop, reached before commands finish.
```

<p>What happens is your test en-queue's the commands within the function, as if you had written them sequentially.  </p>

<hr>

<p>If you want to gather results, it becomes more difficult because Commands don't return a usable value. You could try chaining <code>.then(result => results.push(result))</code>, but the problem is any code external to the loop that uses the results array will likely run <strong><em>before</em></strong> the command sequence finishes.</p>

<p>One way is to set a Cypress alias at the loop end and wait for it.</p>

<p><strong>Test</strong></p>

<pre class="lang-js prettyprint-override"><code>describe('Data-driven tests', () => {

  it('should wait for results', () => {

    const arrayOfTestData = [1,2,3];
    const results = [];

    const functionContainingSingleTest = (dataItem, index) => {

      cy.visit('app/data-driven.html');
      cy.get('input').type(dataItem);

      cy.get('input').invoke('val')
        .then(result => {
          results.push(result[0]);
        });

      if (index === arrayOfTestData.length -1) {
        // Note, the following line executes before all tests finish,
        // but is just queueing a command, which will run after
        // all the tests have completed
        cy.wrap(true).as('done');
      }
    }

    arrayOfTestData.forEach((dataItem, index) =>
      functionContainingSingleTest(dataItem, index)
    );

    // After loop, reached before commands finish.
    console.log(results);  // outputs []

    // Wait for the signal
    cy.get('@done').then(_ => {
      console.log(results);  // outputs ["1", "2", "3"]
    });

  })
})
</code>```

app/data-driven.html

<input />
```

Body:
I am trying to repeat a certain action in cypress defined in doTheAction and then get the results of those repeated actions. When I try Promise.all it immediately resolves to an array of undefined

describe("some test", () => {
  it("for each", () => {
    const data = { a: 1, b: 2 };
    Promise.all(
      Object.entries(data.en).map(([key, value]) =>
        doTheAction(value).then(result => [key, result])
      )
    ).then(result => {
      debugger;
      // array of undefined before the browser did anything
      console.log(result);
    });
  });
});
const doTheAction = text => {
  cy.visit(
    "https://my.site"
  );
  cy.get("some input").type(text);
  return cy
    .get("the result")
    .then(result => result[0].innerText);
};

When I try to chain the actions I get undefined for results when the second action is finished:

describe("some test", () => {
  it("for each", () => {
    const data = { a: 1, b: 2 };
    Object.entries(data).reduce(
      (results, [key, value]) =>
        results.then(results =>
          doTheAction(value).then(
            result =>
              //results is undefined after the second action
              results.concat([[key, result]]) //current result
          )
        ),
      Promise.resolve([]) //initial results
    );
  }).then(results => {
    //never gets here
    console.log(results);
  });
});
const doTheAction = text => {
  cy.visit("https://my.site");
  cy.get("some input").type(text);
  return cy
    .get("the result")
    .then(result => result[0].innerText);
};

Either with Promise.all or chaining the promises the actions will run in the correct order (cypress schedules them and runs them in order) but I don't see how it's possible to get a result out of it.

Body:
Data driven tests are quite easy, one generalized pattern is

const arrayOfTestData = [...];
const arrayOfExpectedResults = [...];

const functionContainingSingleTest = (dataItem, index) => {

  // Commands that use dataItem, and check arrayOfExpectedResults[index]

}

arrayOfTestData.forEach((dataItem, index) =>
  functionContainingSingleTest(dataItem, index)
);
// After loop, reached before commands finish.

What happens is your test en-queue's the commands within the function, as if you had written them sequentially.

If you want to gather results, it becomes more difficult because Commands don't return a usable value. You could try chaining .then(result => results.push(result)), but the problem is any code external to the loop that uses the results array will likely run before the command sequence finishes.

One way is to set a Cypress alias at the loop end and wait for it.

Test

describe('Data-driven tests', () => {

  it('should wait for results', () => {

    const arrayOfTestData = [1,2,3];
    const results = [];

    const functionContainingSingleTest = (dataItem, index) => {

      cy.visit('app/data-driven.html');
      cy.get('input').type(dataItem);

      cy.get('input').invoke('val')
        .then(result => {
          results.push(result[0]);
        });

      if (index === arrayOfTestData.length -1) {
        // Note, the following line executes before all tests finish,
        // but is just queueing a command, which will run after
        // all the tests have completed
        cy.wrap(true).as('done');
      }
    }

    arrayOfTestData.forEach((dataItem, index) =>
      functionContainingSingleTest(dataItem, index)
    );

    // After loop, reached before commands finish.
    console.log(results);  // outputs []

    // Wait for the signal
    cy.get('@done').then(_ => {
      console.log(results);  // outputs ["1", "2", "3"]
    });

  })
})

app/data-driven.html

<input />


来源: stackexchange

问:
Iterate over rows and apply function based on conditions in existing dataframe columns
I have the following script:

```<code>df = pd.DataFrame()
df["Stake"]=[0.25,0.15,0.26,0.30,0.10,0.40,0.32,0.11,0.20,0.25]
df["Odds"]=[2.5,4.0,1.75,2.2,1.85,3.2,1.5,1.2,2.15,1.65]
df["Ftr"]=["H","D","A","H","H","A","D","H","H","A"]
df["Ind"]=[1,2,2,1,3,3,3,1,2,2]

</code>```

which results in:

```<code>    Stake   Odds    Ftr Ind
0   0.25    2.50    H   1
1   0.15    4.00    D   2
2   0.26    1.75    A   2
3   0.30    2.20    H   1
4   0.10    1.85    H   3
5   0.40    3.20    A   3
6   0.32    1.50    D   3
7   0.11    1.20    H   1
8   0.20    2.15    H   2
9   0.25    1.65    A   2
</code>```

I want to create two additional columns "Start Balance" and "End Balance"."Start Balance" in index 0 is equal to 1000. "End balance" is always equal to either:

```<code>"Start Balance" - "Stake" * "Start Balance" + "Stake" x "Start Balance" x "Odds" if column "Ftr" = "H".
</code>```

or,

```<code>"Start Balance" - "Stake" * "Start Balance" if column "Ftr" different than "H".
</code>```

Then the next index "Start balance" becomes the preceding index "End Balance". For example "End Balance" in index 0 becomes "Start Balance" in index 1.

To make things a bit more complicated the "Start Balance" should respect one more condition. If "Ind" column is different than 1 , for example 2 then the "Start Balance" for both rows (indices 1 and 2) is equal to the "End Balance" in index 0. Likewise where "Ind" is 3 then all indices (4,5,6) should have "Start Balance" equal to the "End balance" in index 3. Expected result is:

```<code>    Stake   Odds    Ftr Ind Start Balance   End Balance
0   0.25    2.5      H   1     1000.0          1375.0
1   0.15     4       D   2     1375.0          1168.8
2   0.26    1.75     A   2     1375.0          1017.5
3   0.3     2.2      H   1     1017.5          1383.8
4   0.1     1.85     H   3     1383.8          1501.4
5   0.4     3.2      A   3     1383.8           830.3
6   0.32    1.5      D   3     1383.8           941.0
7   0.11    1.2      H   1      941.0           961.7
8   0.2     2.15     H   2      961.7          1182.9
9   0.25    1.65     A   2      961.7           721.3
</code>```

I have not tried anything since I truly don't know how to approach so many conditions :). Cheers

答:
I can't think of a vectorized function to do what you want so a for loop is the only solution I can think of:

```<code># A temp dataframe to keep track of the End Balance by Ind
# It's empty to start
tmp = pd.DataFrame(columns=['index', 'End Balance']).rename_axis('ind')

for index, row in df.iterrows():
    stake, odds, ind = row['Stake'], row['Odds'], row['Ind']

    if index == 0:
        start_balance = 1000
    elif row['Ind'] == 1:
        start_balance = df.loc[index - 1, 'End Balance']
    else:
        start_balance = tmp.query('ind != @ind').sort_values('index')['End Balance'].iloc[-1]

    end_balance = start_balance * (1 - stake + stake * odds) if row['Ftr'] == 'H' else start_balance * (1 - stake)

    # Keep track of when the current Ind last occurs
    tmp.loc[ind, ['index', 'End Balance']] = [index, end_balance]

    df.loc[index, 'Start Balance'] = start_balance
    df.loc[index, 'End Balance'] = end_balance
</code>```

Result:

```<code>   Stake  Odds Ftr  Ind  Start Balance  End Balance
0   0.25  2.50   H    1    1000.000000  1375.000000
1   0.15  4.00   D    2    1375.000000  1168.750000
2   0.26  1.75   A    2    1375.000000  1017.500000
3   0.30  2.20   H    1    1017.500000  1383.800000
4   0.10  1.85   H    3    1383.800000  1501.423000
5   0.40  3.20   A    3    1383.800000   830.280000
6   0.32  1.50   D    3    1383.800000   940.984000
7   0.11  1.20   H    1     940.984000   961.685648
8   0.20  2.15   H    2     961.685648  1182.873347
9   0.25  1.65   A    2     961.685648   721.264236
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following script:

df = pd.DataFrame()
df["Stake"]=[0.25,0.15,0.26,0.30,0.10,0.40,0.32,0.11,0.20,0.25]
df["Odds"]=[2.5,4.0,1.75,2.2,1.85,3.2,1.5,1.2,2.15,1.65]
df["Ftr"]=["H","D","A","H","H","A","D","H","H","A"]
df["Ind"]=[1,2,2,1,3,3,3,1,2,2]

which results in:

    Stake   Odds    Ftr Ind
0   0.25    2.50    H   1
1   0.15    4.00    D   2
2   0.26    1.75    A   2
3   0.30    2.20    H   1
4   0.10    1.85    H   3
5   0.40    3.20    A   3
6   0.32    1.50    D   3
7   0.11    1.20    H   1
8   0.20    2.15    H   2
9   0.25    1.65    A   2

I want to create two additional columns "Start Balance" and "End Balance"."Start Balance" in index 0 is equal to 1000. "End balance" is always equal to either:

"Start Balance" - "Stake" * "Start Balance" + "Stake" x "Start Balance" x "Odds" if column "Ftr" = "H".

or,

"Start Balance" - "Stake" * "Start Balance" if column "Ftr" different than "H".

Then the next index "Start balance" becomes the preceding index "End Balance". For example "End Balance" in index 0 becomes "Start Balance" in index 1.

To make things a bit more complicated the "Start Balance" should respect one more condition. If "Ind" column is different than 1 , for example 2 then the "Start Balance" for both rows (indices 1 and 2) is equal to the "End Balance" in index 0. Likewise where "Ind" is 3 then all indices (4,5,6) should have "Start Balance" equal to the "End balance" in index 3. Expected result is:

    Stake   Odds    Ftr Ind Start Balance   End Balance
0   0.25    2.5      H   1     1000.0          1375.0
1   0.15     4       D   2     1375.0          1168.8
2   0.26    1.75     A   2     1375.0          1017.5
3   0.3     2.2      H   1     1017.5          1383.8
4   0.1     1.85     H   3     1383.8          1501.4
5   0.4     3.2      A   3     1383.8           830.3
6   0.32    1.5      D   3     1383.8           941.0
7   0.11    1.2      H   1      941.0           961.7
8   0.2     2.15     H   2      961.7          1182.9
9   0.25    1.65     A   2      961.7           721.3

I have not tried anything since I truly don't know how to approach so many conditions :). Cheers

Body:
I can't think of a vectorized function to do what you want so a for loop is the only solution I can think of:

# A temp dataframe to keep track of the End Balance by Ind
# It's empty to start
tmp = pd.DataFrame(columns=['index', 'End Balance']).rename_axis('ind')

for index, row in df.iterrows():
    stake, odds, ind = row['Stake'], row['Odds'], row['Ind']

    if index == 0:
        start_balance = 1000
    elif row['Ind'] == 1:
        start_balance = df.loc[index - 1, 'End Balance']
    else:
        start_balance = tmp.query('ind != @ind').sort_values('index')['End Balance'].iloc[-1]

    end_balance = start_balance * (1 - stake + stake * odds) if row['Ftr'] == 'H' else start_balance * (1 - stake)

    # Keep track of when the current Ind last occurs
    tmp.loc[ind, ['index', 'End Balance']] = [index, end_balance]

    df.loc[index, 'Start Balance'] = start_balance
    df.loc[index, 'End Balance'] = end_balance

Result:

   Stake  Odds Ftr  Ind  Start Balance  End Balance
0   0.25  2.50   H    1    1000.000000  1375.000000
1   0.15  4.00   D    2    1375.000000  1168.750000
2   0.26  1.75   A    2    1375.000000  1017.500000
3   0.30  2.20   H    1    1017.500000  1383.800000
4   0.10  1.85   H    3    1383.800000  1501.423000
5   0.40  3.20   A    3    1383.800000   830.280000
6   0.32  1.50   D    3    1383.800000   940.984000
7   0.11  1.20   H    1     940.984000   961.685648
8   0.20  2.15   H    2     961.685648  1182.873347
9   0.25  1.65   A    2     961.685648   721.264236


问:
Why does the line marked with //1 print 57 instead of 39?
```<code>class X {
    protected int v = 0;

    public X() {
        v += 10;
    }

    public void proc(X p) {
        System.out.println(43);
    }
}

class Y extends X {
    public Y() {
        v += 5;
    }

    public void proc(X p) {
        System.out.println(57);
    }

    public int getV() {
        return v;
    }
}

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        System.out.println(39);
    }
}

class Main {
    public static void main(String[] args) {
        X x = new Z();
        Y y = new Z();
        Z z = new Z();
        x.proc(z);// 1
        System.out.println(y.getV());
    }
}
</code>```

From what I can understand,the method proc() is called on an object of type X that "holds" a type Z and at runtime JVM checks the object's type and overrides the method with the proc() method from Y.But the method parameter is of type Z,why doesn't it call the overloaded method from the Z class?

答:
It happens because you don't override the method 'proc' in Z class. When you overriding the method, you can't use argument, which has a child class of original argument class. If you add @Override on Z.proc(Z p), your code will be not compiled.

Let's imagine that it is possible, then you can use some method from Z class during executing Z.proc(Z p).

```<code>class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        someActions();
        System.out.println(39);
    }

    private void someActions() {
        System.out.println("Some actions");
    }

}
</code>```

Now when you executing

```<code>X x = new Z();
x.proc(new X());
</code>```

What should happens? There is no 'someActions' method in the X class. How it should works? That's why Z.proc(Z p) doesn't override X.proc(X p). Class Z, has two different methods: Z.proc(Z p) and Y.proc(X p).

When you calling

```<code>X x = new Z();
x.proc(new Z());
</code>```

JVM looks for closest overrided or original method with signature 'proc(X)' to Z class (because X class has 'proc(X)' method) finds it in Y class and executing Y.proc(x p). That's why you see '57' in output.

Body:
class X {
    protected int v = 0;

    public X() {
        v += 10;
    }

    public void proc(X p) {
        System.out.println(43);
    }
}

class Y extends X {
    public Y() {
        v += 5;
    }

    public void proc(X p) {
        System.out.println(57);
    }

    public int getV() {
        return v;
    }
}

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        System.out.println(39);
    }
}

class Main {
    public static void main(String[] args) {
        X x = new Z();
        Y y = new Z();
        Z z = new Z();
        x.proc(z);// 1
        System.out.println(y.getV());
    }
}

From what I can understand,the method proc() is called on an object of type X that "holds" a type Z and at runtime JVM checks the object's type and overrides the method with the proc() method from Y.But the method parameter is of type Z,why doesn't it call the overloaded method from the Z class?

Body:
It happens because you don't override the method 'proc' in Z class. When you overriding the method, you can't use argument, which has a child class of original argument class. If you add @Override on Z.proc(Z p), your code will be not compiled.

Let's imagine that it is possible, then you can use some method from Z class during executing Z.proc(Z p).

class Z extends Y {
    public Z() {
        v += 9;
    }

    public void proc(Z p) {
        someActions();
        System.out.println(39);
    }

    private void someActions() {
        System.out.println("Some actions");
    }

}

Now when you executing

X x = new Z();
x.proc(new X());

What should happens? There is no 'someActions' method in the X class. How it should works? That's why Z.proc(Z p) doesn't override X.proc(X p). Class Z, has two different methods: Z.proc(Z p) and Y.proc(X p).

When you calling

X x = new Z();
x.proc(new Z());

JVM looks for closest overrided or original method with signature 'proc(X)' to Z class (because X class has 'proc(X)' method) finds it in Y class and executing Y.proc(x p). That's why you see '57' in output.


问:
Is Logging using FileHandler a bottleneck?
I am considering logging business events in a J2EE web application by using Java logging and FileHandler.

I am wondering whether that could cause a performance bottleneck, since many log records will be written to one file.

What are your experiences and opinions?

Is logging a busy web application to one file with Java logging and FileHandler likely to become performance bottleneck?

答:
It all depends on how much log statements you add. If you add logging after every line of code then performance will must certainly degrade.

Use logging for the important cases, set the correct logging level for your current purposes (testing or actual deployment) and use constructions like

```<code>if (Logger.isDebugEnabled()) {
   Logger.debug("Value is " + costlyOperation()")
}
</code>```

to avoid calling code that is costly to run.

You might also want to check this article

ContentLicense: CC BY-SA 3.0

Body:
It all depends on how much log statements you add. If you add logging after every line of code then performance will must certainly degrade.

Use logging for the important cases, set the correct logging level for your current purposes (testing or actual deployment) and use constructions like

if (Logger.isDebugEnabled()) {
   Logger.debug("Value is " + costlyOperation()")
}

to avoid calling code that is costly to run.

You might also want to check this article


问:
String Replace not changing the String
I try to replace some braces with ids to braces with a name and id like this {20} to {sensor_20}

I have try this:

```<code>print('{{{}}}'.format(sensor.id))
struct.expression.replace('{{{}}}'.format(sensor.id), '{{sensor_{}}}'.format(sensor.id))
print(struct.expression)
</code>```

But in terminal says:

```<code>{19} #String to replace
{19}+{20} #How string is in final
{20} #String to replace
{19}+{20} #How string is in final
</code>```

答:
The documentation of replace says:

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the
  first maxreplace occurrences are replaced.

The string itself is not modified.

Title: String Replace not changing the String

Body:
I try to replace some braces with ids to braces with a name and id like this {20} to {sensor_20}

I have try this:

print('{{{}}}'.format(sensor.id))
struct.expression.replace('{{{}}}'.format(sensor.id), '{{sensor_{}}}'.format(sensor.id))
print(struct.expression)

But in terminal says:

{19} #String to replace
{19}+{20} #How string is in final
{20} #String to replace
{19}+{20} #How string is in final


问:
I need help making a java constructor that akes a string and initilizes the value var with appropriate in
so sorry if my question is dumb but i haven't done java in 2 years. I'm working in my hw right now and i'm one method away from being done. but one of my constructor is wrong and idk where. thanks in advance!
the value variable is a private integer.
so far i have:

```<code>public  FancyInt(String a) {
       value = "";

       a = this.value;
}
</code>```

basically this constructor takes a string and initalizes the value to the appropriate int

答:
If you say that the variable "value" is a Integer, then your code cannot compile because you are assigning a String (in this case, an empty string "") to a Integer.

According to your last sentence, I think your code should look like this:

```<code>public FancyInt(String a) {

     this.value = isInteger(a)? Integer.parseInt(a) : 0;
}

private boolean isInteger(String val) {

    try{
        Integer.parseInt(val);
        return true;
    }
    catch (NumberFormatException e) {
        return false;
    }
}
</code>```

You can change the implementation of the isInteger method, in this link Determine if a String is an Integer in Java you have multiple options that could help you.

Body:
so sorry if my question is dumb but i haven't done java in 2 years. I'm working in my hw right now and i'm one method away from being done. but one of my constructor is wrong and idk where. thanks in advance!
the value variable is a private integer.
so far i have:

public  FancyInt(String a) {
       value = "";

       a = this.value;
}

basically this constructor takes a string and initalizes the value to the appropriate int

Body:
If you say that the variable "value" is a Integer, then your code cannot compile because you are assigning a String (in this case, an empty string "") to a Integer.

According to your last sentence, I think your code should look like this:

public FancyInt(String a) {

     this.value = isInteger(a)? Integer.parseInt(a) : 0;
}

private boolean isInteger(String val) {

    try{
        Integer.parseInt(val);
        return true;
    }
    catch (NumberFormatException e) {
        return false;
    }
}

You can change the implementation of the isInteger method, in this link Determine if a String is an Integer in Java you have multiple options that could help you.


问:
In Ansible loop, test existence of files from registered results
I have several files that I need to backup in different directories.  I have tried the code below and not working for me.</p>

```<code>  vars:
    file_vars:
      - {name: /file1}
      - {name: /etc/file2}
      - {name: /etc/file/file3}

  tasks:

  - name: "Checking if config files exists"
    stat:
      path: "{{ item.name }}"
    with_items: "{{ file_vars }}"
    register: stat_result

  - name: Backup Files
    copy: src={{ item.name }} dest={{ item.name }}{{ ansible_date_time.date }}.bak
    with_items: "{{ file_vars }}"
    remote_src: yes
    when: stat_result.stat.exists == True
</code>```

答:
Please try using below worked for me:

```<code>---
- name: Copy files
  hosts: localhost
  become: yes
  become_user: root
  vars_files:
    - files.yml

  tasks:

  - name: "Checking if config files exists"
    stat:
    path: "{{ item }}"
    with_items: "{{ files }}"
    register: stat_result

  - name: Ansible
    debug:
      msg: "{{ stat_result }}"

  - name: Backup Files
    copy:
      src: "{{ item }}"
      dest: "{{ item.bak }}"
    with_items: "{{ files }}"
    when: stat_result == "True"
</code>```

and files.yml will look like:

```<code>---
files:
   - /tmp/file1
   - /tmp/file2
</code>```

you can check you playbook syntax using below command:
    ansible-playbook copy.yml --syntax-check

Also you do dry run your playbook before actual execution.
    ansible-playbook -i localhost copy.yml --check

Body:
I have several files that I need to backup in different directories.  I have tried the code below and not working for me.

  vars:
    file_vars:
      - {name: /file1}
      - {name: /etc/file2}
      - {name: /etc/file/file3}

  tasks:

  - name: "Checking if config files exists"
    stat:
      path: "{{ item.name }}"
    with_items: "{{ file_vars }}"
    register: stat_result

  - name: Backup Files
    copy: src={{ item.name }} dest={{ item.name }}{{ ansible_date_time.date }}.bak
    with_items: "{{ file_vars }}"
    remote_src: yes
    when: stat_result.stat.exists == True

Body:
Please try using below worked for me:

---
- name: Copy files
  hosts: localhost
  become: yes
  become_user: root
  vars_files:
    - files.yml

  tasks:

  - name: "Checking if config files exists"
    stat:
    path: "{{ item }}"
    with_items: "{{ files }}"
    register: stat_result

  - name: Ansible
    debug:
      msg: "{{ stat_result }}"

  - name: Backup Files
    copy:
      src: "{{ item }}"
      dest: "{{ item.bak }}"
    with_items: "{{ files }}"
    when: stat_result == "True"

and files.yml will look like:

---
files:
   - /tmp/file1
   - /tmp/file2

you can check you playbook syntax using below command:
    ansible-playbook copy.yml --syntax-check

Also you do dry run your playbook before actual execution.
    ansible-playbook -i localhost copy.yml --check


问:
Invalid index to scalar variable error in hough circles
Please check this code:

```<code>import cv2
import numpy as np
import numpy.linalg as la
import time

cap = cv2.VideoCapture("3.mp4")

fgbg = cv2.createBackgroundSubtractorMOG2()

while(True):
    _, frame = cap.read()
    if _ == False:
        print("No frame left")
        break

    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    fgmask = fgbg.apply(gray_frame)
    fgmask = cv2.resize(fgmask, (640, 360))

    gray_frame = cv2.medianBlur(fgmask, 3)
    #gray_frame = cv2.GaussianBlur(gray_frame, (3, 3), 5)
    erode_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dilate_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    erosion = cv2.erode(gray_frame, erode_element, iterations = 3)
    dilation = cv2.dilate(erosion, dilate_element, iterations =  2)
    cv2.imshow("sub", dilation)
    cv2.imshow('abc', fgmask)

    rows = gray_frame.shape[0]
    circles = cv2.HoughCircles(dilation, cv2.HOUGH_GRADIENT, 1, rows / 0.01, 200, 100, 20, 10)
    print(circles)
    if circles is not None:
        for i in circles[0, :]:
            center = (i[0], i[1])
            cv2.circle(frame, center,  5, (0,0,255))

    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
</code>```

Issue is with this line:

```<code>circles = cv2.HoughCircles(dilation, cv2.HOUGH_GRADIENT, 1, rows / 0.01, 200, 100, 20, 10)
</code>```

The error is:

```<code>center = (i[0], i[1])
IndexError: invalid index to scalar variable.
</code>```

I cant get to know whats happening. Parameters for hough circles are taken from opencv documentation. I wanted to play around with it but cant get it to run even
for a single time.

Thanks.

答:
Just put a check for 1 dimensional np.array.

Looking at this answer just change

```<code>if circles is not None:
</code>```

To

```<code>if circles is not None and circles[0][0].ndim == 1:
</code>```

Body:
Please check this code:

import cv2
import numpy as np
import numpy.linalg as la
import time

cap = cv2.VideoCapture("3.mp4")

fgbg = cv2.createBackgroundSubtractorMOG2()

while(True):
    _, frame = cap.read()
    if _ == False:
        print("No frame left")
        break

    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    fgmask = fgbg.apply(gray_frame)
    fgmask = cv2.resize(fgmask, (640, 360))

    gray_frame = cv2.medianBlur(fgmask, 3)
    #gray_frame = cv2.GaussianBlur(gray_frame, (3, 3), 5)
    erode_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dilate_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    erosion = cv2.erode(gray_frame, erode_element, iterations = 3)
    dilation = cv2.dilate(erosion, dilate_element, iterations =  2)
    cv2.imshow("sub", dilation)
    cv2.imshow('abc', fgmask)

    rows = gray_frame.shape[0]
    circles = cv2.HoughCircles(dilation, cv2.HOUGH_GRADIENT, 1, rows / 0.01, 200, 100, 20, 10)
    print(circles)
    if circles is not None:
        for i in circles[0, :]:
            center = (i[0], i[1])
            cv2.circle(frame, center,  5, (0,0,255))

    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()

Issue is with this line:

circles = cv2.HoughCircles(dilation, cv2.HOUGH_GRADIENT, 1, rows / 0.01, 200, 100, 20, 10)

The error is:

center = (i[0], i[1])
IndexError: invalid index to scalar variable.

I cant get to know whats happening. Parameters for hough circles are taken from opencv documentation. I wanted to play around with it but cant get it to run even
for a single time.

Thanks.

Body:
Just put a check for 1 dimensional np.array.

Looking at this answer just change

if circles is not None:

To

if circles is not None and circles[0][0].ndim == 1:


问:
How to re-assign a variable in a function in Racket?
I want to initialize acc as 0. I want to add the length of each element of lst. I understand this is not the easiest way to do it, but I simplified my real code for this example. How exactly can I accumulate the total length and assign it to acc.

Also, I am trying to avoid using set! or other ! commands.

```<code>(define (total-length-list lst)
  (define acc 0)
    (for/list ([i lst])
      (cond [(= 0 (length i)) (+ acc 0)]
            [(= 1 (length i)) (+ acc 1)]
            [(= 2 (length i)) (+ acc 2)]))
  acc)
</code>```

答:
From your description I would implement it with apply and map.

```<code>;; total-length-list : [Listof [Listof Any]] -> Natural
(define (total-length-list lst)
  (apply + (map length lst)))
</code>```

If you want to use a loop, then for/sum is good.

```<code>;; total-length-list : [Listof [Listof Any]] -> Natural
(define (total-length-list lst)
  (for/sum ([i lst])
    (length i)))
</code>```

If you want to use an accumulator, for/fold can do that.

```<code>;; total-length-list : [Listof [Listof Any]] -> Natural
(define (total-length-list lst)
  (for/fold ([acc 0]) ([i lst])
    (+ acc (length i))))
</code>```

And if you still want that cond for some reason, you can put that inside the for/fold, but make sure to have an else case that returns the accumulator unchanged.

```<code>;; total-length-list : [Listof [Listof Any]] -> Natural
(define (total-length-list lst)
  (for/fold ([acc 0]) ([i lst])
    (cond [(= 0 (length i)) (+ acc 0)]
          [(= 1 (length i)) (+ acc 1)]
          [(= 2 (length i)) (+ acc 2)]
          [else             acc])))
</code>```

If you leave out the [else acc] in the cond you might get an error about #<void>.

But simpler is better, so I would recommend either using apply with map, or using for/sum, no accumulators or conditionals necessary.

From an imperative programmer's point of view,

```<code>(for/fold ([acc init]) ([elem lst])
  body)
</code>```

returns the same value as

```<code>(define acc init)
(for ([elem lst])
  (set! acc body))
acc
</code>```

However, for/fold does it without any mutation/set! necessary.

Body:
I want to initialize acc as 0. I want to add the length of each element of lst. I understand this is not the easiest way to do it, but I simplified my real code for this example. How exactly can I accumulate the total length and assign it to acc.

Also, I am trying to avoid using set! or other ! commands.

(define (total-length-list lst)
  (define acc 0)
    (for/list ([i lst])
      (cond [(= 0 (length i)) (+ acc 0)]
            [(= 1 (length i)) (+ acc 1)]
            [(= 2 (length i)) (+ acc 2)]))
  acc)

Body:
From your description I would implement it with apply and map.

;; total-length-list : [Listof [Listof Any]] -> Natural
(define (total-length-list lst)
  (apply + (map length lst)))

If you want to use a loop, then for/sum is good.

;; total-length-list : [Listof [Listof Any]] -> Natural
(define (total-length-list lst)
  (for/sum ([i lst])
    (length i)))

If you want to use an accumulator, for/fold can do that.

;; total-length-list : [Listof [Listof Any]] -> Natural
(define (total-length-list lst)
  (for/fold ([acc 0]) ([i lst])
    (+ acc (length i))))

And if you still want that cond for some reason, you can put that inside the for/fold, but make sure to have an else case that returns the accumulator unchanged.

;; total-length-list : [Listof [Listof Any]] -> Natural
(define (total-length-list lst)
  (for/fold ([acc 0]) ([i lst])
    (cond [(= 0 (length i)) (+ acc 0)]
          [(= 1 (length i)) (+ acc 1)]
          [(= 2 (length i)) (+ acc 2)]
          [else             acc])))

If you leave out the [else acc] in the cond you might get an error about #<void>.

But simpler is better, so I would recommend either using apply with map, or using for/sum, no accumulators or conditionals necessary.

From an imperative programmer's point of view,

(for/fold ([acc init]) ([elem lst])
  body)

returns the same value as

(define acc init)
(for ([elem lst])
  (set! acc body))
acc

However, for/fold does it without any mutation/set! necessary.


问:
c# generics, passing class
I just can't figure out how to write an equivalent interface in c#.

Java:

```<code>public interface DAO {
    <T> T find(Class<T> c, Object key);

    <T> List<T> get(Class<T> c);

    <T> void persist(T object);
}
</code>```

This is my attempt so far in c#, problem is i need the Class to call the  dataclassesdatacontext.GetTable<Class here>().ToList();:

```<code>interface IDAO
{
    T Find<T>(object key);

    List<T> Get<T>(T c);

    void Persist<T>(T obj);
}
</code>```

I want to implement it like this:

public List<T> Get<T>()
        {
            return _dbx.GetTable<T>().ToList();
        }

where _dbx is the dataclassdatacontext (linq to sql).
But i get a red line under T which says:
The type 'T' must be a reference type in order to use it as a parameter.

答:
The generic parameter could be placed on the interface definition:</p>

```<code>public interface IDAO<T>
{
    T Find(object key);
    List<T> Get(T c);
    void Persist(T obj);
}
</code>```

Title: c# generics, passing class

Body:
I just can't figure out how to write an equivalent interface in c#.

Java:

public interface DAO {
    <T> T find(Class<T> c, Object key);

    <T> List<T> get(Class<T> c);

    <T> void persist(T object);
}

This is my attempt so far in c#, problem is i need the Class to call the  dataclassesdatacontext.GetTable<Class here>().ToList();:

interface IDAO
{
    T Find<T>(object key);

    List<T> Get<T>(T c);

    void Persist<T>(T obj);
}

I want to implement it like this:

public List<T> Get<T>()
        {
            return _dbx.GetTable<T>().ToList();
        }

where _dbx is the dataclassdatacontext (linq to sql).
But i get a red line under T which says:
The type 'T' must be a reference type in order to use it as a parameter.

Body:
The generic parameter could be placed on the interface definition:

public interface IDAO<T>
{
    T Find(object key);
    List<T> Get(T c);
    void Persist(T obj);
}


问:
When to use as.numeric and as.factor in R
I don't understand the difference between as.numeric and as.factor in R. When do I want to use each?

Example code:

```<code>data2$Response <- as.factor(data2$Response)
data2$VOT <- as.factor(data2$VOT)
data2$Block <- as.factor(data2$Block)
</code>```

What will this do, exactly?

答:
Factors (with as.factor) are variables that have discrete values, which may or may not be ordered.  In other areas of science outside R they're often called categorical values.  For example North South East and West could be factors.

Numerics (with as.numeric) are numbers, with infinite other numbers between them.  So for example 5 is a number, as is 6, but so are 5.01, 5.001, 5.0001 etc.

To build a reproducible example similar to yours

```<code>data2 <- data.frame(numbers = c(1,2,3,4), text = c("one", "two", "three", "four"))
  numbers  text
1       1   one
2       2   two
3       3 three
4       4  four
</code>```

I can use the numbers column to do math:

```<code>library(dplyr)
data2 %>%
mutate(square = numbers * numbers)
  numbers  text square
1       1   one      1
2       2   two      4
3       3 three      9
4       4  four     16
</code>```

If I convert numbers to a factor, using as.factor though

```<code>data2$numbers <- as.factor(data2$numbers)
</code>```

I'll no longer be able to do math (like squaring) using the values in data2$numbers because they're not numeric anymore.  They're factor levels named 1, 2, 3, 4, not the numbers 1, 2, 3, 4.  They could just as easily be named North South East and West, and West * West doesn't make any sense.

So to sum up, you'll want to use as.numeric when whatever you're passing are actually numbers, but perhaps coded as strings ("1", "2", "3", "4") or something you'd like to represent as numbers (in the case of TRUE or FALSE values for example).  You'd like to use as.factor when you'd like to convert whatever you're passing to named categories, which may or may not have an order.

Does that answer your question?

Body:
I don't understand the difference between as.numeric and as.factor in R. When do I want to use each?

Example code:

data2$Response <- as.factor(data2$Response)
data2$VOT <- as.factor(data2$VOT)
data2$Block <- as.factor(data2$Block)

What will this do, exactly?

Body:
Factors (with as.factor) are variables that have discrete values, which may or may not be ordered.  In other areas of science outside R they're often called categorical values.  For example North South East and West could be factors.

Numerics (with as.numeric) are numbers, with infinite other numbers between them.  So for example 5 is a number, as is 6, but so are 5.01, 5.001, 5.0001 etc.

To build a reproducible example similar to yours

data2 <- data.frame(numbers = c(1,2,3,4), text = c("one", "two", "three", "four"))
  numbers  text
1       1   one
2       2   two
3       3 three
4       4  four

I can use the numbers column to do math:

library(dplyr)
data2 %>%
mutate(square = numbers * numbers)
  numbers  text square
1       1   one      1
2       2   two      4
3       3 three      9
4       4  four     16

If I convert numbers to a factor, using as.factor though

data2$numbers <- as.factor(data2$numbers)

I'll no longer be able to do math (like squaring) using the values in data2$numbers because they're not numeric anymore.  They're factor levels named 1, 2, 3, 4, not the numbers 1, 2, 3, 4.  They could just as easily be named North South East and West, and West * West doesn't make any sense.

So to sum up, you'll want to use as.numeric when whatever you're passing are actually numbers, but perhaps coded as strings ("1", "2", "3", "4") or something you'd like to represent as numbers (in the case of TRUE or FALSE values for example).  You'd like to use as.factor when you'd like to convert whatever you're passing to named categories, which may or may not have an order.

Does that answer your question?


问:
Pandas DataFrame find closest index in previous rows where condition is met
I have the following df1 dataframe:

```<code>    t       A
0   23:00   2
1   23:01   1
2   23:02   2
3   23:03   2
4   23:04   6
5   23:05   5
6   23:06   4
7   23:07   9
8   23:08   7
9   23:09   10
10  23:10   8
</code>```

For each t (increments simplified here, not uniformly distributed in real life), I would like to find, if any, the most recent time tr within the previous 5 min where A(t)- A(tr) >= 4. I want to get:

```<code>    t       A    tr
0   23:00   2
1   23:01   1
2   23:02   2
3   23:03   2
4   23:04   6    23:03
5   23:05   5    23:01
6   23:06   4
7   23:07   9    23:06
8   23:08   7
9   23:09   10   23:06
10  23:10   8    23:06
</code>```

Currently, I can use shift(-1) to compare each row to the previous row like cond = df1['A'] >= df1['A'].shift(-1) + 4.

How can I look further in time?

答:
Assuming your data is continuous by the minute, then you can do usual shift:

```<code>df1['t'] = pd.to_timedelta(df1['t'].add(':00'))

df = pd.DataFrame({i:df1.A - df1.A.shift(i) >= 4 for i in range(1,5)})

df1['t'] - pd.to_timedelta('1min') * df.idxmax(axis=1).where(df.any(1))
</code>```

Output:

```<code>0         NaT
1         NaT
2         NaT
3         NaT
4    23:03:00
5    23:01:00
6         NaT
7    23:06:00
8         NaT
9    23:06:00
10   23:06:00
dtype: timedelta64[ns]
</code>```

Body:
I have the following df1 dataframe:

    t       A
0   23:00   2
1   23:01   1
2   23:02   2
3   23:03   2
4   23:04   6
5   23:05   5
6   23:06   4
7   23:07   9
8   23:08   7
9   23:09   10
10  23:10   8

For each t (increments simplified here, not uniformly distributed in real life), I would like to find, if any, the most recent time tr within the previous 5 min where A(t)- A(tr) >= 4. I want to get:

    t       A    tr
0   23:00   2
1   23:01   1
2   23:02   2
3   23:03   2
4   23:04   6    23:03
5   23:05   5    23:01
6   23:06   4
7   23:07   9    23:06
8   23:08   7
9   23:09   10   23:06
10  23:10   8    23:06

Currently, I can use shift(-1) to compare each row to the previous row like cond = df1['A'] >= df1['A'].shift(-1) + 4.

How can I look further in time?

Body:
Assuming your data is continuous by the minute, then you can do usual shift:

df1['t'] = pd.to_timedelta(df1['t'].add(':00'))

df = pd.DataFrame({i:df1.A - df1.A.shift(i) >= 4 for i in range(1,5)})

df1['t'] - pd.to_timedelta('1min') * df.idxmax(axis=1).where(df.any(1))

Output:

0         NaT
1         NaT
2         NaT
3         NaT
4    23:03:00
5    23:01:00
6         NaT
7    23:06:00
8         NaT
9    23:06:00
10   23:06:00
dtype: timedelta64[ns]


问:
Cannot create JDBC driver of class '' for connect URL 'null' Tomcat 9, Oracle 12c, JDK 8,
I have a simple web service that is trying to open a connection to the database.

I am using jax-ws, Oracle 12c DB, Tomcat 9, Java 8.

Can anyone post the correct way to do this?

So far I've downloaded ojdbc7.jar and ucp.jar into the $TOMCAT_HOME/lib directory.

What goes in applicationPath/META-INF/web.xml ?

Right now I have the following:

```<code>  <resource-ref>
    <res-ref-name>jdbc/UCPPool</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>
</code>```

What goes in TOMCAT_HOME/conf/server.xml ?

Right now I have the following:

```<code><context docbase="demods" path="/demods" reloadable="true">
  <Resource
       name="jdbc/UCPPool"
       auth="Container"
       factory="oracle.ucp.jdbc.PoolDataSourceImpl"
       type="oracle.ucp.jdbc.PoolDataSource"
       description="Pas testing UCP Pool in Tomcat"
       connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
       minPoolSize="2"
       maxPoolSize="5"
       inactiveConnectionTimeout="20"
       user="test"
       password="test"
       url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=oracleDB12c)(PORT=1563))(CONNECT_DATA=(SERVICE_NAME=PPS)))"
       connectionPoolName="UCPPool"
       validateConnectionOnBorrow="true"
       sqlForValidateConnection="select 1 from DUAL" />
 </context>
</code>```

What goes in TOMCAT_HOME/conf/context.xml ?

I don't have anything in this file right now.

Here is the code that I am using to setup the JDBC connection:

```<code>         Context ctx = new InitialContext();
         Context envContext = (Context) ctx.lookup("java:comp/env");
         DataSource ds  = (DataSource) envContext.lookup("jdbc/UCPPool");
         Connection conn = null;
         try {
             conn = ds.getConnection();
         }
         catch (SQLException e) {
             return e.getMessage();
         }
</code>```

The message returned by the web service is:

```<code>"Cannot create JDBC driver of class '' for connect URL 'null'"
</code>```

What am I doing wrong?

Thanks in advance!

答: Can you take a look at a github example and follow that to build your Tomcat applicaiton? </p>

Body:
I have a simple web service that is trying to open a connection to the database.

I am using jax-ws, Oracle 12c DB, Tomcat 9, Java 8.

Can anyone post the correct way to do this?

So far I've downloaded ojdbc7.jar and ucp.jar into the $TOMCAT_HOME/lib directory.

What goes in applicationPath/META-INF/web.xml ?

Right now I have the following:

  <resource-ref>
    <res-ref-name>jdbc/UCPPool</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

What goes in TOMCAT_HOME/conf/server.xml ?

Right now I have the following:

<context docbase="demods" path="/demods" reloadable="true">
  <Resource
       name="jdbc/UCPPool"
       auth="Container"
       factory="oracle.ucp.jdbc.PoolDataSourceImpl"
       type="oracle.ucp.jdbc.PoolDataSource"
       description="Pas testing UCP Pool in Tomcat"
       connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
       minPoolSize="2"
       maxPoolSize="5"
       inactiveConnectionTimeout="20"
       user="test"
       password="test"
       url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=oracleDB12c)(PORT=1563))(CONNECT_DATA=(SERVICE_NAME=PPS)))"
       connectionPoolName="UCPPool"
       validateConnectionOnBorrow="true"
       sqlForValidateConnection="select 1 from DUAL" />
 </context>

What goes in TOMCAT_HOME/conf/context.xml ?

I don't have anything in this file right now.

Here is the code that I am using to setup the JDBC connection:

         Context ctx = new InitialContext();
         Context envContext = (Context) ctx.lookup("java:comp/env");
         DataSource ds  = (DataSource) envContext.lookup("jdbc/UCPPool");
         Connection conn = null;
         try {
             conn = ds.getConnection();
         }
         catch (SQLException e) {
             return e.getMessage();
         }

The message returned by the web service is:

"Cannot create JDBC driver of class '' for connect URL 'null'"

What am I doing wrong?

Thanks in advance!


问:
CUDA unified memory and Windows 10
While using CudaMallocManaged() to allocate an array of structs with arrays inside, I'm getting the error "out of memory" even though I have enough free memory. Here's some code that replicates my problem:

```<code>#include <iostream>
#include <cuda.h>

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

#define N 100000
#define ARR_SZ 100

struct Struct
{
    float* arr;
};

int main()
{
    Struct* struct_arr;

    gpuErrchk( cudaMallocManaged((void**)&struct_arr, sizeof(Struct)*N) );
    for(int i = 0; i < N; ++i)
        gpuErrchk( cudaMallocManaged((void**)&(struct_arr[i].arr), sizeof(float)*ARR_SZ) ); //out of memory...

    for(int i = 0; i < N; ++i)
        cudaFree(struct_arr[i].arr);
    cudaFree(struct_arr);

    /*float* f;
    gpuErrchk( cudaMallocManaged((void**)&f, sizeof(float)*N*ARR_SZ) ); //this works ok
    cudaFree(f);*/

    return 0;
}
</code>```

There doesn't seem to be a problem when I call cudaMallocManaged() once to allocate a single chunk of memory, as I'm showing in the last piece of commented code.
I have a GeForce GTX 1070 Ti, and I'm using Windows 10. A friend tried to compile the same code in a PC with Linux and it worked correctly, while it had the same issue in another PC with Windows 10. WDDM TDR is deactivated.
Any help would be appreciated. Thanks.

答:
There is an allocation granularity.

This means that if you ask for 1 byte, or 400 bytes, what is actually used up is something like <s>4096 </s> 65536 bytes. So a bunch of very small allocations will actually use up memory at a much faster rate than what you would predict based on the requested allocation size. The solution is to not make very small allocations, but instead to allocate in larger chunks.

An alternative strategy here would also be to flatten your allocation, and carve out pieces from it for each of your arrays:

```<code>#include <iostream>
#include <cstdio>

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

#define N 100000
#define ARR_SZ 100

struct Struct
{
    float* arr;
};

int main()
{
    Struct* struct_arr;
    float* f;

    gpuErrchk( cudaMallocManaged((void**)&struct_arr, sizeof(Struct)*N) );
    gpuErrchk( cudaMallocManaged((void**)&f, sizeof(float)*N*ARR_SZ) );
    for(int i = 0; i < N; ++i)
        struct_arr[i].arr = f+i*ARR_SZ;
    cudaFree(struct_arr);
    cudaFree(f);

    return 0;
}
</code>```

ARR_SZ divisible by 4 means the various created pointers can also be up-cast to larger vector types e.g. float2 or float4, if your use had any intention of doing that.

A possible reason the original code works on linux is because managed memory on linux, in a proper setup, can oversubscribe the GPU physical memory.  The result is the actual allocation limit is much higher than what the GPU on-board memory would suggest.  It might also be that the linux case has a bit more free memory, or perhaps the allocation granularity on linux is different (smaller).

Based on a question in the comments, I decided to estimate the allocation granularity, using this code:

```<code>#include <iostream>
#include <cstdio>

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char* file, int line, bool abort = true)
{
    if (code != cudaSuccess)
    {
        fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
        if (abort) exit(code);
    }
}

#define N 100000
#define ARR_SZ 100

struct Struct
{
    float* arr;
};

int main()
{
    Struct* struct_arr;
    //float* f;

    gpuErrchk(cudaMallocManaged((void**)& struct_arr, sizeof(Struct) * N));
#if 0
    gpuErrchk(cudaMallocManaged((void**)& f, sizeof(float) * N * ARR_SZ));
    for (int i = 0; i < N; ++i)
        struct_arr[i].arr = f + i * ARR_SZ;
#else
    size_t fre, tot;
    gpuErrchk(cudaMemGetInfo(&fre, &tot));
    std::cout << "Free: " << fre << " total: " << tot << std::endl;
    for (int i = 0; i < N; ++i)
        gpuErrchk(cudaMallocManaged((void**) & (struct_arr[i].arr), sizeof(float) * ARR_SZ));
    gpuErrchk(cudaMemGetInfo(&fre, &tot));
    std::cout << "Free: " << fre << " total: " << tot << std::endl;

    for (int i = 0; i < N; ++i)
        cudaFree(struct_arr[i].arr);
#endif
    cudaFree(struct_arr);
    //cudaFree(f);

    return 0;
}
</code>```

When I compile a debug project with that code, and run that on a windows 10 desktop with RTX 2070 GPU (8GB memory, same as GTX 1070 Ti) I get the following output:

```<code>Microsoft Windows [Version 10.0.17763.973]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\Robert Crovella>cd C:\Users\Robert Crovella\source\repos\test12\x64\Debug

C:\Users\Robert Crovella\source\repos\test12\x64\Debug>test12
Free: 7069866393 total: 8589934592
Free: 516266393 total: 8589934592

C:\Users\Robert Crovella\source\repos\test12\x64\Debug>test12
Free: 7069866393 total: 8589934592
Free: 516266393 total: 8589934592

C:\Users\Robert Crovella\source\repos\test12\x64\Debug>
</code>```

Note that on my machine there is only 0.5GB of reported free memory left after the 100,000 allocations.  So if for any reason your 8GB GPU starts out with less free memory (entirely possible) you may run into an out-of-memory error, even though I did not.

The calculation of the allocation granularity is as follows:

```<code>7069866393 - 516266393 / 100000 = 65536 bytes per allocation(!)
</code>```

So my previous estimate of 4096 bytes per allocation was way off, by at least 1 order of magnitude, on my machine/test setup.

The allocation granularity may vary based on:

windows or linux

WDDM or TCC

x86 or Power9

managed vs ordinary cudaMalloc

possibly other factors (e.g. CUDA version)

so my advice to future readers would not be to assume that it is always 65536 bytes per allocation, minimum.

Title: CUDA unified memory and Windows 10

Body:
While using CudaMallocManaged() to allocate an array of structs with arrays inside, I'm getting the error "out of memory" even though I have enough free memory. Here's some code that replicates my problem:

#include <iostream>
#include <cuda.h>

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

#define N 100000
#define ARR_SZ 100

struct Struct
{
    float* arr;
};

int main()
{
    Struct* struct_arr;

    gpuErrchk( cudaMallocManaged((void**)&struct_arr, sizeof(Struct)*N) );
    for(int i = 0; i < N; ++i)
        gpuErrchk( cudaMallocManaged((void**)&(struct_arr[i].arr), sizeof(float)*ARR_SZ) ); //out of memory...

    for(int i = 0; i < N; ++i)
        cudaFree(struct_arr[i].arr);
    cudaFree(struct_arr);

    /*float* f;
    gpuErrchk( cudaMallocManaged((void**)&f, sizeof(float)*N*ARR_SZ) ); //this works ok
    cudaFree(f);*/

    return 0;
}

There doesn't seem to be a problem when I call cudaMallocManaged() once to allocate a single chunk of memory, as I'm showing in the last piece of commented code.
I have a GeForce GTX 1070 Ti, and I'm using Windows 10. A friend tried to compile the same code in a PC with Linux and it worked correctly, while it had the same issue in another PC with Windows 10. WDDM TDR is deactivated.
Any help would be appreciated. Thanks.

Body:
There is an allocation granularity.

This means that if you ask for 1 byte, or 400 bytes, what is actually used up is something like <s>4096 </s> 65536 bytes. So a bunch of very small allocations will actually use up memory at a much faster rate than what you would predict based on the requested allocation size. The solution is to not make very small allocations, but instead to allocate in larger chunks.

An alternative strategy here would also be to flatten your allocation, and carve out pieces from it for each of your arrays:

#include <iostream>
#include <cstdio>

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
   if (code != cudaSuccess)
   {
      fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
      if (abort) exit(code);
   }
}

#define N 100000
#define ARR_SZ 100

struct Struct
{
    float* arr;
};

int main()
{
    Struct* struct_arr;
    float* f;

    gpuErrchk( cudaMallocManaged((void**)&struct_arr, sizeof(Struct)*N) );
    gpuErrchk( cudaMallocManaged((void**)&f, sizeof(float)*N*ARR_SZ) );
    for(int i = 0; i < N; ++i)
        struct_arr[i].arr = f+i*ARR_SZ;
    cudaFree(struct_arr);
    cudaFree(f);

    return 0;
}

ARR_SZ divisible by 4 means the various created pointers can also be up-cast to larger vector types e.g. float2 or float4, if your use had any intention of doing that.

A possible reason the original code works on linux is because managed memory on linux, in a proper setup, can oversubscribe the GPU physical memory.  The result is the actual allocation limit is much higher than what the GPU on-board memory would suggest.  It might also be that the linux case has a bit more free memory, or perhaps the allocation granularity on linux is different (smaller).

Based on a question in the comments, I decided to estimate the allocation granularity, using this code:

#include <iostream>
#include <cstdio>

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char* file, int line, bool abort = true)
{
    if (code != cudaSuccess)
    {
        fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
        if (abort) exit(code);
    }
}

#define N 100000
#define ARR_SZ 100

struct Struct
{
    float* arr;
};

int main()
{
    Struct* struct_arr;
    //float* f;

    gpuErrchk(cudaMallocManaged((void**)& struct_arr, sizeof(Struct) * N));
#if 0
    gpuErrchk(cudaMallocManaged((void**)& f, sizeof(float) * N * ARR_SZ));
    for (int i = 0; i < N; ++i)
        struct_arr[i].arr = f + i * ARR_SZ;
#else
    size_t fre, tot;
    gpuErrchk(cudaMemGetInfo(&fre, &tot));
    std::cout << "Free: " << fre << " total: " << tot << std::endl;
    for (int i = 0; i < N; ++i)
        gpuErrchk(cudaMallocManaged((void**) & (struct_arr[i].arr), sizeof(float) * ARR_SZ));
    gpuErrchk(cudaMemGetInfo(&fre, &tot));
    std::cout << "Free: " << fre << " total: " << tot << std::endl;

    for (int i = 0; i < N; ++i)
        cudaFree(struct_arr[i].arr);
#endif
    cudaFree(struct_arr);
    //cudaFree(f);

    return 0;
}

When I compile a debug project with that code, and run that on a windows 10 desktop with RTX 2070 GPU (8GB memory, same as GTX 1070 Ti) I get the following output:

Microsoft Windows [Version 10.0.17763.973]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\Robert Crovella>cd C:\Users\Robert Crovella\source\repos\test12\x64\Debug

C:\Users\Robert Crovella\source\repos\test12\x64\Debug>test12
Free: 7069866393 total: 8589934592
Free: 516266393 total: 8589934592

C:\Users\Robert Crovella\source\repos\test12\x64\Debug>test12
Free: 7069866393 total: 8589934592
Free: 516266393 total: 8589934592

C:\Users\Robert Crovella\source\repos\test12\x64\Debug>

Note that on my machine there is only 0.5GB of reported free memory left after the 100,000 allocations.  So if for any reason your 8GB GPU starts out with less free memory (entirely possible) you may run into an out-of-memory error, even though I did not.

The calculation of the allocation granularity is as follows:

7069866393 - 516266393 / 100000 = 65536 bytes per allocation(!)

So my previous estimate of 4096 bytes per allocation was way off, by at least 1 order of magnitude, on my machine/test setup.

The allocation granularity may vary based on:

windows or linux

WDDM or TCC

x86 or Power9

managed vs ordinary cudaMalloc

possibly other factors (e.g. CUDA version)

so my advice to future readers would not be to assume that it is always 65536 bytes per allocation, minimum.


问:
Getting AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint' in Django 1.11
I am using Django 1.11 and when trying to import UniqueConstraint, I am getting this terrible

AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint'

error. I don't want to step down to unique_together, because it seems like being depreciated. So why I get this error in the latest version of Django ?!

I am importing it the following way:

```<code>from django.db import models

class CalendarAccount(models.Model):

    class Meta:
        managed = False
        db_table = 'my_table'
        constraints = [
            models.UniqueConstraint(...),
        ]
</code>```

答:
That doesn't exist yet if you're using django 1.11.

If you move to 2.2, use UniqueConstraint, but by then you'll have set unique_together and it isn't deprecated yet, so no point changing it.

Django 1.11 docs for unique_together

As a pointer, by looking at the available versions of the documentation in the bottom right, you can see if what you're reading is relevant to the version of django you are using.

The docs for UniqueConstraint show only 2.2, 3.0 and dev so that isn't available prior to 2.2.

Anyway, docs are here; https://docs.djangoproject.com/en/1.11/ref/models/options/#unique-together

Body:
I am using Django 1.11 and when trying to import UniqueConstraint, I am getting this terrible

AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint'

error. I don't want to step down to unique_together, because it seems like being depreciated. So why I get this error in the latest version of Django ?!

I am importing it the following way:

from django.db import models

class CalendarAccount(models.Model):

    class Meta:
        managed = False
        db_table = 'my_table'
        constraints = [
            models.UniqueConstraint(...),
        ]


问:
Is it worth learning Smarty for PHP templating?
I'm building a simple 10-page site using an MVC-like architecture. Is it worth learning the Smarty templating engine?</p>

答:
I agree with what is said above. For a simple site with 10 pages, use PHP on the MVC model or use a lightweight and fast template engine like RainTPL or Savant.

That test might be biased as it is published by the author of RainTPL. But anyway I benchmarked several template engines with the Apache ab utility and can confirm these results. RainTPL is fast.


问:
c++ std::enable_if .... else?
```<code>#include <stdio.h>
#include <type_traits>

void print()
{
    printf("cheers from print !\n");
}

class A
{
  public:
  void print()
  {
      printf("cheers from A !");
  }
};

template<typename Function>
typename std::enable_if< std::is_function<
                                typename std::remove_pointer<Function>::type >::value,
                                void >::type
run(Function f)
{
    f();
}

template<typename T>
typename std::enable_if< !std::is_function<
                                typename std::remove_pointer<T>::type >::value,
                                void >::type
run(T& t)
{
    t.print();
}

int main()
{
    run(print);

    A a;
    run(a);

    return 0;
}
</code>```

The code above compiles and print as expected:

cheers from print ! cheers from A !

what I would like to express is : "if the template is function then apply this function, else ...". Or in another formulation : having a version of the function for function templates, and a default version for non function templates.

so, this part seems somehow redundant, and could be "replaced" by a "else" condition :

```<code>template<typename T>
typename std::enable_if< !std::is_function<
                                typename std::remove_pointer<T>::type >::value,
                                void >::type
run(T& t)
</code>```

would this exists ?

答:
What you are looking for is constexpr if.  That will let you write the code like

```<code>template<typename Obj>
void run(Obj o)
{
    if constexpr (std::is_function_v<std::remove_pointer_t<Obj>>)
        o();
    else
        o.print();
}
</code>```

Live Example

If you don't have access to C++17 but do have C++14, you can at least shorten the code you need to write using a variable template.  That would look like

```<code>template<typename T>
static constexpr bool is_function_v = std::is_function< typename std::remove_pointer<T>::type >::value;

template<typename Function>
typename std::enable_if< is_function_v<Function>, void>::type
run(Function f)
{
    f();
}

template<typename T>
typename std::enable_if< !is_function_v<T>, void>::type
run(T& t)
{
    t.print();
}
</code>```

Live Example

Title: c++ std::enable_if .... else?

Body:
#include <stdio.h>
#include <type_traits>

void print()
{
    printf("cheers from print !\n");
}

class A
{
  public:
  void print()
  {
      printf("cheers from A !");
  }
};

template<typename Function>
typename std::enable_if< std::is_function<
                                typename std::remove_pointer<Function>::type >::value,
                                void >::type
run(Function f)
{
    f();
}

template<typename T>
typename std::enable_if< !std::is_function<
                                typename std::remove_pointer<T>::type >::value,
                                void >::type
run(T& t)
{
    t.print();
}

int main()
{
    run(print);

    A a;
    run(a);

    return 0;
}

The code above compiles and print as expected:

cheers from print ! cheers from A !

what I would like to express is : "if the template is function then apply this function, else ...". Or in another formulation : having a version of the function for function templates, and a default version for non function templates.

so, this part seems somehow redundant, and could be "replaced" by a "else" condition :

template<typename T>
typename std::enable_if< !std::is_function<
                                typename std::remove_pointer<T>::type >::value,
                                void >::type
run(T& t)

would this exists ?

Body:
What you are looking for is constexpr if.  That will let you write the code like

template<typename Obj>
void run(Obj o)
{
    if constexpr (std::is_function_v<std::remove_pointer_t<Obj>>)
        o();
    else
        o.print();
}

Live Example

If you don't have access to C++17 but do have C++14, you can at least shorten the code you need to write using a variable template.  That would look like

template<typename T>
static constexpr bool is_function_v = std::is_function< typename std::remove_pointer<T>::type >::value;

template<typename Function>
typename std::enable_if< is_function_v<Function>, void>::type
run(Function f)
{
    f();
}

template<typename T>
typename std::enable_if< !is_function_v<T>, void>::type
run(T& t)
{
    t.print();
}

Live Example


问:
Add a custom fee for percentage and fixed cost to specific payment gateway in WooCommerce
In WooCommerce I need to apply a custom handling fee for a specific payment gateway.

A custom handling fee for percentage cost and a custom handling for per fixed cost.

I have this 2 pieces of codes:

A) PERCENTAGE COST - function

/************************************************************/
/*  PERCENTACE COST
**/
// Add a custom fee based o cart subtotal
// Add a custom fee based o cart subtotal

add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
function custom_percentage_fee ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page

    $payment_method = WC()->session->get( 'chosen_payment_method' );

    if ( 'cod' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.025;
        $cart->add_fee( 'Percentage Cost', $surcharge, true );
    }
}

// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page
    ?>

    <?php
}
```
<p><strong>Result frontend</strong></p>
<p><img src="https://i.stack.imgur.com/Jc5mB.png" alt="enter image description here" /></p>
<hr />
<p><strong>B) FIXED COST - function</strong></p>
<pre class="lang-php prettyprint-override"><code>/************************************************************/
/*  FIXED COST
**/
// Add a custom fee based o cart subtotal
add_action( 'woocommerce_cart_calculate_fees', 'custom_fixed_fee', 10, 1 );
function custom_fixed_fee ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( 'cod' === WC()->session->get('chosen_payment_method') ) {
        $fee = 0.31;
        $cart->add_fee( 'Fixed Cost', $fee, true );
    }
}

// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('form.checkout').on('change', 'input[name="payment_method"]', function(){
            $(document.body).trigger('update_checkout');
        });
    });
    </script>
    <?php
    endif;
}
</code>```

Result frontend

The two distinct functions work perfectly separately. Now, I would like to combine the two functions to get the sum of the two costs.

My code attempt (A + B): function evolution with addition other payment systems

add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
function custom_percentage_fee ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

     if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page

    $payment_method = WC()->session->get( 'chosen_payment_method' );

     if ( 'stripe' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.025;
        $fee = 0.31;
    }
     if ( 'paypal_credit_card_rest' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.036;
        $fee = 0.35;
    }
     if ( 'paypal_express' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.036;
        $fee = 0.35;
    }
     if ( 'bacs' == $payment_method ) {
        return;
    }

      $together = $surcharge + $fee;
      $cart->add_fee( 'Plus Cost', $together, true );
}

// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page
    ?>

    <?php
}
```
<p><strong>The function returns the following errors:</strong></p>
<p>Notice: Undefined variable: surcharge in /MY-FOLDER..../snippet-ops.php(446) : eval()'d code on line 79</p>
<p>Notice: Undefined variable: fee in /MY FOLDER..../snippet-ops.php(446) : eval()'d code on line 79</p>
<p>That is exactly here:</p>
```$together = $surcharge + $fee;
```

Result frontend

Any advice on how to combine the 2 codes above into 1?

答:
The difference between the 2 examples you've posted is really minimal. You can just use:

if ( 'cod' == $payment_method ) {
    $surcharge = $cart->subtotal * 0.025;
    $fee = 0.31;

    $together = $surcharge + $fee;
    $cart->add_fee( 'Plus Cost', $together, true );
}
```

Body:
In WooCommerce I need to apply a custom handling fee for a specific payment gateway.

A custom handling fee for percentage cost and a custom handling for per fixed cost.

I have this 2 pieces of codes:

A) PERCENTAGE COST - function

/************************************************************/
/*  PERCENTACE COST
**/
// Add a custom fee based o cart subtotal
// Add a custom fee based o cart subtotal

add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
function custom_percentage_fee ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page

    $payment_method = WC()->session->get( 'chosen_payment_method' );

    if ( 'cod' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.025;
        $cart->add_fee( 'Percentage Cost', $surcharge, true );
    }
}

// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page
    ?>

    <?php
}

Result frontend

B) FIXED COST - function

/************************************************************/
/*  FIXED COST
**/
// Add a custom fee based o cart subtotal
add_action( 'woocommerce_cart_calculate_fees', 'custom_fixed_fee', 10, 1 );
function custom_fixed_fee ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( 'cod' === WC()->session->get('chosen_payment_method') ) {
        $fee = 0.31;
        $cart->add_fee( 'Fixed Cost', $fee, true );
    }
}

// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>

    <?php
    endif;
}

Result frontend

The two distinct functions work perfectly separately. Now, I would like to combine the two functions to get the sum of the two costs.

My code attempt (A + B): function evolution with addition other payment systems

add_action( 'woocommerce_cart_calculate_fees', 'custom_percentage_fee', 20, 1 );
function custom_percentage_fee ( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

     if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page

    $payment_method = WC()->session->get( 'chosen_payment_method' );

     if ( 'stripe' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.025;
        $fee = 0.31;
    }
     if ( 'paypal_credit_card_rest' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.036;
        $fee = 0.35;
    }
     if ( 'paypal_express' == $payment_method ) {
        $surcharge = $cart->subtotal * 0.036;
        $fee = 0.35;
    }
     if ( 'bacs' == $payment_method ) {
        return;
    }

      $together = $surcharge + $fee;
      $cart->add_fee( 'Plus Cost', $together, true );
}

// jQuery - Update checkout on methode payment change
add_action( 'wp_footer', 'custom_checkout_jqscript' );
function custom_checkout_jqscript() {
    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
        return; // Only checkout page
    ?>

    <?php
}

The function returns the following errors:

Notice: Undefined variable: surcharge in /MY-FOLDER..../snippet-ops.php(446) : eval()'d code on line 79

Notice: Undefined variable: fee in /MY FOLDER..../snippet-ops.php(446) : eval()'d code on line 79

That is exactly here:

$together = $surcharge + $fee;

Result frontend

Any advice on how to combine the 2 codes above into 1?


问:
Respect rbenv when running commands over ssh
I have a headless Ubuntu 18.04 VM where I'm installing a Rails application on top of rbenv.

I want to be able to automate some administrative operations so I can run them locally and have my script execute the commands over ssh.  However when I do this, I get the system ruby instead of the rbenv ruby.  If I ssh directly to the box, then I get the correct rbenv ruby.

Example:

ubuntu:~$ cat show-ruby.sh
which ruby
ruby --version
ubuntu:~$ bash show-ruby.sh
/home/ubuntu/.rbenv/shims/ruby
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
```

<pre class="lang-sh prettyprint-override"><code>laptop:~$ ssh ubuntu 'bash show-ruby.sh'
/usr/bin/ruby
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]
</code>```

rbenv is initialized in my .bashrc file:

```<code>export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"
</code>```

So I tried adding source ~/.bashrc to the top of my show-ruby.sh test script but it doesn't make a difference.  Any ideas how I can force my remotely executed scripts to respect my rbenv-installed ruby?

答:
Just add a .ruby-version file with the needed ruby version and rbenv will automatically set the ruby version </p>

```<code>[current] > cat .ruby-version
2.4.6
[current] > rbenv version
2.4.6 (set by .ruby-version)
</code>```

Body:
I have a headless Ubuntu 18.04 VM where I'm installing a Rails application on top of rbenv.

I want to be able to automate some administrative operations so I can run them locally and have my script execute the commands over ssh.  However when I do this, I get the system ruby instead of the rbenv ruby.  If I ssh directly to the box, then I get the correct rbenv ruby.

Example:

ubuntu:~$ cat show-ruby.sh
which ruby
ruby --version
ubuntu:~$ bash show-ruby.sh
/home/ubuntu/.rbenv/shims/ruby
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]

laptop:~$ ssh ubuntu 'bash show-ruby.sh'
/usr/bin/ruby
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]

rbenv is initialized in my .bashrc file:

export PATH="$HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

So I tried adding source ~/.bashrc to the top of my show-ruby.sh test script but it doesn't make a difference.  Any ideas how I can force my remotely executed scripts to respect my rbenv-installed ruby?

Body:
Just add a .ruby-version file with the needed ruby version and rbenv will automatically set the ruby version

[current] > cat .ruby-version
2.4.6
[current] > rbenv version
2.4.6 (set by .ruby-version)


问:
Boxable if cell height is changed text don't appear
I have created BaseTable according to example from https://github.com/dhorions/boxable/wiki

```<code>
    float margin = 50;
    float yStartNewPage = myPage.getMediaBox().getHeight() - (2 * margin);
    float tableWidth = myPage.getMediaBox().getWidth() - (2 * margin);

    boolean drawContent = true;
    float yStart = yStartNewPage;
    float bottomMargin = 70;

    float yPosition = 550;

    BaseTable table = new BaseTable(yPosition, yStartNewPage, bottomMargin, tableWidth, margin, mainDocument, myPage, true, drawContent);

    Row<PDPage> headerRow = table.createRow(15f);
    Cell<PDPage> cell = headerRow.createCell(100, "Header");
    table.addHeaderRow(headerRow);

    Row<PDPage> row = table.createRow(12);
    cell = row.createCell(30, "Data 1");
    cell = row.createCell(70, "Some value");

    table.draw();

    contentStream.close();
    mainDocument.addPage(myPage);
    mainDocument.save("testfile.pdf");
    mainDocument.close();
</code>```

Table looks fine

but when I want change cell height like this

cell.setHeight(5f);

Content is not drawn in cell

I was trying with changing row height, font size change, but it didn't help.

Do You know how to fix it?

答:
After some debugging I've noticed that the cell height can be changed like this:

```<code>cell.setHeight(cell.getTextHeight() + 0.5f);
</code>```

It's important to pick cell.getTextHeight() and then add Your value, if You only put some number like 12f it won't work

Body:
I have created BaseTable according to example from https://github.com/dhorions/boxable/wiki

    float margin = 50;
    float yStartNewPage = myPage.getMediaBox().getHeight() - (2 * margin);
    float tableWidth = myPage.getMediaBox().getWidth() - (2 * margin);

    boolean drawContent = true;
    float yStart = yStartNewPage;
    float bottomMargin = 70;

    float yPosition = 550;

    BaseTable table = new BaseTable(yPosition, yStartNewPage, bottomMargin, tableWidth, margin, mainDocument, myPage, true, drawContent);

    Row<PDPage> headerRow = table.createRow(15f);
    Cell<PDPage> cell = headerRow.createCell(100, "Header");
    table.addHeaderRow(headerRow);

    Row<PDPage> row = table.createRow(12);
    cell = row.createCell(30, "Data 1");
    cell = row.createCell(70, "Some value");

    table.draw();

    contentStream.close();
    mainDocument.addPage(myPage);
    mainDocument.save("testfile.pdf");
    mainDocument.close();

Table looks fine

but when I want change cell height like this

cell.setHeight(5f);

Content is not drawn in cell

I was trying with changing row height, font size change, but it didn't help.

Do You know how to fix it?

Body:
After some debugging I've noticed that the cell height can be changed like this:

cell.setHeight(cell.getTextHeight() + 0.5f);

It's important to pick cell.getTextHeight() and then add Your value, if You only put some number like 12f it won't work


问:
JMeter - Api GET Request - Response says: No known way to render data, Status Code is 200 though
Performing GET Requests which returns a JSON response.
JMeter is getting Statua code 200 but in Response, it says: NO way found to render data.
I tried the same request in POSTMAN and it is working fine.

答:
Compared to the Postman and JMeter requests.
Postman was working without passing Accept and Cache-Control headers but Jmeter requires it.
After adding these 2 in headers, I started getting a response. And I changed few JMeter properties to avoid checking the response size check.</p>


问:
best way for running code in async with kotlin
hi i want use jsoup to load a large table from html, what is the best way for doing this in async way?
AsyncTask? coroutines? doasync library? which one? i need show progressbar while fetching data so please tell me what is the best way?

UPDATE:
i want run this code in async

```<code>doc: Document = Jsoup.connect(url).timeout(0).maxBodySize(0).ignoreHttpErrors(true).sslSocketFactory(setTrustAllCerts()).get()
// some code for parsing...
</code>```

答:
In Kotlin, the general approach is coroutines, but normal threading is also a completely fine option, depending on what you're doing.

For example, if your operation is a thread-blocking operation, it actually can't run safely in a coroutine unless it's dispatched in a separate thread. For coroutines, you need to know the difference between suspending and blocking (huge difference).

So if reading the HTML table is a blocking operation, and you don't need to integrate with other coroutines, then a normal thread works just fine. There are many Java examples that are transferable to Kotlin.

With coroutines, you can do something like:

```<code>suspend fun getDoc() = withContext(Dispatchers.IO) {
    Jsoup.connect(url).timeout(0).maxBodySize(0).ignoreHttpErrors(true).sslSocketFactory(setTrustAllCerts()).get()
}
</code>```

Then, in your main code:

```<code>fun main() = runBlocking {

    val deferredDoc = async { getDoc() }

    // Do whatever.... it's not being blocked...

    val doc = deferredDoc.await() // SUSPENDING CALL - but not blocking
}
</code>```

Obviously, your program's structure will look different than this example, because it depends entirely on what code you want to execute asynchronously with "getDoc()".

For example, you can even have another coroutine that executes while "deferredDoc.await()" is suspending, without even creating another thread. That's the benefit of coroutines.

In the structure above, we have 3 guaranteed threads:

Main thread, which is always blocked

Main Coroutine thread. This is what the coroutines generally run on. Kotlin coroutines will run your coroutines asynchronously inside this thread using suspension.

IO thread. This is what your blocking code will run on.

Body:
hi i want use jsoup to load a large table from html, what is the best way for doing this in async way?
AsyncTask? coroutines? doasync library? which one? i need show progressbar while fetching data so please tell me what is the best way?

UPDATE:
i want run this code in async

doc: Document = Jsoup.connect(url).timeout(0).maxBodySize(0).ignoreHttpErrors(true).sslSocketFactory(setTrustAllCerts()).get()
// some code for parsing...

Body:
In Kotlin, the general approach is coroutines, but normal threading is also a completely fine option, depending on what you're doing.

For example, if your operation is a thread-blocking operation, it actually can't run safely in a coroutine unless it's dispatched in a separate thread. For coroutines, you need to know the difference between suspending and blocking (huge difference).

So if reading the HTML table is a blocking operation, and you don't need to integrate with other coroutines, then a normal thread works just fine. There are many Java examples that are transferable to Kotlin.

With coroutines, you can do something like:

suspend fun getDoc() = withContext(Dispatchers.IO) {
    Jsoup.connect(url).timeout(0).maxBodySize(0).ignoreHttpErrors(true).sslSocketFactory(setTrustAllCerts()).get()
}

Then, in your main code:

fun main() = runBlocking {

    val deferredDoc = async { getDoc() }

    // Do whatever.... it's not being blocked...

    val doc = deferredDoc.await() // SUSPENDING CALL - but not blocking
}

Obviously, your program's structure will look different than this example, because it depends entirely on what code you want to execute asynchronously with "getDoc()".

For example, you can even have another coroutine that executes while "deferredDoc.await()" is suspending, without even creating another thread. That's the benefit of coroutines.

In the structure above, we have 3 guaranteed threads:

Main thread, which is always blocked

Main Coroutine thread. This is what the coroutines generally run on. Kotlin coroutines will run your coroutines asynchronously inside this thread using suspension.

IO thread. This is what your blocking code will run on.