问:
Android MP Pie Chart how to remove text and values from Pie chart

How can i achieve this using MPAndroidChart ?

Using version : com.github.PhilJay:MPAndroidChart:v3.1.0-alpha
 Adding code for Legend and piechart margin:

```<code>private void setPieChartData() {
        //https://stackoverflow.com/a/50551488/1427037
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setExtraOffsets(5,5,10,5);
        pieChart.setDragDecelerationFrictionCoef(0.9f);
        pieChart.setDrawCenterText(false);
        pieChart.setDrawHoleEnabled(false);
        //pieChart.animateY(1000, Easing.EasingOption.EaseInOutCubic);
        ArrayList<PieEntry> yValues = new ArrayList<>();
        yValues.add(new PieEntry(34f,"Ilala"));
        yValues.add(new PieEntry(56f,"Temeke"));
        yValues.add(new PieEntry(66f,"Kinondoni"));
        yValues.add(new PieEntry(45f,"Kigamboni"));
        yValues.add(new PieEntry(45f,"Kigamboni2"));
        pieChart.setDrawEntryLabels(false);

        PieDataSet dataSet = new PieDataSet(yValues, "Desease Per Regions");
        dataSet.setSliceSpace(0.1f);
        dataSet.setDrawValues(false);
        dataSet.setSelectionShift(5f);
        dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS);

        PieData pieData = new PieData((dataSet));
        pieData.setValueTextSize(10f);
        pieData.setValueTextColor(Color.BLACK);
        pieChart.setData(pieData);
        pieChart.setDrawSliceText(false);
        setLegend();
    }

    private void setLegend() {
        Legend l = pieChart.getLegend();
        l.setFormSize(10f); // set the size of the legend forms/shapes
        l.setForm(Legend.LegendForm.SQUARE); // set what type of form/shape should be used
        l.setYOffset(5f);
        //l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); // set vertical alignment for legend
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); // set horizontal alignment for legend
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setTextSize(12f);
        l.setTextColor(Color.BLACK);
        //l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
        l.setYEntrySpace(1f); // set the space between the legend entries on the y-axis
        // set custom labels and colors
        List<LegendEntry> entries = new ArrayList<>();
        ArrayList<PieEntry> yValues = new ArrayList<>();
        yValues.add(new PieEntry(34f,"Ilala"));
        yValues.add(new PieEntry(56f,"Temeke"));
        yValues.add(new PieEntry(66f,"Kinondoni"));
        yValues.add(new PieEntry(45f,"Kigamboni"));
        yValues.add(new PieEntry(45f,"Kigamboni2"));
        for (int i = 0; i < 3; i++) {
            LegendEntry entry = new LegendEntry();
            entry.formColor = ColorTemplate.VORDIPLOM_COLORS[i];
            entry.label = yValues.get(i).getLabel() ;
            entries.add(entry);
        }
        l.setCustom(entries);
    }
   [![code result][2]][2]
</code>```

How to set position of legend same as actual image i am getting problem to set its layout.please correct code and share any link for help
Please share details to resolve this problem

How to resolve this UI issue .. legend label should be on right side same as Required mock

答:
I hope it will help!

I did it,

```<code>    pieChart.setDrawCenterText(true);
    pieChart.setDrawEntryLabels(true);
    pieChart.setDrawMarkers(false);
    pieChart.getDescription().setEnabled(false);

    pieChart.getLegend().setEnabled(false);
</code>```

just change to false all and you shouldn't see any text(s)!
[ sorry if i had poor English ]

Body:
How can i achieve this using MPAndroidChart ?

Using version : com.github.PhilJay:MPAndroidChart:v3.1.0-alpha
 Adding code for Legend and piechart margin:

private void setPieChartData() {
        //https://stackoverflow.com/a/50551488/1427037
        pieChart.setUsePercentValues(true);
        pieChart.getDescription().setEnabled(false);
        pieChart.setExtraOffsets(5,5,10,5);
        pieChart.setDragDecelerationFrictionCoef(0.9f);
        pieChart.setDrawCenterText(false);
        pieChart.setDrawHoleEnabled(false);
        //pieChart.animateY(1000, Easing.EasingOption.EaseInOutCubic);
        ArrayList<PieEntry> yValues = new ArrayList<>();
        yValues.add(new PieEntry(34f,"Ilala"));
        yValues.add(new PieEntry(56f,"Temeke"));
        yValues.add(new PieEntry(66f,"Kinondoni"));
        yValues.add(new PieEntry(45f,"Kigamboni"));
        yValues.add(new PieEntry(45f,"Kigamboni2"));
        pieChart.setDrawEntryLabels(false);

        PieDataSet dataSet = new PieDataSet(yValues, "Desease Per Regions");
        dataSet.setSliceSpace(0.1f);
        dataSet.setDrawValues(false);
        dataSet.setSelectionShift(5f);
        dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS);

        PieData pieData = new PieData((dataSet));
        pieData.setValueTextSize(10f);
        pieData.setValueTextColor(Color.BLACK);
        pieChart.setData(pieData);
        pieChart.setDrawSliceText(false);
        setLegend();
    }

    private void setLegend() {
        Legend l = pieChart.getLegend();
        l.setFormSize(10f); // set the size of the legend forms/shapes
        l.setForm(Legend.LegendForm.SQUARE); // set what type of form/shape should be used
        l.setYOffset(5f);
        //l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP); // set vertical alignment for legend
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT); // set horizontal alignment for legend
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setTextSize(12f);
        l.setTextColor(Color.BLACK);
        //l.setXEntrySpace(5f); // set the space between the legend entries on the x-axis
        l.setYEntrySpace(1f); // set the space between the legend entries on the y-axis
        // set custom labels and colors
        List<LegendEntry> entries = new ArrayList<>();
        ArrayList<PieEntry> yValues = new ArrayList<>();
        yValues.add(new PieEntry(34f,"Ilala"));
        yValues.add(new PieEntry(56f,"Temeke"));
        yValues.add(new PieEntry(66f,"Kinondoni"));
        yValues.add(new PieEntry(45f,"Kigamboni"));
        yValues.add(new PieEntry(45f,"Kigamboni2"));
        for (int i = 0; i < 3; i++) {
            LegendEntry entry = new LegendEntry();
            entry.formColor = ColorTemplate.VORDIPLOM_COLORS[i];
            entry.label = yValues.get(i).getLabel() ;
            entries.add(entry);
        }
        l.setCustom(entries);
    }
   [![code result][2]][2]

How to set position of legend same as actual image i am getting problem to set its layout.please correct code and share any link for help
Please share details to resolve this problem

How to resolve this UI issue .. legend label should be on right side same as Required mock

Body:
I hope it will help!

I did it,

    pieChart.setDrawCenterText(true);
    pieChart.setDrawEntryLabels(true);
    pieChart.setDrawMarkers(false);
    pieChart.getDescription().setEnabled(false);

    pieChart.getLegend().setEnabled(false);

just change to false all and you shouldn't see any text(s)!
[ sorry if i had poor English ]


来源: stackexchange

问:
Tuple assignment to mutable struct parameters
I’m getting an error I’m not sure how to handle, related to a tuple assignment I’m trying. The incr function below gets a left-hand of expression not valid error. What am I misunderstanding?

```<code>struct Fib {
    i: u64,
    fa: u64,
    fb: u64,
}

impl Fib {
    fn incr(&mut self) {
        self.i += 1;
        (self.fa, self.fb) = (self.fa + self.fb, self.fa);
    }
}
</code>```

答:
As the helpful error explanation says†, you try to assign to a non-place expression.  A place expression represents a memory location, and thus it can be a variable, a dereference, an indexing expression or a field reference, but a tuple is not one of these.

If you would use a binding, such as:

let (x, y) = (1, 2);
```

<p>that would be a whole different story because <code>let</code> statements have different rules than assignment: the left hand side of a <code>let</code> statement is a pattern, not an expression, and <code>(x, y)</code> is a legal pattern.</p>

<p>To solve your problem, you may want to do the following and introduce a temporary variable, and then update the values of the members:</p>

<p><em>(The following is also fixing your fibonacci sequence, i.e. correcting the values of the members since they are naturally ordered as 'a' and 'b')</em></p>

<pre class="lang-rust prettyprint-override"><code>impl Fib {
    fn incr(&mut self) {
        self.i += 1;
        let fa = self.fa;
        self.fa = self.fb;
        self.fb += fa;
    }
}
</code>```

Note: Albeit it was not your question, I would strongly advise to implement Iterator for your Fib type, in which case you wouldn't have to keep track of the index (i) because that would be available through the enumerate method.
  E.g.

impl Iterator for Fib {
    type Item = u64;
    fn next(&mut self) -> Option<Self::Item> {
        let fa = self.fa;
        self.fa = self.fb;
        self.fb += fa;
        Some(fa)
    }
}
```

  <p>And then you could use it as:</p>

  <pre class="lang-rust prettyprint-override"><code>for (i, x) in my_fib.enumerate() { ... }
</code>```

† rustc --explain E0070

ContentLicense: CC BY-SA 4.0

Body:
I’m getting an error I’m not sure how to handle, related to a tuple assignment I’m trying. The incr function below gets a left-hand of expression not valid error. What am I misunderstanding?

struct Fib {
    i: u64,
    fa: u64,
    fb: u64,
}

impl Fib {
    fn incr(&mut self) {
        self.i += 1;
        (self.fa, self.fb) = (self.fa + self.fb, self.fa);
    }
}

Body:
As the helpful error explanation says†, you try to assign to a non-place expression.  A place expression represents a memory location, and thus it can be a variable, a dereference, an indexing expression or a field reference, but a tuple is not one of these.

If you would use a binding, such as:

let (x, y) = (1, 2);

that would be a whole different story because let statements have different rules than assignment: the left hand side of a let statement is a pattern, not an expression, and (x, y) is a legal pattern.

To solve your problem, you may want to do the following and introduce a temporary variable, and then update the values of the members:

(The following is also fixing your fibonacci sequence, i.e. correcting the values of the members since they are naturally ordered as 'a' and 'b')

impl Fib {
    fn incr(&mut self) {
        self.i += 1;
        let fa = self.fa;
        self.fa = self.fb;
        self.fb += fa;
    }
}

Note: Albeit it was not your question, I would strongly advise to implement Iterator for your Fib type, in which case you wouldn't have to keep track of the index (i) because that would be available through the enumerate method.
  E.g.

impl Iterator for Fib {
    type Item = u64;
    fn next(&mut self) -> Option<Self::Item> {
        let fa = self.fa;
        self.fa = self.fb;
        self.fb += fa;
        Some(fa)
    }
}

And then you could use it as:

for (i, x) in my_fib.enumerate() { ... }

† rustc --explain E0070


问:
Ruby 2.7.0 in termux - FFI:NotFoundError
My question is regarding using Ruby 2.7.0 (built via rbenv) on termux:-

I'm seeing:-

FFI::NotFoundError: Function 'getdtablesize' not found in [libc.so] when I try and run rake, I've searched online but haven't managed to find much about this error so far.

Stack trace:-

```<code>FFI::NotFoundError: Function 'getdtablesize' not found in [libc.so]
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/ffi-1.11.3/lib/ffi/library.rb:273:in `attach_function'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/ethon-0.12.0/lib/ethon/libc.rb:16:in `<module:Libc>'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/ethon-0.12.0/lib/ethon/libc.rb:6:in `<module:Ethon>'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/ethon-0.12.0/lib/ethon/libc.rb:1:in `<main>'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `block in require_with_bootsnap_lfi'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'```
```

答:
It seems the getdtablesize function (which is used by the ethon gem) was removed from the libc of more recent Android distributions, apparently after being deprecated for some time.

Thus, to use the ethon gem on your Android distribution, you would need to either:

adapt the gem to not use the getdtablesize function anymore, or

use a different libc for your project which still provides the function, e.g. the libc of the GNU project

Body:
My question is regarding using Ruby 2.7.0 (built via rbenv) on termux:-

I'm seeing:-

FFI::NotFoundError: Function 'getdtablesize' not found in [libc.so] when I try and run rake, I've searched online but haven't managed to find much about this error so far.

Stack trace:-

FFI::NotFoundError: Function 'getdtablesize' not found in [libc.so]
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/ffi-1.11.3/lib/ffi/library.rb:273:in `attach_function'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/ethon-0.12.0/lib/ethon/libc.rb:16:in `<module:Libc>'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/ethon-0.12.0/lib/ethon/libc.rb:6:in `<module:Ethon>'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/ethon-0.12.0/lib/ethon/libc.rb:1:in `'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `block in require_with_bootsnap_lfi'
/data/data/com.termux/files/home/Projects/myapp/.bundle/ruby/2.7.0/gems/bootsnap-1.4.5/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'```


问:
Appending a list based on the column that the data comes from
I'm attempting to append a binary numpy array to another numpy array to feed into a neural network. The binary list is dependent on the column that the array is coming from.
For example, an array that comes from the third column is [0 0 1 0 0 0 0 0 0].

Here is an example:

Data (list of arrays):

```<code>[[0, 1, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 0, 0, 0]]
</code>```

Let's say that the first two elements came from the first column of a dataframe and the third element came from the second column. After appending the binary array the data would look something like this:

```<code> [([0, 1, 1, 1, 0],
[1 0 0 0 0 0 0 0 0]),

([0, 1, 0, 0, 1],
[1 0 0 0 0 0 0 0 0]),

([1, 0, 0, 0, 0],
[0 1 0 0 0 0 0 0 0])]
</code>```

For context, I was originally training on just a single column of a dataframe, however I want to be able to train over the entire dataframe now.

Is there a way to automatically append this array to my data depending on the column the data is coming from so that the neural network can train on the whole data set rather than just going column by column?

Additionally, would this require two input layers or just one?

答:
Maybe you could add a more concrete example to your question. But anyway, is this what you're expecting?</p>

```<code>In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'col1': [[0,0,1], [1,1,1]], 'col2': [[1,1,0],[0,0,0]]})

In [3]: df
Out[3]:
        col1       col2
0  [0, 0, 1]  [1, 1, 0]
1  [1, 1, 1]  [0, 0, 0]

In [4]: for col_index, col_name in enumerate(df.columns):
   ...:     array_to_append = [0] * len(df.columns)
   ...:     array_to_append[col_index] = 1
   ...:     df[col_name] = df[col_name].map(lambda x: (x, array_to_append))
   ...:

In [5]: df
Out[5]:
                  col1                 col2
0  ([0, 0, 1], [1, 0])  ([1, 1, 0], [0, 1])
1  ([1, 1, 1], [1, 0])  ([0, 0, 0], [0, 1])
</code>```

Body:
I'm attempting to append a binary numpy array to another numpy array to feed into a neural network. The binary list is dependent on the column that the array is coming from.
For example, an array that comes from the third column is [0 0 1 0 0 0 0 0 0].

Here is an example:

Data (list of arrays):

[[0, 1, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 0, 0, 0]]

Let's say that the first two elements came from the first column of a dataframe and the third element came from the second column. After appending the binary array the data would look something like this:

 [([0, 1, 1, 1, 0],
[1 0 0 0 0 0 0 0 0]),

([0, 1, 0, 0, 1],
[1 0 0 0 0 0 0 0 0]),

([1, 0, 0, 0, 0],
[0 1 0 0 0 0 0 0 0])]

For context, I was originally training on just a single column of a dataframe, however I want to be able to train over the entire dataframe now.

Is there a way to automatically append this array to my data depending on the column the data is coming from so that the neural network can train on the whole data set rather than just going column by column?

Additionally, would this require two input layers or just one?

Body:
Maybe you could add a more concrete example to your question. But anyway, is this what you're expecting?

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'col1': [[0,0,1], [1,1,1]], 'col2': [[1,1,0],[0,0,0]]})

In [3]: df
Out[3]:
        col1       col2
0  [0, 0, 1]  [1, 1, 0]
1  [1, 1, 1]  [0, 0, 0]

In [4]: for col_index, col_name in enumerate(df.columns):
   ...:     array_to_append = [0] * len(df.columns)
   ...:     array_to_append[col_index] = 1
   ...:     df[col_name] = df[col_name].map(lambda x: (x, array_to_append))
   ...:

In [5]: df
Out[5]:
                  col1                 col2
0  ([0, 0, 1], [1, 0])  ([1, 1, 0], [0, 1])
1  ([1, 1, 1], [1, 0])  ([0, 0, 0], [0, 1])


问:
passing php variable into html
I'm new to php so pardon the ignorance

I'm trying to include a php variable, it is and is not working.

```<code>$currentdata = file_get_contents("http://www.abr.business.gov.au/abnDetails.aspx?abn=$abn");
</code>```

This works with $abn being the variable being passed from earlier being set.

```<code>$abntypedata = '/d$abn&ResultListURL=">(.+?)</'; This does not work.
$abntypedata = '/d33051775556&ResultListURL=">(.+?)</'; This does.
</code>```

I need to be able to use the variable $abn to insert that number as it will be user defined. Why is this not working?

答:
Variable substitution does not occur with single quotes. Change those to double quotes and should work.

EDIT: FYI, here's the PHP manual for strings in PHP. It's useful to know what the various types of strings are: http://www.php.net/manual/en/language.types.string.php

ContentLicense: CC BY-SA 3.0

Title: passing php variable into html

Body:
I'm new to php so pardon the ignorance

I'm trying to include a php variable, it is and is not working.

$currentdata = file_get_contents("http://www.abr.business.gov.au/abnDetails.aspx?abn=$abn");

This works with $abn being the variable being passed from earlier being set.

$abntypedata = '/d$abn&ResultListURL=">(.+?)</'; This does not work.
$abntypedata = '/d33051775556&ResultListURL=">(.+?)</'; This does.

I need to be able to use the variable $abn to insert that number as it will be user defined. Why is this not working?


问:
Running Concatenation of column values in oracle sql
I have table structure like below

```<code>create table emp ( empno number,dept_no varchar(4));
insert into emp VALUES  (1,'A');
insert into emp  VALUES (1,'B');
insert into emp  VALUES (1,'C');
insert into emp  VALUES (1,'D');
insert into emp  VALUES (2,'P');
insert into emp  VALUES (2,'Q');
insert into emp  VALUES (2,'R');
insert into emp  VALUES (2,'S');
</code>```

I need output like below

```<code>1, A
1, A,B
1, A,B,C
1, A,B,C,D
2, P
2, P,Q
2, P,Q,R
2, P,Q,R,S
</code>```

I am able to achieve this using PL/SQL Block, however is there any possibility we can achieve this through sql?

答:
This is a task for listagg(). Unfortunately, although it can be used as window function, it does not support the order by window option, which is needed here.

One way to work around this would be to use a correlated subquery:

```<code>select
    e.empno,
    (
            select listagg(e1.dept_no, ',') within group(order by e1.dept_no)
            from emp e1
            where e1.empno = e.empno and e1.dept_no <= e.dept_no
    ) depts
from emp e
</code>```

Demo on DB Fiddlde:

```
EMPNO | DEPTS
----: | :------
    1 | A
    1 | A,B
    1 | A,B,C
    1 | A,B,C,D
    2 | P
    2 | P,Q
    2 | P,Q,R
    2 | P,Q,R,S
```

Body:
I have table structure like below

create table emp ( empno number,dept_no varchar(4));
insert into emp VALUES  (1,'A');
insert into emp  VALUES (1,'B');
insert into emp  VALUES (1,'C');
insert into emp  VALUES (1,'D');
insert into emp  VALUES (2,'P');
insert into emp  VALUES (2,'Q');
insert into emp  VALUES (2,'R');
insert into emp  VALUES (2,'S');

I need output like below

1, A
1, A,B
1, A,B,C
1, A,B,C,D
2, P
2, P,Q
2, P,Q,R
2, P,Q,R,S

I am able to achieve this using PL/SQL Block, however is there any possibility we can achieve this through sql?

Body:
This is a task for listagg(). Unfortunately, although it can be used as window function, it does not support the order by window option, which is needed here.

One way to work around this would be to use a correlated subquery:

select
    e.empno,
    (
            select listagg(e1.dept_no, ',') within group(order by e1.dept_no)
            from emp e1
            where e1.empno = e.empno and e1.dept_no <= e.dept_no
    ) depts
from emp e

Demo on DB Fiddlde:

EMPNO | DEPTS
----: | :------
    1 | A
    1 | A,B
    1 | A,B,C
    1 | A,B,C,D
    2 | P
    2 | P,Q
    2 | P,Q,R
    2 | P,Q,R,S


问:
IBM API Connect developer portal admin link missing
I have setup an API Connect developer portal in the sandbox catalog (I've been following the basic tutorials about configuring an API developer portal found here).

I receive a message saying that i'll get a one time login link so that i can login to the portal as admin and reset my password. However, this never arrives. I have tried configuring the portal a number of times now and this link never comes. Therefore i'm unable to login as admin.

I've also tried using the 'request new password' option on the developer portal itself and entering my email but this also does not work

Is there a way I can retrieve the login link?

答:
This could be a number of things:

1) the IBM emails often get flagged as spam
2) the IBM email server, or rather the people they've contracted this out to, doesn't fully comply with DKIM/SPF security, so if you are on a corporate server that requires this then you won't get your emails.

The workaround I've done in the past is spin up a gmail account and be sure to check my spam folder.


问:
What does the f do in plt.ylabel(f'g(x)')?
Firstly,

```<code>import matplotlib.pyplot as plt
import matplotlib
</code>```

In an elementary example on how to plot with matplotlib in our lecture I encountered the following line

```<code>plt.ylabel(f'g(x)')
</code>```

What I have tried

In the documentation there's no mention of an additional parameter to be inserted before the actual label text. I further checked out examples where plt.ylabel was used and discovered here that also r seems to be a valid option.
Also, I discovered in this example that the "parameter" r can also be used in plt.title, but also in the corresponding documentation I didn't find anything.

Entire Code

```<code>plt.figure(figsize=(6,4))
X = np.arange(0,2*np.pi,0.2)
plt.plot(X,np.sin(X),'o-',label='$\sin(x)$')
plt.plot(X,np.cos(X),'*-',c='g', label='$\cos(x)$')
plt.ylabel(f'f(x)' rotation=0)
plt.grid() # adds grid
_=plt.legend(loc=3)
</code>```

答:
f stands for format string
u can use it everywhere it is not
matplotlib specific

example:

```<code>x = 12
print(f'Hello {x}') # That will print 'Hello 12'
</code>```

Also:

```<code>print(f'Hello') # Also Works Just fine That will print 'Hello'
</code>```

check if it is a left over f

Body:
Firstly,

import matplotlib.pyplot as plt
import matplotlib

In an elementary example on how to plot with matplotlib in our lecture I encountered the following line

plt.ylabel(f'g(x)')

What I have tried

In the documentation there's no mention of an additional parameter to be inserted before the actual label text. I further checked out examples where plt.ylabel was used and discovered here that also r seems to be a valid option.
Also, I discovered in this example that the "parameter" r can also be used in plt.title, but also in the corresponding documentation I didn't find anything.

Entire Code

plt.figure(figsize=(6,4))
X = np.arange(0,2*np.pi,0.2)
plt.plot(X,np.sin(X),'o-',label='$\sin(x)$')
plt.plot(X,np.cos(X),'*-',c='g', label='$\cos(x)$')
plt.ylabel(f'f(x)' rotation=0)
plt.grid() # adds grid
_=plt.legend(loc=3)

Body:
f stands for format string
u can use it everywhere it is not
matplotlib specific

example:

x = 12
print(f'Hello {x}') # That will print 'Hello 12'

Also:

print(f'Hello') # Also Works Just fine That will print 'Hello'

check if it is a left over f


问:
UITextfield Value in UITableView
I have a textfield inside a UITableviewController. I want to get the user entered data after the user has finished typing and moves to the next field. I want to store that information.

Because once I scroll the user entered data disappears.

Any help is appreciated.

```<code>if (([indexPath section] == 1) && ([indexPath row] == 2))
{
    static NSString *CellIdentifier1 = @"Cell";

    GeneralInfocell *cell = (GeneralInfocell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
    [[NSBundle mainBundle] loadNibNamed:@"GeneralInfocell" owner:self options:nil];

    cell = addresscell;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    addresscell.txtStreet.delegate = self;

    addresscell.txtStreet.font = [UIFont fontWithName:@"Arial" size:14];

    addresscell.txtStreet.keyboardType = UIKeyboardTypeDefault;
    addresscell.txtStreet.returnKeyType = UIReturnKeyNext;

    addresscell.txtStreet.backgroundColor = [UIColor whiteColor];
    addresscell.txtStreet.autocorrectionType = UITextAutocorrectionTypeNo;
    addresscell. txtStreet.autocapitalizationType = UITextAutocapitalizationTypeNone;
    addresscell. txtStreet.textAlignment = UITextAlignmentLeft;

    addresscell.txtStreet.textColor = [UIColor blackColor];

    [addresscell.txtStreet addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
}
</code>```

In the textFieldDidEndEditing method I have,

```<code>- (void)textFieldDidEndEditing:(UITextField *)textField {

    UILabel *label = [NSString stringWithFormat:@"%@",[addresscell.txtCity text]];
    NSLog(@"label:%@",label);

}
</code>```

But I don't get any value.

Thanks

答:
Your UITextFieldDelegate should be something like this –

```<code>- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"Data entered: %@", textField.text);
}
</code>```

Since everything else is wired correctly, you should get a proper value now.

Since cells are reused, you lose data on scrolling. You will need to reset the text field's value every time the cell is requested. For this, you can maintain a mutable array of strings if there are multiple fields, one for each of the text fields. When a text field is dismissed, save the data entered in the array and restore it next time the cell is requested for.

Let me know if you need any further assistance.

EDIT

tag all the ten text fields 0 to 9.

Declare a NSMutableArray iVar in your view controller, say data, to store the strings for the text fields.

In -viewDidLoad:,

```<code>...
data = [[NSMutableArray] initWithCapacity:10];
for ( int i = 0; i < 10; i++ ) {
    [data addObject:@""];
}
...
</code>```

In -textFieldDidEndEditing:,

```<code>...
[data replaceObjectAtIndex:[textField tag] withObject:[textField text]];
...
</code>```

In -tableView:cellForRowAtIndexPath:,

```<code>...
// Since they are named variables, it will be something on lines of
addressCell.txtStreet.text = [data objectAtIndex:[addressCell.txtStreet tag]];
// Repeat for all other text fields
...
</code>```

Don't forget to release data in the dealloc method.

Title: UITextfield Value in UITableView

Body:
I have a textfield inside a UITableviewController. I want to get the user entered data after the user has finished typing and moves to the next field. I want to store that information.

Because once I scroll the user entered data disappears.

Any help is appreciated.

if (([indexPath section] == 1) && ([indexPath row] == 2))
{
    static NSString *CellIdentifier1 = @"Cell";

    GeneralInfocell *cell = (GeneralInfocell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
    [[NSBundle mainBundle] loadNibNamed:@"GeneralInfocell" owner:self options:nil];

    cell = addresscell;

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    addresscell.txtStreet.delegate = self;

    addresscell.txtStreet.font = [UIFont fontWithName:@"Arial" size:14];

    addresscell.txtStreet.keyboardType = UIKeyboardTypeDefault;
    addresscell.txtStreet.returnKeyType = UIReturnKeyNext;

    addresscell.txtStreet.backgroundColor = [UIColor whiteColor];
    addresscell.txtStreet.autocorrectionType = UITextAutocorrectionTypeNo;
    addresscell. txtStreet.autocapitalizationType = UITextAutocapitalizationTypeNone;
    addresscell. txtStreet.textAlignment = UITextAlignmentLeft;

    addresscell.txtStreet.textColor = [UIColor blackColor];

    [addresscell.txtStreet addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
}

In the textFieldDidEndEditing method I have,

- (void)textFieldDidEndEditing:(UITextField *)textField {

    UILabel *label = [NSString stringWithFormat:@"%@",[addresscell.txtCity text]];
    NSLog(@"label:%@",label);

}

But I don't get any value.

Thanks

Body:
Your UITextFieldDelegate should be something like this –

- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"Data entered: %@", textField.text);
}

Since everything else is wired correctly, you should get a proper value now.

Since cells are reused, you lose data on scrolling. You will need to reset the text field's value every time the cell is requested. For this, you can maintain a mutable array of strings if there are multiple fields, one for each of the text fields. When a text field is dismissed, save the data entered in the array and restore it next time the cell is requested for.

Let me know if you need any further assistance.

EDIT

tag all the ten text fields 0 to 9.

Declare a NSMutableArray iVar in your view controller, say data, to store the strings for the text fields.

In -viewDidLoad:,

...
data = [[NSMutableArray] initWithCapacity:10];
for ( int i = 0; i < 10; i++ ) {
    [data addObject:@""];
}
...

In -textFieldDidEndEditing:,

...
[data replaceObjectAtIndex:[textField tag] withObject:[textField text]];
...

In -tableView:cellForRowAtIndexPath:,

...
// Since they are named variables, it will be something on lines of
addressCell.txtStreet.text = [data objectAtIndex:[addressCell.txtStreet tag]];
// Repeat for all other text fields
...

Don't forget to release data in the dealloc method.


问:
Replace element in array by average
I have a question about the exercise from my course:
Write a program that takes array of real numbers as parameter and replaces each element that is smaller than average of the first and last element, by this average. This is my code:

```<code>#include <iostream>
#include <string>
using namespace std;

void replaverage(int arr[], int n)
{
    for (int i; i < 6; i++) {
        cout << "Enter the numbers" << endl;
        cin >> arr[i];
    }
    int f = arr[0];
    int l = arr[n - 1];
    double av = f + l / 2;
    for (int i; i < n; i++) {
        if (arr[i] < av) {
            arr[i] = av;
        }
    }
}

int main()
{
    int n;
    int arr[n];
    replaverage(arr, n);
    cout << arr << " " << endl;
    return 0;
}
</code>```

Code is working, however as an output, it is giving some kind of address "0x7fff2306a5c0". I'm beginner so I apologize, maybe my error is stupid but I don't know how to fix it. Thanks for helping!

答:
```<code>#include <iostream>
#include <string>
using namespace std;

void replaverage(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
        cout << "Enter the number: ";
        cin >> arr[i];
        cout << endl;
    }
    int f = arr[0];
    int l = arr[n - 1];
    double av = (f + l) / 2;
    for (int i = 0; i < n; i++) {
        if (arr[i] < av) {
            arr[i] = av;
        }
    }
}

int main()
{
    int n = 6; // Making 6 since you had it hardcoded
    int arr[n];
    replaverage(arr, n);
    for (int i = 0; i < n; i++) {
       cout << arr[i] << endl;
    }
    return 0;
}
</code>```

First problem: Initialize your loop counters to 0;

Second problem: Initialize n in main being passed as parameter to
something

Third problem: Your average calculation is incorrect. It should be (f+l) / 2. Otherwise it will be doing l/2 + f, which is incorrect.

Fourth problem: You need to loop over your array to see all the
elements

Title: Replace element in array by average

Body:
I have a question about the exercise from my course:
Write a program that takes array of real numbers as parameter and replaces each element that is smaller than average of the first and last element, by this average. This is my code:

#include <iostream>
#include <string>
using namespace std;

void replaverage(int arr[], int n)
{
    for (int i; i < 6; i++) {
        cout << "Enter the numbers" << endl;
        cin >> arr[i];
    }
    int f = arr[0];
    int l = arr[n - 1];
    double av = f + l / 2;
    for (int i; i < n; i++) {
        if (arr[i] < av) {
            arr[i] = av;
        }
    }
}

int main()
{
    int n;
    int arr[n];
    replaverage(arr, n);
    cout << arr << " " << endl;
    return 0;
}

Code is working, however as an output, it is giving some kind of address "0x7fff2306a5c0". I'm beginner so I apologize, maybe my error is stupid but I don't know how to fix it. Thanks for helping!

Body:
#include <iostream>
#include <string>
using namespace std;

void replaverage(int arr[], int n)
{
    for (int i = 0; i < n; i++) {
        cout << "Enter the number: ";
        cin >> arr[i];
        cout << endl;
    }
    int f = arr[0];
    int l = arr[n - 1];
    double av = (f + l) / 2;
    for (int i = 0; i < n; i++) {
        if (arr[i] < av) {
            arr[i] = av;
        }
    }
}

int main()
{
    int n = 6; // Making 6 since you had it hardcoded
    int arr[n];
    replaverage(arr, n);
    for (int i = 0; i < n; i++) {
       cout << arr[i] << endl;
    }
    return 0;
}

First problem: Initialize your loop counters to 0;

Second problem: Initialize n in main being passed as parameter to
something

Third problem: Your average calculation is incorrect. It should be (f+l) / 2. Otherwise it will be doing l/2 + f, which is incorrect.

Fourth problem: You need to loop over your array to see all the
elements


问:
Unable to locate package
I am trying to enter sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev to install OpenCV on ubuntu but I keep getting the errors:

Unable to locate package libswcale-dev
and
Unable to locate package libv4l-dev

答:
Try sudo apt-get update

If no result show your /etc/apt/sources.list, please.

Title: Unable to locate package


问:
Numpy 2d array: account for border elements when modifying neighbouring elements
I'm using CodeSignal exercises to learn programming, so here it goes.
I have a 2d numpy array (called matrix) (doesn't have to be numpy though, if any better structure exists for this purpose), and 2 for loops which loop through each element in the matrix, checking if it meets some condition.
I have created a np.zeros array of the same size as the input matrix (called result), which will be populated with my result.

Back to the for loops. When the condition is met for a given element with indices i,j of matrix, I want the programme to identify all the neighbouring elements and add a 1 to each of them.

So for example if

```<code>matrix = [[True, False, False],
         [False, False, False],
         [False, False, False]]
</code>```

Then

```<code>result = [[0, 1, 0],
          [1, 1, 0],
          [0, 0, 0]]
</code>```

What I have now:

```<code>matrix = np.array(matrix)
(row, col) = matrix.shape
result = np.zeros((row,col), dtype=int)

for i in range(0, row):
    for j in range(0, col):
        print(i,j)
        if matrix[i,j] == True:
             matrix[i-1:i+2, j-1:j+2] += 1      ##problem
return result

</code>```

The problem with the line I have indicated is of course it does not work if the element is at a border, since there is no i-1 or i+2 etc.. (I tried, no error message, it just does not perform any function on the zeros matrix).
I could write a bunch of if-statements like if i == 0 or j == 0 or i == row or j == col and specify separate slicing for each, but there must be a way easier method than that, which I can not think of or find.

Thanks in advance for the help.

答:
Add up sub-matrixes:</p>

```<code>matrix = np.array(matrix)
result = np.zeros(matrix.shape, dtype=int)
result[1:,1:] += matrix[:-1,:-1]
result[1:,:] += matrix[:-1,:]
result[1:,:-1] += matrix[:-1,1:]
result[:,1:] += matrix[:,:-1]
result[:,:-1] += matrix[:,1:]
result[:-1,1:] += matrix[1:,:-1]
result[:-1,:] += matrix[1:,:]
result[:-1,:-1] += matrix[1:,1:]
</code>```

Body:
I'm using CodeSignal exercises to learn programming, so here it goes.
I have a 2d numpy array (called matrix) (doesn't have to be numpy though, if any better structure exists for this purpose), and 2 for loops which loop through each element in the matrix, checking if it meets some condition.
I have created a np.zeros array of the same size as the input matrix (called result), which will be populated with my result.

Back to the for loops. When the condition is met for a given element with indices i,j of matrix, I want the programme to identify all the neighbouring elements and add a 1 to each of them.

So for example if

matrix = [[True, False, False],
         [False, False, False],
         [False, False, False]]

Then

result = [[0, 1, 0],
          [1, 1, 0],
          [0, 0, 0]]

What I have now:

matrix = np.array(matrix)
(row, col) = matrix.shape
result = np.zeros((row,col), dtype=int)

for i in range(0, row):
    for j in range(0, col):
        print(i,j)
        if matrix[i,j] == True:
             matrix[i-1:i+2, j-1:j+2] += 1      ##problem
return result

The problem with the line I have indicated is of course it does not work if the element is at a border, since there is no i-1 or i+2 etc.. (I tried, no error message, it just does not perform any function on the zeros matrix).
I could write a bunch of if-statements like if i == 0 or j == 0 or i == row or j == col and specify separate slicing for each, but there must be a way easier method than that, which I can not think of or find.

Thanks in advance for the help.

Body:
Add up sub-matrixes:

matrix = np.array(matrix)
result = np.zeros(matrix.shape, dtype=int)
result[1:,1:] += matrix[:-1,:-1]
result[1:,:] += matrix[:-1,:]
result[1:,:-1] += matrix[:-1,1:]
result[:,1:] += matrix[:,:-1]
result[:,:-1] += matrix[:,1:]
result[:-1,1:] += matrix[1:,:-1]
result[:-1,:] += matrix[1:,:]
result[:-1,:-1] += matrix[1:,1:]


问:
Is "type" a function or class?
I'm a little confused about type as it is listed in Built-in Functions in the Python documentation.

However, when I run type(type) and type.__dict__ it looks more like a callable class. Besides that calling isinstance(type, type) returns True. What's going on?

答:
type is a type. It's the metaclass of other built-in types (including itself)

```<code>>>> type(int)
<class 'type'>
>>> type(type)
<class 'type'>
</code>```

as well as the default metaclass for user-defined types:

```<code>>>> class A: pass
...
>>> type(A)
<class 'type'>
</code>```

When called with one argument (as in the preceding examples), it returns the type of its argument. When called with three arguments (a name, a tuple of base classes, and a dict), it returns a new instance of type, as one might expect when calling a type.

```<code>>>> B = type('B', (A,), {'x': 3})
>>> type(B)
<class 'type'>
>>> B.x
3
</code>```

In fact, a class statement is a declarative syntax for a call to type. The preceding is equivalent to

```<code>class B(A):
    x = 3
</code>```

Title: Is "type" a function or class?

Body:
type is a type. It's the metaclass of other built-in types (including itself)

>>> type(int)
<class 'type'>
>>> type(type)
<class 'type'>

as well as the default metaclass for user-defined types:

>>> class A: pass
...
>>> type(A)
<class 'type'>

When called with one argument (as in the preceding examples), it returns the type of its argument. When called with three arguments (a name, a tuple of base classes, and a dict), it returns a new instance of type, as one might expect when calling a type.

>>> B = type('B', (A,), {'x': 3})
>>> type(B)
<class 'type'>
>>> B.x
3

In fact, a class statement is a declarative syntax for a call to type. The preceding is equivalent to

class B(A):
    x = 3


问:
I can't see or edit MySQL stored procedures in NetBeans
I can connect to MySQL database (5.7.23) from NetBeans (8.2) using JDBC (MySQL-AB JDBC Driver, mysql-connector-java-5.1.23). I can see tables and views, execute SQL statements and everything else with database but I cannot see or edit stored procedures (or functions) in NetBeans. I have them inside database, I can see and manage them in MySQL Workbench but cannot see them in NetBeans (folder "Procedures" in NetBeans is empty). What could be the problem?

Left in NetBeans, right in Workbench:

I have 64-bit Windows 10 Pro (1709), 64-bit NetBeans 8.2 (PHP) and 64-bit MySQL 5.7.14 (from WAMP).

答:
This is quite annoying that I still haven't found the solution for this problem. This question is more than one year old. NetBeans changed from 8.2, 9, 10, now I use 11.2 and still this functionality does not work! I changed MySQL versions, NetBeans versions, JDBC driver versions!!! I must be related to regional settings of my machine that disrupts NetBeans!

On screenshot one can see that SHOW PROCEDURE STATUS in NetBeans shows the list of my stored procedures inside database but NetBeans does not show them in navigation tree!

It's really awkward that nobody else encountered this NetBeans strange behaviour.


问:
Java: invalid selector: An invalid or illegal selector was specified
I'm trying to click an element on payment pop-up:

```<code><label data-v-533987c6="" xpath="1">Card Number:</label>
<input data-v-533987c6="" type="tel" data-mask="#### #### #### ####" data-previous-value="" xpath="1">
</code>```

with following xPath:

@FindBy(name = "//div[contains(@class,'buy-tickets')]//div/label[text()='Card Number:']/following-sibling::input")

but I receive this error:

```<code>org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=80.0.3987.87)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-VQ56FMV', ip: '192.168.0.13', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_231'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 80.0.3987.87, chrome: {chromedriverVersion: 80.0.3987.106 (f68069574609..., userDataDir: C:\Users\Nastya\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: localhost:64958}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webdriver.remote.sessionid: 3ca3f388f2b3cf47642733a6f03...}
Session ID: 3ca3f388f2b3cf47642733a6f0383c1e
*** Element info: {Using=name, value=//div[contains(@class,'buy-tickets')]//div/label[text()='Card Number:']/following-sibling::input}
</code>```

Why? Hope, you can help me!

答:
Error message is explaining itself

*** Element info: {Using=name, value=//div[contains(@class,'buy-tickets')]//div/label[text()='Card
  Number:']/following-sibling::input}

You are using xpath but selector is using name

```<code>driver.findElement(By.xpath("//label[contains(text(),'Card Number')]/following-sibling::input"));
</code>```

Body:
I'm trying to click an element on payment pop-up:

Card Number:
<input data-v-533987c6="" type="tel" data-mask="#### #### #### ####" data-previous-value="" xpath="1">

with following xPath:

@FindBy(name = "//div[contains(@class,'buy-tickets')]//div/label[text()='Card Number:']/following-sibling::input")

but I receive this error:

org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified
  (Session info: chrome=80.0.3987.87)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-VQ56FMV', ip: '192.168.0.13', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_231'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 80.0.3987.87, chrome: {chromedriverVersion: 80.0.3987.106 (f68069574609..., userDataDir: C:\Users\Nastya\AppData\Loc...}, goog:chromeOptions: {debuggerAddress: localhost:64958}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webdriver.remote.sessionid: 3ca3f388f2b3cf47642733a6f03...}
Session ID: 3ca3f388f2b3cf47642733a6f0383c1e
*** Element info: {Using=name, value=//div[contains(@class,'buy-tickets')]//div/label[text()='Card Number:']/following-sibling::input}

Why? Hope, you can help me!

Body:
Error message is explaining itself

*** Element info: {Using=name, value=//div[contains(@class,'buy-tickets')]//div/label[text()='Card
  Number:']/following-sibling::input}

You are using xpath but selector is using name

driver.findElement(By.xpath("//label[contains(text(),'Card Number')]/following-sibling::input"));


问:
SQL - Need help filtering results based on rows
I have a table that looks like this:

```<code>p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1
</code>```

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?

答:
```<code>SELECT p_id
FROM TABLE
WHERE EXISTS (SELECT P_ID from TABLE where comp_id=1) and EXISTS (SELECT P_ID from TABLE where comp_id=2)
</code>```

Body:
I have a table that looks like this:

p_id | comp_id
-----+--------
 100 | 1
 100 | 2
 101 | 1
 102 | 1

Basically, the p_id can be entered multiple times into the table for as many comp_id as needed.

What I need is to select all the p_ids that have been on comp_id 1 and 2. In the above table, that would mean only p_id == 100 would be returned.

Is there an efficient way to do this?


问:
Stanford coreNLP output.printSingletonEntities parameter doesn't work
I'm using coreNLP for coreference resolution from command line. I need the system to annotate singletons (single mentions) to be able to evaluate the output on my data, which has them annotated. I know that the system was trained on Ontonotes, which doesn't have singletons, but I found this parameter  output.printSingletonEntities which is supposed, I guess, to add singletons annotation in some heuristic way.

output.printSingletonEntities : Boolean. Whether to print singleton entity mentions in coreference output.

However, adding it into the parameters file changed absolutely nothing.
What am I doing wrong?

This is my parameter file:

annotators = tokenize,ssplit,pos,lemma,ner,parse,coref

tokenize.whitespace = true

tokenize.options = tokenizePerLine

ssplit.newlineIsSentenceBreak = always

coref.algorithm = neural

filelist = /Users/veronika/Dropbox/data/preprocessing/filelist.txt

output.printSingletonEntities = true

I also tried to call it from command line directly, but the annotation stays the same.

java -cp "" -Xmx10g edu.stanford.nlp.pipeline.StanfordCoreNLP -props /Users/veronika/Dropbox/data/sampleProps.properties -output.printSingletonEntities true*

Thank you in advance for your advices!

答: I think you need to add in -coref.removeSingletonClusters false to your settings.


问:
How to upgrade Git on Windows to the latest version
I just upgraded to Git 1.8.0.1 for Windows, from my previous version 1.7.9.mysysgit.0. I downloaded the new version from the Git site and installed through the normal Git installer EXE.

That said, when I fire up my terminal window, it still is showing that I am running Git version 1.7.9.mysysgit.0. When I type git --version from my prompt, the same thing.

I found this article on a similar issue with Git on Mac OS X, which leads me to believe that it has something to do with a faulty PATH, but I'm still pretty new at all this (five months self-taught), so I'm at a loss in how to translate this to Windows.

This problem arose when I began a new Ruby on Rails project and tried to push it up to Git. I added the remote:

```<code>git remote add origin git@github.com:brianscottk/blog.git
</code>```

then:

```<code>git push -u origin master
</code>```

I received the following error message:

fatal: https://github.com refs not found: did you run git update-server-info on the server?

Googling that error led me to this article, which prompted me to upgrade, and here I am.

答:
If you look at the most recent update on Git's website in the "git via git" section you will see an option to update your older version.

Here is the command that git has on their site:

```<code>git clone https://github.com/git/git
</code>```

It worked for my version of git which was a 2.13.0.windows.1.

Body:
I just upgraded to Git 1.8.0.1 for Windows, from my previous version 1.7.9.mysysgit.0. I downloaded the new version from the Git site and installed through the normal Git installer EXE.

That said, when I fire up my terminal window, it still is showing that I am running Git version 1.7.9.mysysgit.0. When I type git --version from my prompt, the same thing.

I found this article on a similar issue with Git on Mac OS X, which leads me to believe that it has something to do with a faulty PATH, but I'm still pretty new at all this (five months self-taught), so I'm at a loss in how to translate this to Windows.

This problem arose when I began a new Ruby on Rails project and tried to push it up to Git. I added the remote:

git remote add origin git@github.com:brianscottk/blog.git

then:

git push -u origin master

I received the following error message:

fatal: https://github.com refs not found: did you run git update-server-info on the server?

Googling that error led me to this article, which prompted me to upgrade, and here I am.

Body:
If you look at the most recent update on Git's website in the "git via git" section you will see an option to update your older version.

Here is the command that git has on their site:

git clone https://github.com/git/git

It worked for my version of git which was a 2.13.0.windows.1.


问:
Value labels in R?
Thanks for all of the support that I've recieved on here so far. It is much appreciated!

I'm trying to add value labels to an R variable.

For example, I currently have this in SPSS:

```<code>VARIABLE LABELS band_age_3 'Three-way banded age group'.

VALUE LABELS band_age_3
               1 '1-29'
               2 '30-49'
               3 '50-59'

FREQUENCIES band_age_3.
</code>```

Would this be the best method:

```<code>2019data$band_age_3 <- factor(2019data$band_age_3,
levels = c(1,2,3),
labels = c("1-29", "30-49", "50-59"))
</code>```

As with all things R related, there tends to be multiple ways of doing things and I was wondering whether this would be the most suitable.

Cheers.

Title: Value labels in R?

Body:
Thanks for all of the support that I've recieved on here so far. It is much appreciated!

I'm trying to add value labels to an R variable.

For example, I currently have this in SPSS:

VARIABLE LABELS band_age_3 'Three-way banded age group'.

VALUE LABELS band_age_3
               1 '1-29'
               2 '30-49'
               3 '50-59'

FREQUENCIES band_age_3.

Would this be the best method:

2019data$band_age_3 <- factor(2019data$band_age_3,
levels = c(1,2,3),
labels = c("1-29", "30-49", "50-59"))

As with all things R related, there tends to be multiple ways of doing things and I was wondering whether this would be the most suitable.

Cheers.

Body:
We can use a named vector for replacement

setNames(c("1-29", "30-49", "50-59"), 1:3)[as.character(`2019data`$band_age_3)]

Using a reproducible example

unname(setNames(c("1-29", "30-49", "50-59"), 1:3)[as.character(c(1, 3, 2, 1, 3))])
#[1] "1-29"  "50-59" "30-49" "1-29"  "50-59"


问:
can't install php 7.1
```<code>devall@giga:~$ sudo apt-get install php7.1
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.1
E: Couldn't find any package by glob 'php7.1'
E: Couldn't find any package by regex 'php7.1'
</code>```

I am trying to install php 7.1 , tried almost everything...

```<code>sudo apt-add-repository ppa:ondrej/php
sudo apt-get update
</code>```

reinstalled ubuntu twice.. still same error. #help

答:
try with software-properties-common

sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
sudo apt search php7
sudo apt install php7.1
php -v
```

Title: can't install php 7.1

Body:
devall@giga:~$ sudo apt-get install php7.1
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.1
E: Couldn't find any package by glob 'php7.1'
E: Couldn't find any package by regex 'php7.1'

I am trying to install php 7.1 , tried almost everything...

sudo apt-add-repository ppa:ondrej/php
sudo apt-get update

reinstalled ubuntu twice.. still same error. #help


问:
BeautifulSoup4 - Concatenating multiple html elements between two different tags
I am scraping a page using Python & bs4

The html source code that I get from bs4 is as follows (cleaned up a bit for readability purpose):

```<code><p style="text-align:justify;font-size:12.0px;font-family:Arial, Helvetica, sans-serif">
<span style="font-size:14.0px"><span style="font-family:Arial, Helvetica, sans-serif">

<strong>COMPANY DESCRIPTION</strong><br>
Here goes the first para of company description</span></span></p>

<p style="text-align:justify;font-size:12.0px;font-family:Arial, Helvetica, sans-serif">
<span style="font-size:14.0px"><span style="font-family:Arial, Helvetica, sans-serif">
Here goes the second para of company description</span></span></p>

<p><strong>PURPOSE AND OBJECTIVES</strong></p>
<p>To address requirements in the area of Supply Chain Management Extended Warehouse Management solutions, Build competencies at Solution Delivery Center to deliver solutions<br>

<strong>EXPECTATIONS AND TASKS </strong></p>
<ul>
    <li>Independently handle large implementation projects with focus on Warehouse Management processes such as inbound, outbound and internal processes. RF Device functions and Barcode support experience is desirable</li>
    <li>Able to lead EWM discussions, assessments and detail requirement studies with customers</li>
</ul>

<strong>KEY PERFORMANCE INDICATORS</strong></p>
<ul>
    <li>Customer Feedback/customer satisfaction scores</li>
    <li>Productive days/utilization as defined by the organization for projects/assessments/etc.</li>
    <li>Knowledge Management and creation of effective reusable components</li>
</ul>

<strong>EXPERIENCE REQUIREMENTS</strong></p>
<ul>
    <li>Minimum of 4+ years industry experience and a minimum of 5 to 6 years of SAP EWM experience</li>
    <li>Domain knowledge in Supply Chain Management in the areas of Planning, Manufacturing & warehousing processes is a must</li>
</ul>

<p><strong>EDUCATION AND QUALIFICATIONS/SKILLS AND COMPETENCIES</strong></p>
<ul>
    <li>Degree in Engineering or IT</li>
    <li>SAP Certification in Extended Warehouse Management (EWM) desirable</li>
</ul>

<p><span style="font-family:Arial,Helvetica,sans-serif"><span style="font-size:14.0px"><strong>WHAT YOU GET FROM US </strong></span></span></p>
</code>```

Observations:

In above code all the section headings are between   tags. The headings can vary across different pages.

My requirement:

To combine all the html text & tags starting from 2nd  tag after COMPANY DESCRIPTION i.e. from PURPOSE AND OBJECTIVES & end before the  tag containing WHAT YOU GET FROM US.

I am not looking for any solution using Selenium as it will be comparatively slow.

The page I am scraping is Link I am scraping

Here is my peice of python code:

```<code>def scrape_url(url, method='bs4'):
    session = requests.session()
    page = session.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    return soup

url = 'https://jobs.sap.com/job/Mumbai-Senior-Account-Executive-Job-MH/539212101/'
soup = scrape_url(url)
job_page = soup.body.find('div', attrs={'class': 'job'})
print(job_page)

</code>```

答:
First identify the tag with text using regular expression and then use find_next_siblings() to get all next siblings and then check if any siblings contains the text WHAT YOU GET FROM US

Code:

```<code>import re
import requests
from bs4 import BeautifulSoup
def scrape_url(url, method='bs4'):
    session = requests.session()
    page = session.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    return soup

url = 'https://jobs.sap.com/job/Kuala-Lumpur-Business-Processes-Consultant-%28FICO%29-Job-14/541909901/'
soup = scrape_url(url)
findtag=soup.find('p',text=re.compile("PURPOSE AND OBJECTIVES"))
print(findtag.text)
for item in findtag.find_next_siblings():
    if 'WHAT YOU GET FROM US' in item.text:
        break
    else:
        print(item.text.strip())
</code>```

Output: On console

```<code>PURPOSE AND OBJECTIVES

To address requirements in the area of Supply Chain Management Extended Warehouse Management solutions, Build competencies at Solution Delivery Center to deliver solutions especially in areas relating to SAP EWM

EXPECTATIONS AND TASKS

Independently handle large implementation projects with focus on Warehouse Management processes such as inbound, outbound and internal processes. RF Device functions and Barcode support experience is desirable
Able to lead EWM discussions, assessments and detail requirement studies with customers
Leading the team that are assigned to, in functional capacity, adding value to the project and to the final deliverables
Be actively involved in the preparation, conception, realization and Go Live of customer implementation projects
Demonstrate the ability to plan, run, and manage blueprint workshops / meetings with internal and external clients
Responsible for defining the scope of a project / opportunities, estimating efforts and project timelines
Participating in RFP discussions and estimating under guidance from a Bid Manager
Providing a creative source of ideas/solutions to address problems
Delivering billable components that meets a customer’s needs
KEY PERFORMANCE INDICATORS

Customer Feedback/customer satisfaction scores
Productive days/utilization as defined by the organization for projects/assessments/etc.
Knowledge Management and creation of effective reusable components
EXPERIENCE REQUIREMENTS

Minimum of 4+ years industry experience and a minimum of 5 to 6 years of SAP EWM experience
Domain knowledge in Supply Chain Management in the areas of Planning, Manufacturing & warehousing processes is a must
Must have strong ERP implementation experience
Experience in SAP Material Flow Systems (MFS) or any other third party automation tools will be desirable
Experience in EWM technical knowledge will be an added advantage
Knowledge on SAP S/4HANA Public Cloud solution and SAP IOT/Leonardo portfolio will be preferred but not mandatory
Good understanding of S/4HANA Order to Cash and Procure to Pay business processes
Good understanding of SAP ACTIVATE implementation methodology
Use of Solution Manager as a part of implementation life cycle is desirable
Good Communication skill in English.

EDUCATION AND QUALIFICATIONS/SKILLS AND COMPETENCIES

Degree in Engineering or IT
SAP Certification in Extended Warehouse Management (EWM) desirable
Minimum 4 to 5 full life cycle SAP EWM implementations
Strong knowledge in SAP SCM Extended Warehouse Management Solutions and S/4HANA Embedded EWM Solution
Good integration knowledge with other components with SAP S/4HANA (WM, SD, MM, PP) and other SAP or Non-SAP legacy applications
Knowledge of SCOR, APICS certification preferable
Strong client-facing experience and well-developed customer focus
Solid oral and written communication skills, with the demonstrated ability to communicate complex technical topics to management and non-technical audiences
Mobility is must – candidate must be ready to travel to project locations (short term and long term)
</code>```

Body:
I am scraping a page using Python & bs4

The html source code that I get from bs4 is as follows (cleaned up a bit for readability purpose):

COMPANY DESCRIPTION

Here goes the first para of company description

Here goes the second para of company description

PURPOSE AND OBJECTIVES

To address requirements in the area of Supply Chain Management Extended Warehouse Management solutions, Build competencies at Solution Delivery Center to deliver solutions

EXPECTATIONS AND TASKS

Independently handle large implementation projects with focus on Warehouse Management processes such as inbound, outbound and internal processes. RF Device functions and Barcode support experience is desirable

Able to lead EWM discussions, assessments and detail requirement studies with customers

KEY PERFORMANCE INDICATORS

Customer Feedback/customer satisfaction scores

Productive days/utilization as defined by the organization for projects/assessments/etc.

Knowledge Management and creation of effective reusable components

EXPERIENCE REQUIREMENTS

Minimum of 4+ years industry experience and a minimum of 5 to 6 years of SAP EWM experience

Domain knowledge in Supply Chain Management in the areas of Planning, Manufacturing & warehousing processes is a must

EDUCATION AND QUALIFICATIONS/SKILLS AND COMPETENCIES

Degree in Engineering or IT

SAP Certification in Extended Warehouse Management (EWM) desirable

WHAT YOU GET FROM US

Observations:

In above code all the section headings are between   tags. The headings can vary across different pages.

My requirement:

To combine all the html text & tags starting from 2nd  tag after COMPANY DESCRIPTION i.e. from PURPOSE AND OBJECTIVES & end before the  tag containing WHAT YOU GET FROM US.

I am not looking for any solution using Selenium as it will be comparatively slow.

The page I am scraping is Link I am scraping

Here is my peice of python code:

def scrape_url(url, method='bs4'):
    session = requests.session()
    page = session.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    return soup

url = 'https://jobs.sap.com/job/Mumbai-Senior-Account-Executive-Job-MH/539212101/'
soup = scrape_url(url)
job_page = soup.body.find('div', attrs={'class': 'job'})
print(job_page)

Body:
First identify the tag with text using regular expression and then use find_next_siblings() to get all next siblings and then check if any siblings contains the text WHAT YOU GET FROM US

Code:

import re
import requests
from bs4 import BeautifulSoup
def scrape_url(url, method='bs4'):
    session = requests.session()
    page = session.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    return soup

url = 'https://jobs.sap.com/job/Kuala-Lumpur-Business-Processes-Consultant-%28FICO%29-Job-14/541909901/'
soup = scrape_url(url)
findtag=soup.find('p',text=re.compile("PURPOSE AND OBJECTIVES"))
print(findtag.text)
for item in findtag.find_next_siblings():
    if 'WHAT YOU GET FROM US' in item.text:
        break
    else:
        print(item.text.strip())

Output: On console

PURPOSE AND OBJECTIVES

To address requirements in the area of Supply Chain Management Extended Warehouse Management solutions, Build competencies at Solution Delivery Center to deliver solutions especially in areas relating to SAP EWM

EXPECTATIONS AND TASKS

Independently handle large implementation projects with focus on Warehouse Management processes such as inbound, outbound and internal processes. RF Device functions and Barcode support experience is desirable
Able to lead EWM discussions, assessments and detail requirement studies with customers
Leading the team that are assigned to, in functional capacity, adding value to the project and to the final deliverables
Be actively involved in the preparation, conception, realization and Go Live of customer implementation projects
Demonstrate the ability to plan, run, and manage blueprint workshops / meetings with internal and external clients
Responsible for defining the scope of a project / opportunities, estimating efforts and project timelines
Participating in RFP discussions and estimating under guidance from a Bid Manager
Providing a creative source of ideas/solutions to address problems
Delivering billable components that meets a customer’s needs
KEY PERFORMANCE INDICATORS

Customer Feedback/customer satisfaction scores
Productive days/utilization as defined by the organization for projects/assessments/etc.
Knowledge Management and creation of effective reusable components
EXPERIENCE REQUIREMENTS

Minimum of 4+ years industry experience and a minimum of 5 to 6 years of SAP EWM experience
Domain knowledge in Supply Chain Management in the areas of Planning, Manufacturing & warehousing processes is a must
Must have strong ERP implementation experience
Experience in SAP Material Flow Systems (MFS) or any other third party automation tools will be desirable
Experience in EWM technical knowledge will be an added advantage
Knowledge on SAP S/4HANA Public Cloud solution and SAP IOT/Leonardo portfolio will be preferred but not mandatory
Good understanding of S/4HANA Order to Cash and Procure to Pay business processes
Good understanding of SAP ACTIVATE implementation methodology
Use of Solution Manager as a part of implementation life cycle is desirable
Good Communication skill in English.

EDUCATION AND QUALIFICATIONS/SKILLS AND COMPETENCIES

Degree in Engineering or IT
SAP Certification in Extended Warehouse Management (EWM) desirable
Minimum 4 to 5 full life cycle SAP EWM implementations
Strong knowledge in SAP SCM Extended Warehouse Management Solutions and S/4HANA Embedded EWM Solution
Good integration knowledge with other components with SAP S/4HANA (WM, SD, MM, PP) and other SAP or Non-SAP legacy applications
Knowledge of SCOR, APICS certification preferable
Strong client-facing experience and well-developed customer focus
Solid oral and written communication skills, with the demonstrated ability to communicate complex technical topics to management and non-technical audiences
Mobility is must – candidate must be ready to travel to project locations (short term and long term)


问:
In Rust, is there a function for continuously "folding" a stream, i.e. mapping with state?
I have a futures::stream::Stream of websocket messages that represent state changes, and I want a stream of the state. I've come across the fold method which does something similar, but it collects everything up into one final state, rather than producing a new stream of all the intermediate states.

E.g. I have an initial state "0" and a stream of "increment" and "decrement" events, I want a stream of the resulting numbers.

答:
In the Iterator world, scan would be the appropriate adapter for this job. But a Stream is not an Iterator, so we can't use Iterator's methods.

The StreamExt trait provides extension methods for the Stream trait. Many of these methods are adapted versions of Iterator's adapter methods. This includes scan.


问:
passing php variable into html
I'm new to php so pardon the ignorance

I'm trying to include a php variable, it is and is not working.

```<code>$currentdata = file_get_contents("http://www.abr.business.gov.au/abnDetails.aspx?abn=$abn");
</code>```

This works with $abn being the variable being passed from earlier being set.

```<code>$abntypedata = '/d$abn&ResultListURL=">(.+?)</'; This does not work.
$abntypedata = '/d33051775556&ResultListURL=">(.+?)</'; This does.
</code>```

I need to be able to use the variable $abn to insert that number as it will be user defined. Why is this not working?

答:
You can't use inline variables like that in single-quoted strings.</p>

```<code>$abntypedata = "/d$abn&ResultListURL=\">(.+?)</";
</code>```

Title: passing php variable into html

Body:
I'm new to php so pardon the ignorance

I'm trying to include a php variable, it is and is not working.

$currentdata = file_get_contents("http://www.abr.business.gov.au/abnDetails.aspx?abn=$abn");

This works with $abn being the variable being passed from earlier being set.

$abntypedata = '/d$abn&ResultListURL=">(.+?)</'; This does not work.
$abntypedata = '/d33051775556&ResultListURL=">(.+?)</'; This does.

I need to be able to use the variable $abn to insert that number as it will be user defined. Why is this not working?

Body:
You can't use inline variables like that in single-quoted strings.

$abntypedata = "/d$abn&amp;ResultListURL=\">(.+?)</";


问:
Relative import in Python package does not seem to work
I have a package which is structured as follows:

```<code>mypackage/
  util/
    __init__.py
    a.py
  b.py
  __init__.py
  setup.py
</code>```

The __init__.py files are empty. In b.py there is an import of util/a.py:

```<code>from .util import a
</code>```

The tests included with the package run fine. However, when I install the package and try to use it in another project with from mypackage import b, I get:

```<code>File [...] , in <module>
    from mypackage import b
File "/usr/local/lib/python3.7/site-packages/mypackage-0.0.1-py3.7.egg/mypackage/b.py", line 1, in <module>
    from .util import a
ModuleNotFoundError: No module named 'mypackage.util'
</code>```

Edit 1

setup.py looks like this:

```<code>from setuptools import setup

setup(name="mypackage",
      version="0.0.1",
      description="My package",
      packages=["mypackage"])
</code>```

答:
You have to include that sub-package in the call to setup otherwise it won't be installed:

```<code>setup(
    ...
    packages=[
        'mypackage',
        'mypackage.util',
    ]
)
</code>```

You can also use setuptools.find_packages in order to automatize this process:

```<code>from setuptools import find_packages

setup(..., packages=find_packages())
</code>```

Body:
I have a package which is structured as follows:

mypackage/
  util/
    __init__.py
    a.py
  b.py
  __init__.py
  setup.py

The __init__.py files are empty. In b.py there is an import of util/a.py:

from .util import a

The tests included with the package run fine. However, when I install the package and try to use it in another project with from mypackage import b, I get:

File [...] , in <module>
    from mypackage import b
File "/usr/local/lib/python3.7/site-packages/mypackage-0.0.1-py3.7.egg/mypackage/b.py", line 1, in <module>
    from .util import a
ModuleNotFoundError: No module named 'mypackage.util'

Edit 1

setup.py looks like this:

from setuptools import setup

setup(name="mypackage",
      version="0.0.1",
      description="My package",
      packages=["mypackage"])

Body:
You have to include that sub-package in the call to setup otherwise it won't be installed:

setup(
    ...
    packages=[
        'mypackage',
        'mypackage.util',
    ]
)

You can also use setuptools.find_packages in order to automatize this process:

from setuptools import find_packages

setup(..., packages=find_packages())


问:
How to get exact scroll position when animating elements onScroll
I am trying to animate elements while scrolling based on the elements progress through the scene. I am running into the issue of the browser returning intermittent scroll positions making it difficult to be exact when starting and stopping element animation.

Minimal example:

Fiddle Fiddle Demo

const tweens = document.querySelectorAll('.tween');
const trigger = document.querySelector('.start');
const triggerRect = trigger.getBoundingClientRect();

let yScroll = window.scrollY;
let yCurrent = yScroll;
let AF = null;

const start = triggerRect.top - yScroll - 200;
const end = start + 400;

const updateScroll = () => {
 yScroll = window.scrollY;
  startAnimation();
}

const startAnimation = () => {
  if(!AF) AF = requestAnimationFrame(animate)
}

const cancelAnimation = () => {
  yCurrent = yScroll;
  cancelAnimationFrame(AF);
  AF = null;
}

const animate = () => {
  if(yCurrent === yScroll) cancelAnimation();
  else {
   updateElements();
    yCurrent = yScroll;
    AF = requestAnimationFrame(animate);
  }
}

const updateElements = () => {
  const pos = yCurrent - start;
  if(inScene()){
    tweens[0].style.transform = `translateX(${pos}px)`;
    tweens[1].style.transform = `translateY(${pos}px)`;
  }
}

const inScene = () => {
  return start <= yCurrent && end >= yCurrent ? true : false;
};

window.addEventListener('scroll', updateScroll);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper{
  position:relative;
  margin: 100vh 20px;
  background: rgb(240,240,240);
  height: 900px;
  border: 1px solid red;
}

.line{
  position:absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: red;
}

.start{
  top: 200px;
}

.end{
  bottom: 200px;
}

.tween{
  position:absolute;
  top:200px;
  width: 100px;
  height: 100px;
  background: blue;
}

.left{
  left: 0;
}

.right{
  right: 0;
}</code>```

Scroll Down

```

As you can see the elements are supposed to stop on the lines but when you scroll they never really do.  And the faster you scroll the worse it becomes.

So is there a technique to either return the correct scroll position or somehow debounce the elements so then can reach the full range when scrolling instead of constantly coming up short of their intended position?

I know this is possible because scrolling libraries like ScrollMagic do a pretty good job of handling this but I don't really want to deconstruct then entire ScrollMagic framework to find out how they achieve it.  I would use the ScrollMagic framework itself but I am trying to have a momentum style scrolling container wrapping the page and translating it on scroll along with elements inside this container and using ScrollMagic it is pretty buggy.  So I figured I would post the question here and see if anyone had any experience or insight on the situation.

Any guidance would be appreciated as I have been mulling over this for a while.

答:
https://jsfiddle.net/b2pqndvh/

First, you need to set “boundaries” like Math.min(END, Math.max(0, scrollY - start)); if there is not enough time to update a position by scrolling. Second, I would recommend removing requestAnimationFrame, because this method tells the browser that you wish to perform an update after the next repaint. That's why it looks more clunky with it. The performance tests (in chrome and firefox) shows that performance doesn't suffer without requestAnimationFrame in this example, but it may suffer from the more complex layout.

const tweens = document.querySelectorAll('.tween');
const trigger = document.querySelector('.start');
const triggerRect = trigger.getBoundingClientRect();

const START = 0;
const MIDDLE = 200;
const END = 400;

const start = triggerRect.top - window.scrollY - MIDDLE;
const end = start + END;

const inSceneStart = scrollY => start <= scrollY;
const inSceneEnd = scrollY => end >= scrollY;

const updateTransform = value => {
  tweens[0].style.transform = `translateX(${value}px)`;
  tweens[1].style.transform = `translateY(${value}px)`;
}

const updateScroll = () => {
  const scrollY = window.scrollY;
  const pos = Math.min(END, Math.max(0, scrollY - start));
  updateTransform(pos);
}

window.addEventListener('scroll', updateScroll);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper{
  position:relative;
  margin: 100vh 20px;
  background: rgb(240,240,240);
  height: 900px;
}

.line{
  position:absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: red;
}

.start{
  top: 200px;
}

.end{
  bottom: 200px;
}

.tween{
  position:absolute;
  top:200px;
  width: 100px;
  height: 100px;
  background: blue;
}

.left{
  left: 0;
}

.right{
  right: 0;
}</code>```

Scroll Down

```

Body:
I am trying to animate elements while scrolling based on the elements progress through the scene. I am running into the issue of the browser returning intermittent scroll positions making it difficult to be exact when starting and stopping element animation.

Minimal example:

Fiddle Fiddle Demo

const tweens = document.querySelectorAll('.tween');
const trigger = document.querySelector('.start');
const triggerRect = trigger.getBoundingClientRect();

let yScroll = window.scrollY;
let yCurrent = yScroll;
let AF = null;

const start = triggerRect.top - yScroll - 200;
const end = start + 400;

const updateScroll = () => {
 yScroll = window.scrollY;
  startAnimation();
}

const startAnimation = () => {
  if(!AF) AF = requestAnimationFrame(animate)
}

const cancelAnimation = () => {
  yCurrent = yScroll;
  cancelAnimationFrame(AF);
  AF = null;
}

const animate = () => {
  if(yCurrent === yScroll) cancelAnimation();
  else {
   updateElements();
    yCurrent = yScroll;
    AF = requestAnimationFrame(animate);
  }
}

const updateElements = () => {
  const pos = yCurrent - start;
  if(inScene()){
    tweens[0].style.transform = `translateX(${pos}px)`;
    tweens[1].style.transform = `translateY(${pos}px)`;
  }
}

const inScene = () => {
  return start <= yCurrent && end >= yCurrent ? true : false;
};

window.addEventListener('scroll', updateScroll);

.wrapper{
  position:relative;
  margin: 100vh 20px;
  background: rgb(240,240,240);
  height: 900px;
  border: 1px solid red;
}

.line{
  position:absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: red;
}

.start{
  top: 200px;
}

.end{
  bottom: 200px;
}

.tween{
  position:absolute;
  top:200px;
  width: 100px;
  height: 100px;
  background: blue;
}

.left{
  left: 0;
}

.right{
  right: 0;
}

Scroll Down

As you can see the elements are supposed to stop on the lines but when you scroll they never really do.  And the faster you scroll the worse it becomes.

So is there a technique to either return the correct scroll position or somehow debounce the elements so then can reach the full range when scrolling instead of constantly coming up short of their intended position?

I know this is possible because scrolling libraries like ScrollMagic do a pretty good job of handling this but I don't really want to deconstruct then entire ScrollMagic framework to find out how they achieve it.  I would use the ScrollMagic framework itself but I am trying to have a momentum style scrolling container wrapping the page and translating it on scroll along with elements inside this container and using ScrollMagic it is pretty buggy.  So I figured I would post the question here and see if anyone had any experience or insight on the situation.

Any guidance would be appreciated as I have been mulling over this for a while.

Body:
https://jsfiddle.net/b2pqndvh/

First, you need to set “boundaries” like Math.min(END, Math.max(0, scrollY - start)); if there is not enough time to update a position by scrolling. Second, I would recommend removing requestAnimationFrame, because this method tells the browser that you wish to perform an update after the next repaint. That's why it looks more clunky with it. The performance tests (in chrome and firefox) shows that performance doesn't suffer without requestAnimationFrame in this example, but it may suffer from the more complex layout.

const tweens = document.querySelectorAll('.tween');
const trigger = document.querySelector('.start');
const triggerRect = trigger.getBoundingClientRect();

const START = 0;
const MIDDLE = 200;
const END = 400;

const start = triggerRect.top - window.scrollY - MIDDLE;
const end = start + END;

const inSceneStart = scrollY => start <= scrollY;
const inSceneEnd = scrollY => end >= scrollY;

const updateTransform = value => {
  tweens[0].style.transform = `translateX(${value}px)`;
  tweens[1].style.transform = `translateY(${value}px)`;
}

const updateScroll = () => {
  const scrollY = window.scrollY;
  const pos = Math.min(END, Math.max(0, scrollY - start));
  updateTransform(pos);
}

window.addEventListener('scroll', updateScroll);

.wrapper{
  position:relative;
  margin: 100vh 20px;
  background: rgb(240,240,240);
  height: 900px;
}

.line{
  position:absolute;
  left: 0;
  width: 100%;
  height: 1px;
  background: red;
}

.start{
  top: 200px;
}

.end{
  bottom: 200px;
}

.tween{
  position:absolute;
  top:200px;
  width: 100px;
  height: 100px;
  background: blue;
}

.left{
  left: 0;
}

.right{
  right: 0;
}

<h1>Scroll Down</h1>
<div class="wrapper">
  <div class="line start trigger"></div>
  <div class="line end"></div>
  <div class="tween left"></div>
  <div class="tween right"></div>
</div>


问:
Member Function Call and the C++ Object Model
Consider the below code that is designed to study how member functions calls are made and how it relates to C++'s object model:

```<code>struct A {
  int a_;
};
struct B : A {
  int b_;
  void f();
};
void B::f() {
  std::cout << "this\t" << std::hex << this << '\n';
}
struct C: B {
  int c_;
};
int main()
{
  C c;
  C* pc = &c;
  std::cout << "&c\t" << std::hex << pc << '\n';
  pc->f();
  return 0;
}
</code>```

Based on the C++ object model, object c will have the object layout:

```<code>  -------
 | a_    |
 |------ |
 | b_    |
 |------ |
 | c_    |
  -------
</code>```

And,

B::f() would be translated to void f(B *const)

pc->f() would be translated to void f(pc + offset(b_)), where offset(b_) represents the offset of sub-object B in c.

So, based on the above observations, the output should be:

```<code>&c     address_of_c
this   address_of_c + sizeof(a_) = address_of_c + 4
</code>```

But what I'm getting is the same address for both (I'm using g++ 9.2):

```<code>&c      0xffffcc0c
this    0xffffcc0c
</code>```

I'm not clear as to why? Can someone please explain?

FYI: Bjarne Stroustrup has an article written about this; more specifically, you can refer to section 4.2 (page 373):

https://www.usenix.org/legacy/publications/compsystems/1989/fall_stroustrup.pdf

Thanks!

答:
Class C inherits only one class B. So you have

```<code>struct B
   ^
   |
   |
struct C
</code>```

When an object of the class C was created the sub-object of the class B was placed in the beginning of the memory allocated for the object of the class C.

Within the object of the class B there is a sub-object of the class A.

You can imagine the placement of an object of the class C the following way

```<code>struct B b;
int c_;
</code>```

Body:
Consider the below code that is designed to study how member functions calls are made and how it relates to C++'s object model:

struct A {
  int a_;
};
struct B : A {
  int b_;
  void f();
};
void B::f() {
  std::cout << "this\t" << std::hex << this << '\n';
}
struct C: B {
  int c_;
};
int main()
{
  C c;
  C* pc = &c;
  std::cout << "&c\t" << std::hex << pc << '\n';
  pc->f();
  return 0;
}

Based on the C++ object model, object c will have the object layout:

  -------
 | a_    |
 |------ |
 | b_    |
 |------ |
 | c_    |
  -------

And,

B::f() would be translated to void f(B *const)

pc->f() would be translated to void f(pc + offset(b_)), where offset(b_) represents the offset of sub-object B in c.

So, based on the above observations, the output should be:

&c     address_of_c
this   address_of_c + sizeof(a_) = address_of_c + 4

But what I'm getting is the same address for both (I'm using g++ 9.2):

&c      0xffffcc0c
this    0xffffcc0c

I'm not clear as to why? Can someone please explain?

FYI: Bjarne Stroustrup has an article written about this; more specifically, you can refer to section 4.2 (page 373):

https://www.usenix.org/legacy/publications/compsystems/1989/fall_stroustrup.pdf

Thanks!

Body:
Class C inherits only one class B. So you have

struct B
   ^
   |
   |
struct C

When an object of the class C was created the sub-object of the class B was placed in the beginning of the memory allocated for the object of the class C.

Within the object of the class B there is a sub-object of the class A.

You can imagine the placement of an object of the class C the following way

struct B b;
int c_;


问:
How can I use regex to find data between quotation marks?
I need to extract data which is between the single quotes.

```<code>"request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>"
</code>```

I did try:
^"request="'*' but doesn;t work

答:
if you need the data BETWEEN the single quates, use look-behind and look-ahead in the matched pattern:</p>

```<code>(?<=').*(?=')
</code>```

Body:
I need to extract data which is between the single quotes.

"request='fgj234fgj9da41c76a8bc7d470kjykl89a5d'>"

I did try:
^"request="'*' but doesn;t work

Body:
if you need the data BETWEEN the single quates, use look-behind and look-ahead in the matched pattern:

(?<=').*(?=')