问:
What algorithm does ByteBuddy's ElementMatchers#nameStartsWith use?
Let's suppose that I want to apply an @Advice.OnMethodEnter to the methods declared in org.springframework.web.context.support.GenericWebApplicationContext. To do that, I've written this minimal agent:

public class SequenceAgent {

  public static void premain(final String args,
                             final Instrumentation instrumentation) {
    new AgentBuilder.Default()
        .with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
        .type(nameStartsWith(
            "org.springframework.web.context.support.GenericWebApplicationContext"))
        .transform((builder, typeDescription, classLoader, module) -> builder
            .method(any()).intercept(Advice.to(SequenceAdvice.class)))
        .installOn(instrumentation);
  }

  public static class SequenceAdvice {

    @Advice.OnMethodEnter
    static void enter(@Advice.This Object thiz, @Advice.Origin Method method,
                      @Advice.AllArguments Object... args) {
      String className = thiz.getClass().getName();
      String methodName = method.getName();

      System.out.println("Entered: " + className + "#" + methodName);
    }
  }
}
```

<p>I expected this configuration to filter out <code>org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext</code> as it doesn't match <code>org.springframework.web.context.support.GenericWebApplicationContext</code> but looks like invocation of methods on objects of this class are also intercepted:</p>

<pre class="lang-java prettyprint-override"><code>import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;

public class AgentTest {

    public static void main(String[] args) {
        AnnotationConfigServletWebServerApplicationContext context =
                new AnnotationConfigServletWebServerApplicationContext();

        context.containsBean("SomeBean");
    }

}
</code>```

When attached to the agent and ran, it prints out (wrapped for readability):

```<code>Entered: org.springframework.boot.web.servlet.context.
    AnnotationConfigServletWebServerApplicationContext
    #getResourcePatternResolver
.
.
.
Entered: org.springframework.boot.web.servlet.context.
    AnnotationConfigServletWebServerApplicationContext
    #getResourceCache

Entered: org.springframework.boot.web.servlet.context.
    AnnotationConfigServletWebServerApplicationContext
    #getClassLoader

Entered: org.springframework.boot.web.servlet.context.
    AnnotationConfigServletWebServerApplicationContext
    #containsBean
</code>```

And the class hierarchy for org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServe.ApplicationContext is:

```<code>org.springframework.core.io.DefaultResourceLoader
        ⇧
org.springframework.context.support.AbstractApplicationContext
        ⇧
org.springframework.context.support.GenericApplicationContext
        ⇧
⤏⤏⤏⤏ org.springframework.web.context.support.GenericWebApplicationContext
        ⇧
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext
        ⇧
org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServe.ApplicationContext
</code>```

And the containsBean method is declared and overridden in:

```<code>org.springframework.beans.factory.BeanFactory#containsBean
        ⇧
org.springframework.context.support.AbstractApplicationContext#containsBean
</code>```

Why for containsBean, @Advice.This Object thiz is resolved to org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext and not org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext?

答:
Byte Buddy uses String.startsWith.

What you are seeing is due to Byte Buddy instrumenting classes, not instances. In a way, think of Byte Buddy copying the advice code into the target method.

As a result, all subclasses will be affected. For doing what you are doing, you need to check the instance class's type during invocation, just as if you wanted to implement this in Java.

Body:
Let's suppose that I want to apply an @Advice.OnMethodEnter to the methods declared in org.springframework.web.context.support.GenericWebApplicationContext. To do that, I've written this minimal agent:

public class SequenceAgent {

  public static void premain(final String args,
                             final Instrumentation instrumentation) {
    new AgentBuilder.Default()
        .with(new AgentBuilder.InitializationStrategy.SelfInjection.Eager())
        .type(nameStartsWith(
            "org.springframework.web.context.support.GenericWebApplicationContext"))
        .transform((builder, typeDescription, classLoader, module) -> builder
            .method(any()).intercept(Advice.to(SequenceAdvice.class)))
        .installOn(instrumentation);
  }

  public static class SequenceAdvice {

    @Advice.OnMethodEnter
    static void enter(@Advice.This Object thiz, @Advice.Origin Method method,
                      @Advice.AllArguments Object... args) {
      String className = thiz.getClass().getName();
      String methodName = method.getName();

      System.out.println("Entered: " + className + "#" + methodName);
    }
  }
}

I expected this configuration to filter out org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext as it doesn't match org.springframework.web.context.support.GenericWebApplicationContext but looks like invocation of methods on objects of this class are also intercepted:

import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;

public class AgentTest {

    public static void main(String[] args) {
        AnnotationConfigServletWebServerApplicationContext context =
                new AnnotationConfigServletWebServerApplicationContext();

        context.containsBean("SomeBean");
    }

}

When attached to the agent and ran, it prints out (wrapped for readability):

Entered: org.springframework.boot.web.servlet.context.
    AnnotationConfigServletWebServerApplicationContext
    #getResourcePatternResolver
.
.
.
Entered: org.springframework.boot.web.servlet.context.
    AnnotationConfigServletWebServerApplicationContext
    #getResourceCache

Entered: org.springframework.boot.web.servlet.context.
    AnnotationConfigServletWebServerApplicationContext
    #getClassLoader

Entered: org.springframework.boot.web.servlet.context.
    AnnotationConfigServletWebServerApplicationContext
    #containsBean

And the class hierarchy for org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServe.ApplicationContext is:

org.springframework.core.io.DefaultResourceLoader
        ⇧
org.springframework.context.support.AbstractApplicationContext
        ⇧
org.springframework.context.support.GenericApplicationContext
        ⇧
⤏⤏⤏⤏ org.springframework.web.context.support.GenericWebApplicationContext
        ⇧
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext
        ⇧
org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServe.ApplicationContext

And the containsBean method is declared and overridden in:

org.springframework.beans.factory.BeanFactory#containsBean
        ⇧
org.springframework.context.support.AbstractApplicationContext#containsBean

Why for containsBean, @Advice.This Object thiz is resolved to org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext and not org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext?


来源: stackexchange

问:
grouping of elements of same type together in an array in O(1) Space and O(n) time
This is a problem from Elements of programming interviews book.

Question:

Given an array of n objects with keys that takes on of four values, reorder the array so that the objects that have the same type appear together. Use O(1) additional space and O(n) time.

I am unable to conceive an idea for more than three groups(Dutch National flag problem). Any help would be really appreciated.

For example a[6]={1,2,3,4,3,1}; Then the result should be {1,1,2,3,3,4} or in any order, only the grouping of numbers matters( ie, the result need not be in ascending order)

答:
The O(n) DNF solution forms two sets starting from the lowest and the highest indices, and knows that the third set forming somewhere between them is homogeneous, and thus needs no further treatment.

If you increase the number of sets to four or more, you can still form the top and bottom sets in the same "spirit", and thus in O(n) time, but the middle part remains being mixed, it has to be checked again. And that is why it will not be "pure" O(n) any more - there are only two ends of an array/sequence.

```<code>int a[] = { 1,2,3,4,3,1,2,3,3,4 };
int size = sizeof(a) / sizeof(int);

int bottom = 0, top = size - 1;
for (int bottomband = 1, topband = 4; topband > bottomband; bottomband++, topband--) {
    int i = bottom;
    while (i <= top) {
        if (a[i] == bottomband) {
            swap(a[i], a[bottom]);
            i++;
            bottom++;
        }
        else if (a[i] == topband) {
            swap(a[i], a[top]);
            top--;
        }
        else
            i++;
    }
}

for (int i = 0; i<size; ++i) {
    cout << a[i] << " ";
}
</code>```

You can recognize the "classic" DNF loop inside (when topband starts from 3 it simply becomes the original algorithm). a[] is taken from the other solution for comparability.

There is a thing which is often paraphrased as The difference between theory and practice is greater in practice than in theory. Counting the swap calls shows that there are 10 of them, which also applies to Vivek's solution. That is part coincidence and part the fact that both solutions are happily swapping identical elements, as only the "current" one is checked, the other one (sitting at bottom, top or ptr) is not. For example the very first thing both algorithms do is to swap the 1 at the beginning of the list with itself.

Via skipping continuous blocks of identical elements (it has to be done both at changing the band and at adjusting the marker), the code grows...

```<code>int bottom = 0, top = size - 1;
for (int bottomband = 1, topband = 4; topband > bottomband; bottomband++, topband--) {
    while (a[bottom] == bottomband)bottom++;
    while (a[top] == topband)top--;
    int i = bottom;
    while (i <= top) {
        if (a[i] == bottomband) {
            swap(a[i], a[bottom]);
            i++;
            bottom++; // it would be done by the next line in fact
            while (a[bottom] == bottomband)bottom++;
        }
        else if (a[i] == topband) {
            swap(a[i], a[top]);
            top--; // this one too
            while (a[top] == topband)top--;
        }
        else
            i++;
    }
}
</code>```

...and the number of calls to swap decreases to 6. While the complexity class has not changed (I think), the number of actual calls to a potentionally expensive operation has been reduced by 40%. That is the difference between theory and practice.

ContentLicense: CC BY-SA 4.0

Body:
The O(n) DNF solution forms two sets starting from the lowest and the highest indices, and knows that the third set forming somewhere between them is homogeneous, and thus needs no further treatment.

If you increase the number of sets to four or more, you can still form the top and bottom sets in the same "spirit", and thus in O(n) time, but the middle part remains being mixed, it has to be checked again. And that is why it will not be "pure" O(n) any more - there are only two ends of an array/sequence.

int a[] = { 1,2,3,4,3,1,2,3,3,4 };
int size = sizeof(a) / sizeof(int);

int bottom = 0, top = size - 1;
for (int bottomband = 1, topband = 4; topband > bottomband; bottomband++, topband--) {
    int i = bottom;
    while (i <= top) {
        if (a[i] == bottomband) {
            swap(a[i], a[bottom]);
            i++;
            bottom++;
        }
        else if (a[i] == topband) {
            swap(a[i], a[top]);
            top--;
        }
        else
            i++;
    }
}

for (int i = 0; i<size; ++i) {
    cout << a[i] << " ";
}

You can recognize the "classic" DNF loop inside (when topband starts from 3 it simply becomes the original algorithm). a[] is taken from the other solution for comparability.

There is a thing which is often paraphrased as The difference between theory and practice is greater in practice than in theory. Counting the swap calls shows that there are 10 of them, which also applies to Vivek's solution. That is part coincidence and part the fact that both solutions are happily swapping identical elements, as only the "current" one is checked, the other one (sitting at bottom, top or ptr) is not. For example the very first thing both algorithms do is to swap the 1 at the beginning of the list with itself.

Via skipping continuous blocks of identical elements (it has to be done both at changing the band and at adjusting the marker), the code grows...

int bottom = 0, top = size - 1;
for (int bottomband = 1, topband = 4; topband > bottomband; bottomband++, topband--) {
    while (a[bottom] == bottomband)bottom++;
    while (a[top] == topband)top--;
    int i = bottom;
    while (i <= top) {
        if (a[i] == bottomband) {
            swap(a[i], a[bottom]);
            i++;
            bottom++; // it would be done by the next line in fact
            while (a[bottom] == bottomband)bottom++;
        }
        else if (a[i] == topband) {
            swap(a[i], a[top]);
            top--; // this one too
            while (a[top] == topband)top--;
        }
        else
            i++;
    }
}

...and the number of calls to swap decreases to 6. While the complexity class has not changed (I think), the number of actual calls to a potentionally expensive operation has been reduced by 40%. That is the difference between theory and practice.


问:
Dynamically merge two CSV files using Dataweave in Mule
I get CSV files of different length from different sources. The columns within the CSV are different with the only exception is each CSV file will always have an Id column which can be used to tie the records within different CSV files. At a time, two such CSV files needs to be processed. The process is to take the Id column from the first file and match the rows within the second CSV file and create a third file which contains contents from the first and second file. The id column can be repeated in the first file. Eg is given below. please note that the first file I might have 18 to 19 combination of different data columns so, I cannot hardcode the transformation within dataweave and there is a chance that a new file will be added every time as well. A dynamic approach is what I wanted to accomplish. So once written, the logic should work even if a new file is added. These files get pretty big as well.

The sample files are given below.

```<code>CSV1.csv
--------
id,col1,col2,col3,col4
1,dat1,data2,data3,data4
2,data5,data6,data6,data6
2,data9,data10,data11,data12
2,data13,data14,data15,data16
3,data17,data18,data19,data20
3,data21,data22,data23,data24

CSV2.csv
--------
id,obectId,resid,remarks
1,obj1,res1,rem1
2,obj2,res2,rem2
3,obj3,res3,rem3

Expected file output -CSV3.csv
---------------------
id,col1,col2,col3,col4,objectid,resid,remarks
1,dat1,data2,data3,data4,obj1,res1,rem1
2,data5,data6,data6,data6,obj2,res2,rem2
2,data9,data10,data11,data12,obj2,res2,rem2
2,data13,data14,data15,data16,obj2,res2,rem2
3,data17,data18,data19,data20,obj3,res3,rem3
3,data21,data22,data23,data24,obj3,res3,rem3

</code>```

I was thinking to use pluck to get the column values for the first file. I idea was to get the columns in the transformation without hardcoding it. But I am getting some errors. After this I have the task of searching for the id and getting the value from the second file

```<code>{(
   using(keys = payload pluck $$)
   (
     payload map
     ( (value, index) ->
       {
         (keys[index]) : value

       }
     )
   )
 )}

</code>```

I am getting the following error when using pluck

```<code>Type mismatch for 'pluck' operator
     found :array, :function

    required :object, :function
</code>```

I am thinking of using groupBy on id on the second file to facilitate better searching. But need suggestions on how to append the contents in one transformation to form the 3rd file.

答:
Since you want to combine both CSVs without renaming the column names, you can try something like below

```<code>var file2Grouped=file2 groupBy ((item) -> item.id)
---
file1 map ((item) -> item ++ ((file2Grouped[item.id])[0] default {}) - 'id')
</code>```

output

```<code>id,col1,col2,col3,col4,obectId,resid,remarks
1,dat1,data2,data3,data4,obj1,res1,rem1
2,data5,data6,data6,data6,obj2,res2,rem2
2,data9,data10,data11,data12,obj2,res2,rem2
2,data13,data14,data15,data16,obj2,res2,rem2
3,data17,data18,data19,data20,obj3,res3,rem3
3,data21,data22,data23,data24,obj3,res3,rem3

</code>```

Body:
I get CSV files of different length from different sources. The columns within the CSV are different with the only exception is each CSV file will always have an Id column which can be used to tie the records within different CSV files. At a time, two such CSV files needs to be processed. The process is to take the Id column from the first file and match the rows within the second CSV file and create a third file which contains contents from the first and second file. The id column can be repeated in the first file. Eg is given below. please note that the first file I might have 18 to 19 combination of different data columns so, I cannot hardcode the transformation within dataweave and there is a chance that a new file will be added every time as well. A dynamic approach is what I wanted to accomplish. So once written, the logic should work even if a new file is added. These files get pretty big as well.

The sample files are given below.

CSV1.csv
--------
id,col1,col2,col3,col4
1,dat1,data2,data3,data4
2,data5,data6,data6,data6
2,data9,data10,data11,data12
2,data13,data14,data15,data16
3,data17,data18,data19,data20
3,data21,data22,data23,data24

CSV2.csv
--------
id,obectId,resid,remarks
1,obj1,res1,rem1
2,obj2,res2,rem2
3,obj3,res3,rem3

Expected file output -CSV3.csv
---------------------
id,col1,col2,col3,col4,objectid,resid,remarks
1,dat1,data2,data3,data4,obj1,res1,rem1
2,data5,data6,data6,data6,obj2,res2,rem2
2,data9,data10,data11,data12,obj2,res2,rem2
2,data13,data14,data15,data16,obj2,res2,rem2
3,data17,data18,data19,data20,obj3,res3,rem3
3,data21,data22,data23,data24,obj3,res3,rem3

I was thinking to use pluck to get the column values for the first file. I idea was to get the columns in the transformation without hardcoding it. But I am getting some errors. After this I have the task of searching for the id and getting the value from the second file

{(
   using(keys = payload pluck $$)
   (
     payload map
     ( (value, index) ->
       {
         (keys[index]) : value

       }
     )
   )
 )}

I am getting the following error when using pluck

Type mismatch for 'pluck' operator
     found :array, :function

    required :object, :function

I am thinking of using groupBy on id on the second file to facilitate better searching. But need suggestions on how to append the contents in one transformation to form the 3rd file.

Body:
Since you want to combine both CSVs without renaming the column names, you can try something like below

var file2Grouped=file2 groupBy ((item) -> item.id)
---
file1 map ((item) -> item ++ ((file2Grouped[item.id])[0] default {}) - 'id')

output

id,col1,col2,col3,col4,obectId,resid,remarks
1,dat1,data2,data3,data4,obj1,res1,rem1
2,data5,data6,data6,data6,obj2,res2,rem2
2,data9,data10,data11,data12,obj2,res2,rem2
2,data13,data14,data15,data16,obj2,res2,rem2
3,data17,data18,data19,data20,obj3,res3,rem3
3,data21,data22,data23,data24,obj3,res3,rem3


问:
How to get the specific word fron str.contains
I have a pandas data frame with ID and text string.
I am trying categorize the record with str.contains
I need the word from the text string the str.contains code has identified in different columns.I am using python 3 and pandas
My df is as follows:</p>

```<code>ID  Text
1   The cricket world cup 2019 has begun
2   I am eagrly waiting for the cricket worldcup 2019
3   I will try to watch all the mathes my favourite teams playing in the cricketworldcup 2019
4   I love cricket to watch and badminton to play

searchfor = ['cricket','world cup','2019']
 df['text'].str.contains('|'.join(searchfor))

ID  Text                                    phrase1 phrase2    phrase3
1   The cricket world cup 2019 has begun    cricket  world cup 2019
2   I am eagrly waiting for the
cricket worldcup 2019                           cricket world cup   2019
3   I will try to watch all the mathes my
favourite teams playing in the
cricketworldcup 2019                           cricket  world cup   2019
4   I love cricket to watch and badminton
to play                                        cricket
</code>```

答:
You can use np.where:

```<code>import numpy as np
search_for = ['cricket', 'world cup', '2019']

for word in search_for:
    df[word] = np.where(df.text.str.contains(word), word, np.nan)

df

     text                                               cricket    world cup    2019
1   The cricket world cup 2019 has begun                cricket    world cup    2019
2   I am eagrly waiting for the cricket worldcup 2019   cricket     nan         2019
3   I will try to watch all the mathes my favourit...   cricket     nan         2019
4   I love cricket to watch and badminton to play       cricket     nan         nan
</code>```

Syntax of np.where: np.where(condition[, x, y]). If the condition is True, it returns x otherwise y

Body:
I have a pandas data frame with ID and text string.
I am trying categorize the record with str.contains
I need the word from the text string the str.contains code has identified in different columns.I am using python 3 and pandas
My df is as follows:

ID  Text
1   The cricket world cup 2019 has begun
2   I am eagrly waiting for the cricket worldcup 2019
3   I will try to watch all the mathes my favourite teams playing in the cricketworldcup 2019
4   I love cricket to watch and badminton to play

searchfor = ['cricket','world cup','2019']
 df['text'].str.contains('|'.join(searchfor))

ID  Text                                    phrase1 phrase2    phrase3
1   The cricket world cup 2019 has begun    cricket  world cup 2019
2   I am eagrly waiting for the
cricket worldcup 2019                           cricket world cup   2019
3   I will try to watch all the mathes my
favourite teams playing in the
cricketworldcup 2019                           cricket  world cup   2019
4   I love cricket to watch and badminton
to play                                        cricket

Body:
You can use np.where:

import numpy as np
search_for = ['cricket', 'world cup', '2019']

for word in search_for:
    df[word] = np.where(df.text.str.contains(word), word, np.nan)

df

     text                                               cricket    world cup    2019
1   The cricket world cup 2019 has begun                cricket    world cup    2019
2   I am eagrly waiting for the cricket worldcup 2019   cricket     nan         2019
3   I will try to watch all the mathes my favourit...   cricket     nan         2019
4   I love cricket to watch and badminton to play       cricket     nan         nan

Syntax of np.where: np.where(condition[, x, y]). If the condition is True, it returns x otherwise y


问:
What is the error in this programme of finding the number of times we get consecutive equal values
```<code>def get_count(num_list):
    count=0
    for i in num_list:
        if (i==num_list[i+1]):
            count=count+1
        else:
            pass
    return count

list=[1,1,5,100,-20,-20,6,0,0]
getCount=get_count(list)
print(getCount)

Traceback (most recent call last):
  File "C:/Users/SHIVAM TYAGI/PycharmProjects/infiTQ/Day3Excercise17.py", line 12, in <module>
    getCount=get_count(list)
  File "C:/Users/SHIVAM TYAGI/PycharmProjects/infiTQ/Day3Excercise17.py", line 5, in get_count
    if (i==num_list[i+1]):
IndexError: list index out of range
</code>```

答:
In your code, you are iterating over the elements of num_list, and trying to compare it with an element of num_list the index of which does not exist. Hence the error.

You need to iterate over the indices, till last but one element.

```<code>def get_count(num_list):
    count=0
    for i in range(len(num_list)-1):  # Looping from index 0 to length-1
        if (num_list[i]==num_list[i+1]):
            count=count+1
    return count

list=[1,1,5,100,-20,-20,6,0,0]
getCount=get_count(list)
print(getCount)
</code>```

Body:
In your code, you are iterating over the elements of num_list, and trying to compare it with an element of num_list the index of which does not exist. Hence the error.

You need to iterate over the indices, till last but one element.

def get_count(num_list):
    count=0
    for i in range(len(num_list)-1):  # Looping from index 0 to length-1
        if (num_list[i]==num_list[i+1]):
            count=count+1
    return count

list=[1,1,5,100,-20,-20,6,0,0]
getCount=get_count(list)
print(getCount)


问:
cout does not name a type despite wrapped functions and namespace std
I am getting the error 'cout does not name a type' (line 36 ie main function) along with a couple of other errors in main().

All code is wrapped well within the functions and I have used

using namespace std;
```

<p>but I am still getting this error along with other ~identifier~ was not declared in this scope errors in the main function. </p>

<p>Code:</p>

<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include<cmath>

using namespace std;

double discriminant (double a, double b, double c){
    return (pow(b,2) - (4 * a * c));
}

double* compute_roots(double a, double b, double c){
    double* x;
    double x1,x2;
    double d = discriminant(a,b,c);
    if (d>0){
        cout<<"Two real roots"<<endl;
    }
    else if (d=0){
        cout<<"One unique solution"<<endl;
    }
    else
        {
        cout<<"Does not support complex roots";
        //throw "Negative roots!";
        return x;
    }
    x1 = (-b + sqrt(d))/(2*a);
    x2 = (-b - sqrt(d))/(2*a);
    x[0] = x1;
    x[1] = x2;
    return x;
}

int main{
    double a=2.0,b=5,c=3.1;
    double* res=compute_roots(a,b,c);
    cout<<res[0];
    cout<<res[1];
    return 0;
}
</code>```

答:
```<code>int main{
</code>```

That should be

```<code>int main() {
</code>```

Otherwise the compiler thinks you're trying to define an integer variable called main, not a function, and will get very confused by the code that follows.

Also, compute_roots never initializes its local variable x before using its value, so that can't work:

```<code>double* x;
// ...
return x;
</code>```

Another problem:

```<code>else if (d=0){
</code>```

should probably be d == 0 (= is for assignment, not comparison).

Body:
I am getting the error 'cout does not name a type' (line 36 ie main function) along with a couple of other errors in main().

All code is wrapped well within the functions and I have used

using namespace std;

but I am still getting this error along with other ~identifier~ was not declared in this scope errors in the main function.

Code:

#include<iostream>
#include<cmath>

using namespace std;

double discriminant (double a, double b, double c){
    return (pow(b,2) - (4 * a * c));
}

double* compute_roots(double a, double b, double c){
    double* x;
    double x1,x2;
    double d = discriminant(a,b,c);
    if (d>0){
        cout<<"Two real roots"<<endl;
    }
    else if (d=0){
        cout<<"One unique solution"<<endl;
    }
    else
        {
        cout<<"Does not support complex roots";
        //throw "Negative roots!";
        return x;
    }
    x1 = (-b + sqrt(d))/(2*a);
    x2 = (-b - sqrt(d))/(2*a);
    x[0] = x1;
    x[1] = x2;
    return x;
}

int main{
    double a=2.0,b=5,c=3.1;
    double* res=compute_roots(a,b,c);
    cout<<res[0];
    cout<<res[1];
    return 0;
}

Body:
int main{

That should be

int main() {

Otherwise the compiler thinks you're trying to define an integer variable called main, not a function, and will get very confused by the code that follows.

Also, compute_roots never initializes its local variable x before using its value, so that can't work:

double* x;
// ...
return x;

Another problem:

else if (d=0){

should probably be d == 0 (= is for assignment, not comparison).


问:
My PHP function works perfectly when browse manually but not working properly from cron
I'm developing a web based program and i have several cron jobs for this on my cPanel. Every one of them works perfectly from cron and manually except one. I'm using Codeigniter. The PHP function works perfectly when i run it manually via browser. But when it runs from cron not all the parts of the function works.

I read almost every article about this problem but i still have it.

My cron command is like

59 23 * * * curl --silent http://www.domainname.com/some_controller/some_function

答: I solved the problem. The problem is not the cron job but the code. When the function runs it logs the progress with the user who execute it. Thats why it runs perfectly manually. When cron do this there is no user so the code fails.</p>


问:
How to save a modified array to a file
So I created an array which is saved in a file. I have the number 4 printed out 100 times in the file. Now everytime the an element in the array is accessed it the value will decrease by 1. So if A[1] = 4 is accessed then it will become A[1] = 3 and be saved on the file. The thing is I can't save the modified array to the file.

I already tried moving the placement of FILE pointer.

```<code>void buildingB4()
{
    system("CLS");
    FILE *input, *output;
    int i, B4[100], room;

    input = fopen("B4.txt", "r");
    if (input == NULL)
    {
        output = fopen("B4.txt", "w");
        for (i = 1; i <= 100; i++)
        {
            B4[i] = 4;
            fprintf(output, "%d\n", B4[i]);
        }
        fclose(output);
        for (i = 1; i <= 100; i++)
        {
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
    }
    else
    {

        for (i = 1; i <= 100; i++)
        {
            fscanf(input, "%d\n", &B4[i]);
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
        fclose(input);
        printf("\nPlease choose a room:B-4-");
        scanf("%d", &room);
        B4[room] = B4[room] - 1;
        output = fopen("B4.txt", "a");
        fprintf(output, "%d\n", B4[i]);
        studentDetails();
    }
}
</code>```

say if A[1] = 4
and when user input is 1, 1 is saved in a variable called room.
so A[room] = A[room] -1
so the result would be A[1] = 3 and it modify the A[1] saved in the file.

答:
Use fclose after the line
 fprintf(output, "%d\n", B4[i]);</p>

Title: How to save a modified array to a file

Body:
So I created an array which is saved in a file. I have the number 4 printed out 100 times in the file. Now everytime the an element in the array is accessed it the value will decrease by 1. So if A[1] = 4 is accessed then it will become A[1] = 3 and be saved on the file. The thing is I can't save the modified array to the file.

I already tried moving the placement of FILE pointer.

void buildingB4()
{
    system("CLS");
    FILE *input, *output;
    int i, B4[100], room;

    input = fopen("B4.txt", "r");
    if (input == NULL)
    {
        output = fopen("B4.txt", "w");
        for (i = 1; i <= 100; i++)
        {
            B4[i] = 4;
            fprintf(output, "%d\n", B4[i]);
        }
        fclose(output);
        for (i = 1; i <= 100; i++)
        {
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
    }
    else
    {

        for (i = 1; i <= 100; i++)
        {
            fscanf(input, "%d\n", &B4[i]);
            if (i % 10 == 0)
            {
                printf("\n\n");
            }
            printf("B-4-%d(%d)\t", i, B4[i]);
        }
        fclose(input);
        printf("\nPlease choose a room:B-4-");
        scanf("%d", &room);
        B4[room] = B4[room] - 1;
        output = fopen("B4.txt", "a");
        fprintf(output, "%d\n", B4[i]);
        studentDetails();
    }
}

say if A[1] = 4
and when user input is 1, 1 is saved in a variable called room.
so A[room] = A[room] -1
so the result would be A[1] = 3 and it modify the A[1] saved in the file.


问:
Replacing strings in stream, using Swizzle Stream
I've tried the Swizzle Stream library to replace tokens in an input stream.

```<code>  String RESOURCE_PATH = "FakePom.xml";
  InputStream pomIS = JarFinderServlet.class.getClassLoader().getResourceAsStream( RESOURCE_PATH );

  if( null == pomIS )
     throw new MavenhoeException("Can't read fake pom template - getResourceAsStream( RESOURCE_PATH ) == null");

  Map map = ArrayUtils.toMap(  new String[][]{
     {"@GRP@", artifactInfo.getGroup() },
     {"@ART@", artifactInfo.getName() },
     {"@VER@", artifactInfo.getVersion() },
     {"@PACK@", artifactInfo.getPackaging() },
     {"@NAME@", artifactInfo.getFileName() },
     {"@DESC@", req.getQueryString() },
  } );

  //  This does not replace anything, no idea why. //
  ReplaceStringsInputStream replacingIS = new ReplaceStringsInputStream(pomIS, map);
  ReplaceStringInputStream replacingIS2 = new ReplaceStringInputStream(pomIS, "@VER@", "0.0-AAAAA");
  ReplaceStringInputStream replacingIS3 = new ReplaceStringInputStream(pomIS, "@", "#");

  ServletOutputStream os = resp.getOutputStream();
  IOUtils.copy( replacingIS, os );
  replacingIS.close();
</code>```

This did not work. It just does not replace. So I resorted to the "PHP way"...

```<code>  String pomTemplate = IOUtils.toString(pomIS)
  .replace("@GRP@", artifactInfo.getGroup() )
  .replace("@ART@", artifactInfo.getName() )
  .replace("@VER@", artifactInfo.getVersion() )
  .replace("@PACK@", artifactInfo.getPackaging() )
  .replace("@NAME@", artifactInfo.getFileName() )
  .replace("@DESC@", req.getQueryString() );

  ServletOutputStream os = resp.getOutputStream();
  IOUtils.copy( new StringInputStream(pomTemplate), os );
  os.close();
</code>```

Works.

What's wrong?

答:
IOUtils.copy calls read(byte[]) method instead of read(), which is overridden by FixedTokenReplacementInputStream, a superclass of ReplaceStringInputStream.
You should implement copying on your own, for example, as follows:</p>

```<code>try {
int b;
while ((b = pomIS.read()) != -1) {
    os.write(b);
}} finally { os.flush();os.close(); }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've tried the Swizzle Stream library to replace tokens in an input stream.

  String RESOURCE_PATH = "FakePom.xml";
  InputStream pomIS = JarFinderServlet.class.getClassLoader().getResourceAsStream( RESOURCE_PATH );

  if( null == pomIS )
     throw new MavenhoeException("Can't read fake pom template - getResourceAsStream( RESOURCE_PATH ) == null");

  Map map = ArrayUtils.toMap(  new String[][]{
     {"@GRP@", artifactInfo.getGroup() },
     {"@ART@", artifactInfo.getName() },
     {"@VER@", artifactInfo.getVersion() },
     {"@PACK@", artifactInfo.getPackaging() },
     {"@NAME@", artifactInfo.getFileName() },
     {"@DESC@", req.getQueryString() },
  } );

  //  This does not replace anything, no idea why. //
  ReplaceStringsInputStream replacingIS = new ReplaceStringsInputStream(pomIS, map);
  ReplaceStringInputStream replacingIS2 = new ReplaceStringInputStream(pomIS, "@VER@", "0.0-AAAAA");
  ReplaceStringInputStream replacingIS3 = new ReplaceStringInputStream(pomIS, "@", "#");

  ServletOutputStream os = resp.getOutputStream();
  IOUtils.copy( replacingIS, os );
  replacingIS.close();

This did not work. It just does not replace. So I resorted to the "PHP way"...

  String pomTemplate = IOUtils.toString(pomIS)
  .replace("@GRP@", artifactInfo.getGroup() )
  .replace("@ART@", artifactInfo.getName() )
  .replace("@VER@", artifactInfo.getVersion() )
  .replace("@PACK@", artifactInfo.getPackaging() )
  .replace("@NAME@", artifactInfo.getFileName() )
  .replace("@DESC@", req.getQueryString() );

  ServletOutputStream os = resp.getOutputStream();
  IOUtils.copy( new StringInputStream(pomTemplate), os );
  os.close();

Works.

What's wrong?

Body:
IOUtils.copy calls read(byte[]) method instead of read(), which is overridden by FixedTokenReplacementInputStream, a superclass of ReplaceStringInputStream.
You should implement copying on your own, for example, as follows:

try {
int b;
while ((b = pomIS.read()) != -1) {
    os.write(b);
}} finally { os.flush();os.close(); }


问:
Event inside click function firing outside click
I'm using the hash to detect the current slide in a slideshow but I'd like to only do so when the slideshow is advanced using the previous or next buttons. But the event "cycle-after" which detects a transition in the slideshow, is firing even when the previous or next buttons are not clicked.

How do I make that event only run during the click function?

JSFiddle here: https://jsfiddle.net/yd8L3enj/4/

$(document).ready(function() {
  var clicked = false;

  $('.controls').on('click', function() {
    $('.cycle-slideshow').on('cycle-after', function(event, optionHash) {
      var hash = window.location.hash;
      $('.clicked').removeClass('clicked')
      if (window.location.hash === hash) {
        $(hash).addClass('clicked')
      } else {
        $(hash).removeClass('clicked')
      }
    });
  });

  $('nav a').on('click', function() {
    clicked = !clicked;
    $('.clicked').removeClass('clicked');
    $(this).addClass('clicked');
    $('.content').addClass('visible');
  });

  $("nav a").mouseenter(function() {
    var href = $(this).attr('href');
    window.location.hash = href
    $('.content').addClass('visible');
  }).mouseleave(function() {
    var current = $('.clicked').attr('href');
    window.location.hash = current
    if ($(".clicked")[0]) {
      // Do something if class exists
    } else {
      $('.content').removeClass('visible');
    }
  });

  $('.close').on('click', function() {
    $('.content').removeClass('visible');
    window.location.hash = ""
    clicked = !clicked;
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-size: 150%;
}

img {
  width: 50vw;
  height: auto;
}

.clicked {
  color: green;
}

.content {
  display: none;
}

.visible {
  display: block;
}</code>```

  1
  2
  3

 div" data-cycle-timeout="0" data-cycle-prev=".prev" data-cycle-next=".next" data-cycle-speed="1" data-cycle-fx="fadeOut">

Prev

Next

Close

```

答:
the $(selector).on(... syntax binds an event listener.  Your code is adding an event listener to the 'cycle-after' event every time the click listener is executed.  That means, as soon it was clicked once, all cycle-after events from then on will have that code executed.  If you clicked multiple times, you will have bound multiple listeners, and even more of them will be running on every cycle-after event.

What you probably want to do is, for a click, only perform the code after the first next cycle-after event.  To achieve this you could bind the listener, and at the end of the callback, unbind it again.  Something like this:

```<code>  $('.controls').on('click', function() {
    $('.cycle-slideshow').on('cycle-after', afterCycle);

    function afterCycle(){
      ... your logic here ...
      $('.cycle-slideshow').off('cycle-after', afterCycle);
    }
  });
</code>```

Keep in mind that this is still pretty fragile.  If you click twice before the first cycle-after happens, the library might only fire cycle-after once and you will still have an unwanted listener bound.  If this slide-library supports it, it would be best to simply bind once on 'cycle-after', and then add a check that only continues if the cycle was caused by a click.

Body:
I'm using the hash to detect the current slide in a slideshow but I'd like to only do so when the slideshow is advanced using the previous or next buttons. But the event "cycle-after" which detects a transition in the slideshow, is firing even when the previous or next buttons are not clicked.

How do I make that event only run during the click function?

JSFiddle here: https://jsfiddle.net/yd8L3enj/4/

$(document).ready(function() {
  var clicked = false;

  $('.controls').on('click', function() {
    $('.cycle-slideshow').on('cycle-after', function(event, optionHash) {
      var hash = window.location.hash;
      $('.clicked').removeClass('clicked')
      if (window.location.hash === hash) {
        $(hash).addClass('clicked')
      } else {
        $(hash).removeClass('clicked')
      }
    });
  });

  $('nav a').on('click', function() {
    clicked = !clicked;
    $('.clicked').removeClass('clicked');
    $(this).addClass('clicked');
    $('.content').addClass('visible');
  });

  $("nav a").mouseenter(function() {
    var href = $(this).attr('href');
    window.location.hash = href
    $('.content').addClass('visible');
  }).mouseleave(function() {
    var current = $('.clicked').attr('href');
    window.location.hash = current
    if ($(".clicked")[0]) {
      // Do something if class exists
    } else {
      $('.content').removeClass('visible');
    }
  });

  $('.close').on('click', function() {
    $('.content').removeClass('visible');
    window.location.hash = ""
    clicked = !clicked;
  });

});

body {
  font-size: 150%;
}

img {
  width: 50vw;
  height: auto;
}

.clicked {
  color: green;
}

.content {
  display: none;
}

.visible {
  display: block;
}

  1
  2
  3

 div" data-cycle-timeout="0" data-cycle-prev=".prev" data-cycle-next=".next" data-cycle-speed="1" data-cycle-fx="fadeOut">

Prev

Next

Close

Body:
the $(selector).on(... syntax binds an event listener.  Your code is adding an event listener to the 'cycle-after' event every time the click listener is executed.  That means, as soon it was clicked once, all cycle-after events from then on will have that code executed.  If you clicked multiple times, you will have bound multiple listeners, and even more of them will be running on every cycle-after event.

What you probably want to do is, for a click, only perform the code after the first next cycle-after event.  To achieve this you could bind the listener, and at the end of the callback, unbind it again.  Something like this:

  $('.controls').on('click', function() {
    $('.cycle-slideshow').on('cycle-after', afterCycle);

    function afterCycle(){
      ... your logic here ...
      $('.cycle-slideshow').off('cycle-after', afterCycle);
    }
  });

Keep in mind that this is still pretty fragile.  If you click twice before the first cycle-after happens, the library might only fire cycle-after once and you will still have an unwanted listener bound.  If this slide-library supports it, it would be best to simply bind once on 'cycle-after', and then add a check that only continues if the cycle was caused by a click.


问:
React, using emojis in a drop down
I've been working on a little game in react and part of the game allows for the player to set some settings before starting.  It's a turn-based tag game, four players chase different tokens around the map, while avoiding the one player labeled "it".

I have the following render method for a select option:

render() {
    return (

            <form onSubmit={this.createPlayers} ref="form">
                Choose a Goody!
                <select name="goodies" id="goodies">
                    <option value="donut"></option>
                    <option value="cookie"></option>
                    <option value="hotdog"></option>
                    <option value="bacon"></option>
                    <option value="hamburger"></option>
                    <option value="brocolli"></option>
                </select>
                <button type="submit">Play!</button>
            </form>

    );
}
```

And I get a large warning saying I need to wrap them in span elements, add some aria labels and give them a role of error.

Line 18:  Emojis should be wrapped in , have role="img", and have an accessible description with aria-label or aria-labelledby  jsx-a11y/accessible-emoji

I do that, and then the JSX refuses to compile because it's expect a string for each option.  It won't let me put a span between the option tags.

I'd really like to get this warning to go away, but when I try to do what it asks, the JSX won't compile.  Is there something I have to do to make this work without the warning?

Thing is, I used emojis elsewhere and I got no warnings or any problems whatsoever.

答:
Add in select  like this

```<code> <select name="goodies" id="goodies">
    <option value="donut">
       <span role="img" aria-label="donut"></span>
   </option>
   ....
  </select>
</code>```

Title: React, using emojis in a drop down

Body:
I've been working on a little game in react and part of the game allows for the player to set some settings before starting.  It's a turn-based tag game, four players chase different tokens around the map, while avoiding the one player labeled "it".

I have the following render method for a select option:

render() {
    return (

            <form onSubmit={this.createPlayers} ref="form">
                Choose a Goody!
                <select name="goodies" id="goodies">
                    <option value="donut"></option>
                    <option value="cookie"></option>
                    <option value="hotdog"></option>
                    <option value="bacon"></option>
                    <option value="hamburger"></option>
                    <option value="brocolli"></option>
                </select>
                <button type="submit">Play!</button>
            </form>

    );
}

And I get a large warning saying I need to wrap them in span elements, add some aria labels and give them a role of error.

Line 18:  Emojis should be wrapped in , have role="img", and have an accessible description with aria-label or aria-labelledby  jsx-a11y/accessible-emoji

I do that, and then the JSX refuses to compile because it's expect a string for each option.  It won't let me put a span between the option tags.

I'd really like to get this warning to go away, but when I try to do what it asks, the JSX won't compile.  Is there something I have to do to make this work without the warning?

Thing is, I used emojis elsewhere and I got no warnings or any problems whatsoever.

Body:
Add in select <span role="img" aria-label="xxxxx"> like this

 <select name="goodies" id="goodies">
    <option value="donut">
       <span role="img" aria-label="donut"></span>
   </option>
   ....
  </select>


问:
Async functions are unexpectedly blocking each other
I'm attempting to run two functions in separate threads that do not block each other. Each thread contains a loop.

Output of below code :

```<code>%reset -f

import asyncio
import time

async def run1():

    for i in range(0 , 3) :
        print('run1')
        time.sleep(1)

async def run2():

    for i in range(0 , 3) :
        print('run2')
        time.sleep(2)

async def main():
    results = await asyncio.gather(
        run1() , run2())

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())
</code>```

is :

```<code>run2
run2
run2
run1
run1
run1
</code>```

But it can also be

```<code>run1
run1
run1
run2
run2
run2
</code>```

So it seems that once either of thread run1 or run2 the thread blocks the other thread of starting until the current run completes.

I'm expecting output similar to :

```<code>run1
run1
run2
run2
run1
run2
</code>```

How to allow threads run1 and run2 to not block each other ?

I'm using Python3.

答:
change time.sleep to corresponding asyncio version:

```<code>await asyncio.sleep(1)
</code>```

and the correct result of your code is:

```<code>run1
run2
run1
run2
run1
run2
</code>```

because print happens before sleep.

Body:
I'm attempting to run two functions in separate threads that do not block each other. Each thread contains a loop.

Output of below code :

%reset -f

import asyncio
import time

async def run1():

    for i in range(0 , 3) :
        print('run1')
        time.sleep(1)

async def run2():

    for i in range(0 , 3) :
        print('run2')
        time.sleep(2)

async def main():
    results = await asyncio.gather(
        run1() , run2())

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())

is :

run2
run2
run2
run1
run1
run1

But it can also be

run1
run1
run1
run2
run2
run2

So it seems that once either of thread run1 or run2 the thread blocks the other thread of starting until the current run completes.

I'm expecting output similar to :

run1
run1
run2
run2
run1
run2

How to allow threads run1 and run2 to not block each other ?

I'm using Python3.

Body:
change time.sleep to corresponding asyncio version:

await asyncio.sleep(1)

and the correct result of your code is:

run1
run2
run1
run2
run1
run2

because print happens before sleep.


问:
how to access specific data in json in javascript
I'm trying to access specific data from json array. and i'm using dynamic dropdown.

So in my case i want get all names from the json and plot it on option.

here is the Json we're accessing..

```<code>[
 {
    "id": 1,
    "name": "john"
    "age": 23,
    "city": "New York"
 },
 {
    "id": 2,
    "name": "Donald"
    "age": 34,
    "city": "London"
 },
 {
    "id": 3,
    "name": "k'nan"
    "age": 27,
    "city": "Paris"
 },
 {
    "id": 1,
    "name": "jose"
    "age": 29,
    "city": "lesbon"
 },
]
</code>```

script

```<code>$.each(data, function(key,vlaue ){
          $('select[name="bus_number"]').append('<option value="'+ key +'">'+ value +'</option>');
 });
</code>```

and again i want to access only all names and plot it on options.
i did this and it's not working and may be you guys will tell me a better way.

答:
Brb to explain soon.

Jquery:

```<code>var data = [
 {
    "id": 1,
    "name": "john",
    "age": 23,
    "city": "New York"
 },
 {
    "id": 2,
    "name": "Donald",
    "age": 34,
    "city": "London"
 },
 {
    "id": 3,
    "name": "k'nan",
    "age": 27,
    "city": "Paris"
 },
 {
    "id": 1,
    "name": "jose",
    "age": 29,
    "city": "lesbon"
 },
];

$.each( data, function( index, object ) {
  $('select[name="bus_number"]').append('<option value="'+ object['id'] +'">'+ object['name'] +'</option>');
});
</code>```

Body:
I'm trying to access specific data from json array. and i'm using dynamic dropdown.

So in my case i want get all names from the json and plot it on option.

here is the Json we're accessing..

[
 {
    "id": 1,
    "name": "john"
    "age": 23,
    "city": "New York"
 },
 {
    "id": 2,
    "name": "Donald"
    "age": 34,
    "city": "London"
 },
 {
    "id": 3,
    "name": "k'nan"
    "age": 27,
    "city": "Paris"
 },
 {
    "id": 1,
    "name": "jose"
    "age": 29,
    "city": "lesbon"
 },
]

script

$.each(data, function(key,vlaue ){
          $('select[name="bus_number"]').append('<option value="'+ key +'">'+ value +'</option>');
 });

and again i want to access only all names and plot it on options.
i did this and it's not working and may be you guys will tell me a better way.

Body:
Brb to explain soon.

Jquery:

var data = [
 {
    "id": 1,
    "name": "john",
    "age": 23,
    "city": "New York"
 },
 {
    "id": 2,
    "name": "Donald",
    "age": 34,
    "city": "London"
 },
 {
    "id": 3,
    "name": "k'nan",
    "age": 27,
    "city": "Paris"
 },
 {
    "id": 1,
    "name": "jose",
    "age": 29,
    "city": "lesbon"
 },
];

$.each( data, function( index, object ) {
  $('select[name="bus_number"]').append('<option value="'+ object['id'] +'">'+ object['name'] +'</option>');
});


问:
Build issue with go using SWIG and an external C library
I am trying to create a golang program which will use an external C library.
Before doing complex stuff, I wanted to test the use of SWIG in a small foo example.
I also want to be able to use the "go get" syntax without having to manually run swig. And to take into account that the external C library shall have been built before and can be located anywhere on the machine.

I am using golang 1.12.5 and swig 3.0.12

I have created the following structure:

```<code>.
|-- libfoo
|   |-- foo.c
|   |-- foo.h
|   `-- libfoo.so
`-- src
    |-- example_test.go
    |-- lib.go
    `-- libfoo.swig
</code>```

In the libfoo folder I have a simple shared library. The files contain:
foo.c:

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

int foo(int c){
    return c+1;
};
</code>```

foo.h

```<code>int foo(int c);
</code>```

That I've compiled it with:

```<code>gcc -o ./libfoo.so -fPIC -shared ./foo.c
</code>```

Then the golang files:
libfoo.swig

```<code>%module libfoo

%{
  extern int foo(int a);
%}

extern int foo(int a);
</code>```

lib.go

```<code>package libfoo

/*
#cgo LDFLAGS: -L../libfoo -lfoo
*/

import "C"
</code>```

And finally example_test.go

```<code>package libfoo

import (
    "testing"
    "fmt"
)

func TestFoo(*testing.T) {
    i := Foo(1)
    fmt.Printf("%v\n",i)
}
</code>```

When I try to build with "go build -x" It seems that the cgo directives located in the "lib.go" file are not taken into account as I do not see the flag appears in the output. Here is the output

```<code>06aa7e308d6:/mnt/data/src# go build -x
WORK=/tmp/go-build551116655
mkdir -p $WORK/b001/
swig -version
cd $WORK
/opt/go/pkg/tool/linux_amd64/compile -o ./b001/_go_.o -trimpath ./b001 -p main -complete -goversion go1.12.5 -D _$WORK -c=4 ./swig_intsize.go
cd /mnt/data/src
swig -go -cgo -intgosize 64 -module libfoo -o $WORK/b001/libfoo_wrap.c -outdir $WORK/b001/ libfoo.swig
CGO_LDFLAGS='"-g" "-O2"' /opt/go/pkg/tool/linux_amd64/cgo -objdir $WORK/b001/ -importpath _/mnt/data/src -- -I $WORK/b001/ -g -O2 ./lib.go $WORK/b001/_libfoo_swig.go
cd $WORK
gcc -fno-caret-diagnostics -c -x c - || true
gcc -Qunused-arguments -c -x c - || true
gcc -fdebug-prefix-map=a=b -c -x c - || true
gcc -gno-record-gcc-switches -c -x c - || true
cd $WORK/b001
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_x001.o -c _cgo_export.c
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_x002.o -c lib.cgo2.c
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_x003.o -c _libfoo_swig.cgo2.c
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_x004.o -c libfoo_wrap.c
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_cgo_main.o -c _cgo_main.c
cd /mnt/data/src
TERM='dumb' gcc -I . -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -o $WORK/b001/_cgo_.o $WORK/b001/_cgo_main.o $WORK/b001/_x001.o $WORK/b001/_x002.o $WORK/b001/_x003.o $WORK/b001/_x004.o -g -O2
# _/mnt/data/src
/tmp/go-build551116655/b001/_x004.o: In function `_wrap_foo_libfoo_0f106433f15c8754':
/tmp/go-build/libfoo_wrap.c:255: undefined reference to `foo'
collect2: error: ld returned 1 exit status
</code>```

If I set the CGO_LDFLAGS using an environment variable, it works. However I want to be able to just use "go get" without having those variables before.

I don't understand why go does not take my #cgo directive into account.
Did I miss something ?

答:
Someone on the golang github repository has solved my issue.

The solution was to remove the newline between the import "C" directive and the comments containing the #cgo directives.

Body:
I am trying to create a golang program which will use an external C library.
Before doing complex stuff, I wanted to test the use of SWIG in a small foo example.
I also want to be able to use the "go get" syntax without having to manually run swig. And to take into account that the external C library shall have been built before and can be located anywhere on the machine.

I am using golang 1.12.5 and swig 3.0.12

I have created the following structure:

.
|-- libfoo
|   |-- foo.c
|   |-- foo.h
|   `-- libfoo.so
`-- src
    |-- example_test.go
    |-- lib.go
    `-- libfoo.swig

In the libfoo folder I have a simple shared library. The files contain:
foo.c:

#include "foo.h"

int foo(int c){
    return c+1;
};

foo.h

int foo(int c);

That I've compiled it with:

gcc -o ./libfoo.so -fPIC -shared ./foo.c

Then the golang files:
libfoo.swig

%module libfoo

%{
  extern int foo(int a);
%}

extern int foo(int a);

lib.go

package libfoo

/*
#cgo LDFLAGS: -L../libfoo -lfoo
*/

import "C"

And finally example_test.go

package libfoo

import (
    "testing"
    "fmt"
)

func TestFoo(*testing.T) {
    i := Foo(1)
    fmt.Printf("%v\n",i)
}

When I try to build with "go build -x" It seems that the cgo directives located in the "lib.go" file are not taken into account as I do not see the flag appears in the output. Here is the output

06aa7e308d6:/mnt/data/src# go build -x
WORK=/tmp/go-build551116655
mkdir -p $WORK/b001/
swig -version
cd $WORK
/opt/go/pkg/tool/linux_amd64/compile -o ./b001/_go_.o -trimpath ./b001 -p main -complete -goversion go1.12.5 -D _$WORK -c=4 ./swig_intsize.go
cd /mnt/data/src
swig -go -cgo -intgosize 64 -module libfoo -o $WORK/b001/libfoo_wrap.c -outdir $WORK/b001/ libfoo.swig
CGO_LDFLAGS='"-g" "-O2"' /opt/go/pkg/tool/linux_amd64/cgo -objdir $WORK/b001/ -importpath _/mnt/data/src -- -I $WORK/b001/ -g -O2 ./lib.go $WORK/b001/_libfoo_swig.go
cd $WORK
gcc -fno-caret-diagnostics -c -x c - || true
gcc -Qunused-arguments -c -x c - || true
gcc -fdebug-prefix-map=a=b -c -x c - || true
gcc -gno-record-gcc-switches -c -x c - || true
cd $WORK/b001
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_x001.o -c _cgo_export.c
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_x002.o -c lib.cgo2.c
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_x003.o -c _libfoo_swig.cgo2.c
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_x004.o -c libfoo_wrap.c
TERM='dumb' gcc -I /mnt/data/src -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -I ./ -g -O2 -o ./_cgo_main.o -c _cgo_main.c
cd /mnt/data/src
TERM='dumb' gcc -I . -fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=$WORK/b001=/tmp/go-build -gno-record-gcc-switches -o $WORK/b001/_cgo_.o $WORK/b001/_cgo_main.o $WORK/b001/_x001.o $WORK/b001/_x002.o $WORK/b001/_x003.o $WORK/b001/_x004.o -g -O2
# _/mnt/data/src
/tmp/go-build551116655/b001/_x004.o: In function `_wrap_foo_libfoo_0f106433f15c8754':
/tmp/go-build/libfoo_wrap.c:255: undefined reference to `foo'
collect2: error: ld returned 1 exit status

If I set the CGO_LDFLAGS using an environment variable, it works. However I want to be able to just use "go get" without having those variables before.

I don't understand why go does not take my #cgo directive into account.
Did I miss something ?


答:
I'm assuming that you are trying to create a dropdown where the options' labels are the names in the data and the options' values are the corresponding ids.

```<code>data.forEach(({id, name}) => {
    $('select[name="bus_number"]').append(`<option value="${id}">${name}</option>`);
});
</code>```

Notice that I use JavaSctipt's native forEach instead of jQuery's (no need for that anymore), and I'm also using Object Desctructuring and String Literals which make your code easier to read.

Here's a fiddle.

Title: how to access specific data in json in javascript

Body:
I'm assuming that you are trying to create a dropdown where the options' labels are the names in the data and the options' values are the corresponding ids.

data.forEach(({id, name}) => {
    $('select[name="bus_number"]').append(`<option value="${id}">${name}</option>`);
});

Notice that I use JavaSctipt's native forEach instead of jQuery's (no need for that anymore), and I'm also using Object Desctructuring and String Literals which make your code easier to read.

Here's a fiddle.


问:
Is there any way to embed power bi reports and dashboards in vb.net or C# desktop application with sql server 2008 database?
I have a vb.net desktop application with sql server 2008 database. I am currently using SSRS for reports but my client wishes to have visual data representation. Therefore I want to use Power BI dashboards. So what are the steps to embed power bi dashboards in vb.net application.</p>

答: Power BI Embedding always uses a web browser and an IFrame.  So you would start by embedding a browser control in your desktop app, then doing normal Power BI Embedding.</p>


问:
How to add a crontab job to crontab using a bash script with date stamp?
here was the original question
How to add a crontab job to crontab using a bash script?

```<code> #!/bin/bash
cronjob="* * * * * /path/to/command"
(crontab -u userhere -l; echo "$cronjob" ) | crontab -u userhere -
</code>```

if I try to use command below bash is importing command and replacing (date +\%H_\%M-\%d.\%m.\%Y at the date and time of the import and I see imported command with fixed date stamp as..../mysql/21_18-27.05.2019_dbbackup.sql.gz

is there a way to keep date imported a formula?

```<code>cronjob="05 21 * * * /usr/bin/mysqldump -u mysqluserhere -pmysqlpassword DBname | gzip > /path/to/mysql/$(date +\%H_\%M-\%d.\%m.\%Y)_dbbackup.sql.gz" (crontab -u userhere -l; echo "$cronjob" ) | crontab -u userhere -
</code>```

Many thanks

答:
Using single quotes instead of double around the string will prevent the shell from interpolating anything.

Minimally, switch to single quotes around the variable assignment:

```<code>cronjob='05 21 * * * /usr/bin/mysqldump -u mysqluserhere -pmysqlpassword DBname | gzip > /path/to/mysql/$(date +\%H_\%M-\%d.\%m.\%Y)_dbbackup.sql.gz'
(crontab -u userhere -l; echo "$cronjob" ) |
crontab -u userhere -
</code>```

though of course, a variable you only use once is rather pointless.

```<code>(crontab -u userhere -l
 echo '05 21 * * * /usr/bin/mysqldump -u mysqluserhere -pmysqlpassword DBname | gzip > /path/to/mysql/$(date +\%H_\%M-\%d.\%m.\%Y)_dbbackup.sql.gz' ) |
crontab -u userhere -
</code>```

You probably don't need the full path to mysqldump either.

Body:
here was the original question
How to add a crontab job to crontab using a bash script?

 #!/bin/bash
cronjob="* * * * * /path/to/command"
(crontab -u userhere -l; echo "$cronjob" ) | crontab -u userhere -

if I try to use command below bash is importing command and replacing (date +\%H_\%M-\%d.\%m.\%Y at the date and time of the import and I see imported command with fixed date stamp as..../mysql/21_18-27.05.2019_dbbackup.sql.gz

is there a way to keep date imported a formula?

cronjob="05 21 * * * /usr/bin/mysqldump -u mysqluserhere -pmysqlpassword DBname | gzip > /path/to/mysql/$(date +\%H_\%M-\%d.\%m.\%Y)_dbbackup.sql.gz" (crontab -u userhere -l; echo "$cronjob" ) | crontab -u userhere -

Many thanks

Body:
Using single quotes instead of double around the string will prevent the shell from interpolating anything.

Minimally, switch to single quotes around the variable assignment:

cronjob='05 21 * * * /usr/bin/mysqldump -u mysqluserhere -pmysqlpassword DBname | gzip > /path/to/mysql/$(date +\%H_\%M-\%d.\%m.\%Y)_dbbackup.sql.gz'
(crontab -u userhere -l; echo "$cronjob" ) |
crontab -u userhere -

though of course, a variable you only use once is rather pointless.

(crontab -u userhere -l
 echo '05 21 * * * /usr/bin/mysqldump -u mysqluserhere -pmysqlpassword DBname | gzip > /path/to/mysql/$(date +\%H_\%M-\%d.\%m.\%Y)_dbbackup.sql.gz' ) |
crontab -u userhere -

You probably don't need the full path to mysqldump either.


问:
How to returns correctly matched array?
I have a function that takes a string of DNA and how to return correctly matched dna array
The code that I have tried:</p>

```<code>function checkDNA(dna) {
   var dnaarr = [];

    for(var i = 0; i < dna.length; i++) {
         var str = [];
str.push(dna[i]); //pushing current str[i]
      if(dna[i].indexOf('') === 0) {
        var a = str.push('sd');
      }
      if(dna[i].indexOf('GGC') === 0) {
        var b = str.push("GC", "GC", "CG");
      }
      if(dna[i].indexOf('gat') === 0) {
        var c = str.push("GC", "AT", "TA");
      }
      if(dna[i].indexOf('PGYYYHVB') === 0) {
        var d = str.push('GC');
      }
dnaarr.push(str); //pushing the array dna to the main array dnaarr
    }

    return dnaarr;
}
</code>```

答:
You could take an object for the nucleobases and take the characters of the string for getting the values for each character.

For unknow characters, a later filtering is applied.

function pair(string) {
    var nucleobases = { G: 'C', C: 'G', T: 'A', A: 'T' };

    return Array
        .from(string.toUpperCase(), s => s in nucleobases && s + nucleobases[s])
        .filter(Boolean);
}

console.log(pair('GTTC'));```

Title: How to returns correctly matched array?

Body:
I have a function that takes a string of DNA and how to return correctly matched dna array
The code that I have tried:

function checkDNA(dna) {
   var dnaarr = [];

    for(var i = 0; i < dna.length; i++) {
         var str = [];
str.push(dna[i]); //pushing current str[i]
      if(dna[i].indexOf('') === 0) {
        var a = str.push('sd');
      }
      if(dna[i].indexOf('GGC') === 0) {
        var b = str.push("GC", "GC", "CG");
      }
      if(dna[i].indexOf('gat') === 0) {
        var c = str.push("GC", "AT", "TA");
      }
      if(dna[i].indexOf('PGYYYHVB') === 0) {
        var d = str.push('GC');
      }
dnaarr.push(str); //pushing the array dna to the main array dnaarr
    }

    return dnaarr;
}


问:
About AnnotationConfigApplicationContext in Spring framework
I have written the following simple stand-alone spring app:

```<code>package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

@Configuration
@ComponentScan(basePackages = { "com.example" })
@PropertySource(ignoreResourceNotFound = true, value = "classpath:/application.props")
public class MainDriver {

@Autowired
private Environment env;
@Autowired
private ApplicationContext ctx;
@Autowired
private ConfigurableEnvironment cenv;

public static void main(String[] args) {

    ApplicationContext ctx = new AnnotationConfigApplicationContext(MainDriver.class);
    MainDriver l = ctx.getBean(MainDriver.class);
    System.out.println("In main() the ctx is " + ctx);
    l.test();

}

public void test() {
    System.out.println("hello");
    System.out.println("env is " + env);
    System.out.println("cenv is " + cenv);
    System.out.println("ctx is" + ctx);
}
}
</code>```

I understood that within main() we are Creating a new Application context and then creating Bean and eventually calling test() method.

What I am not able to understand how come Environment , ApplicationContext and ConfigurableEnvironment get Autowired (and to which bean?)

I observed that the autowired ctx gets the context which is initialise in main().

Basically not able to understand how these gets autowired by itself (and what they are set to?)

Any help in understanding this would be of great help.

答:
Any class that is annotated with @Configuration is also a Spring bean. That means the MainDirver is also a spring bean that will be created during creating AnnotationConfigApplicationContext.

And after the MainDirver bean is created , Spring will then inject other beans into its field if that field is annotated with @Autowird. So in this case , Environment , ApplicationContext, and ConfigurableEnvironment are all injected this MainDirver bean.

P.S. You can think that Environment , ApplicationContext, and ConfigurableEnvironment are kind of Spring infrastructure beans that must be created even though you do not define them using @Configuration , @Service , @Bean and etc.

Body:
I have written the following simple stand-alone spring app:

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

@Configuration
@ComponentScan(basePackages = { "com.example" })
@PropertySource(ignoreResourceNotFound = true, value = "classpath:/application.props")
public class MainDriver {

@Autowired
private Environment env;
@Autowired
private ApplicationContext ctx;
@Autowired
private ConfigurableEnvironment cenv;

public static void main(String[] args) {

    ApplicationContext ctx = new AnnotationConfigApplicationContext(MainDriver.class);
    MainDriver l = ctx.getBean(MainDriver.class);
    System.out.println("In main() the ctx is " + ctx);
    l.test();

}

public void test() {
    System.out.println("hello");
    System.out.println("env is " + env);
    System.out.println("cenv is " + cenv);
    System.out.println("ctx is" + ctx);
}
}

I understood that within main() we are Creating a new Application context and then creating Bean and eventually calling test() method.

What I am not able to understand how come Environment , ApplicationContext and ConfigurableEnvironment get Autowired (and to which bean?)

I observed that the autowired ctx gets the context which is initialise in main().

Basically not able to understand how these gets autowired by itself (and what they are set to?)

Any help in understanding this would be of great help.


Title: How to convert a character array to data frame

Body:
I have a character array dat which I want to convert to a data frame df but it is not working

 head(dat)
[1] "   1931   1    5.0     0.6      11    78.4    43.4"
[2] "   1931   2    6.7     0.7       7    48.9    63.6"
[3] "   1931   4   10.4     3.1       3    44.6   110.1"
[4] "   1931   5   13.2     6.1       1    63.7   167.4"
[5] "   1931   6   15.4     8.0       0    87.8   150.3"
[6] "   1931   7   17.3    10.6       0   121.4   111.2"

> df<-as.data.frame(dat)
> head(df)
                                                 dat
1    1931   1    5.0     0.6      11    78.4    43.4
2    1931   2    6.7     0.7       7    48.9    63.6
3    1931   4   10.4     3.1       3    44.6   110.1
4    1931   5   13.2     6.1       1    63.7   167.4
5    1931   6   15.4     8.0       0    87.8   150.3
6    1931   7   17.3    10.6       0   121.4   111.2

df[,c(3)]

Error in [.data.frame(df, , c(3)) : undefined columns selected

Body:
Here's a tidyverse approach:

dat <- c("   1931   1    5.0     0.6      11    78.4    43.4",
         "   1931   2    6.7     0.7       7    48.9    63.6",
         "   1931   4   10.4     3.1       3    44.6   110.1",
         "   1931   5   13.2     6.1       1    63.7   167.4",
         "   1931   6   15.4     8.0       0    87.8   150.3",
         "   1931   7   17.3    10.6       0   121.4   111.2")

library(tidyverse)
str_trim(dat) %>%     # trim leading space
  tibble(x = .) %>%   # put into tibble (data.frame)
  separate(x,         # separate x into 7 columns, named below
           into = c("year","v1","v2","v3","v4","v5","v6"),
           sep = "[ ]{1,}")  # separate by one or more spaces ("[ ]{1,}")

That leads to:

# A tibble: 6 x 7
  year  v1    v2    v3    v4    v5    v6
  <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 1931  1     5.0   0.6   11    78.4  43.4
2 1931  2     6.7   0.7   7     48.9  63.6
3 1931  4     10.4  3.1   3     44.6  110.1
4 1931  5     13.2  6.1   1     63.7  167.4
5 1931  6     15.4  8.0   0     87.8  150.3
6 1931  7     17.3  10.6  0     121.4 111.2


问:
Java: what's the big-O time of declaring an array of size n?
What is the running time of declaring an array of size n in Java? I suppose this would depend on whether the memory is zero'ed out on garbage collection (in which case it could be O(1) ) or on initialization (in which case it'd have to be O(n) ).</p>

答:
It's O(n). Consider this simple program:

```<code>public class ArrayTest {

  public static void main(String[] args) {
     int[] var = new int[5];
  }

}
</code>```

The bytecode generated is:

```<code>Compiled from "ArrayTest.java"
public class ArrayTest extends java.lang.Object{
public ArrayTest();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_5
   1:   newarray int
   3:   astore_1
   4:   return

}
</code>```

The instruction to take a look at is the newarray instruction (just search for newarray). From the VM Spec:

A new array whose components are of type atype and of length count is allocated from the garbage-collected heap. A reference arrayref to this new array object is pushed into the operand stack. Each of the elements of the new array is initialized to the default initial value for the type of the array (§2.5.1).

Since each element is being initialized, it would take O(n) time.

EDIT

Looking at the link amit provided, it is possible to implement array-initialization with a default value, in constant time. So I guess it ultimately depends on the JVM. You could do some rough benchmarking to see if this is the case.

Body:
It's O(n). Consider this simple program:

public class ArrayTest {

  public static void main(String[] args) {
     int[] var = new int[5];
  }

}

The bytecode generated is:

Compiled from "ArrayTest.java"
public class ArrayTest extends java.lang.Object{
public ArrayTest();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   iconst_5
   1:   newarray int
   3:   astore_1
   4:   return

}

The instruction to take a look at is the newarray instruction (just search for newarray). From the VM Spec:

A new array whose components are of type atype and of length count is allocated from the garbage-collected heap. A reference arrayref to this new array object is pushed into the operand stack. Each of the elements of the new array is initialized to the default initial value for the type of the array (§2.5.1).

Since each element is being initialized, it would take O(n) time.

EDIT

Looking at the link amit provided, it is possible to implement array-initialization with a default value, in constant time. So I guess it ultimately depends on the JVM. You could do some rough benchmarking to see if this is the case.


问:
How to set css property according to css property of other element
I am using ionic 4 and want to set some mask element above other element.
My mask element is a fixed image that I want to set just above the ion-tab-bar - it means that I want my image "bottom" css property will be just the same as the ion-tab-bar css "height" property value.

I have already tried this inside the tabs page:

```<code>ionViewDidEnter() {
    document.getElementById('mask').style.bottom = document.getElementById('tabsbar').style.height;
}
</code>```

But the style property returned empty fields...

Is there some other way? maybe with ngStyle?

答:
you could go the jquery way:

function hallo(){
    $("#num1").css("bottom", $("#num2").css("height"));
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#num1{
position: absolute;
bottom: 100px;
background-color: red;
padding: 15px;
width: 100px;
height: 50px;
}
#num2{
position: absolute;
top: 0;
left: 100px;
background-color: green;
padding: 15px;
width: 100px;
height: 150px;
}</code>```

<button onclick="hallo();">I position red div at bottom: 150px</button>

```

Body:
I am using ionic 4 and want to set some mask element above other element.
My mask element is a fixed image that I want to set just above the ion-tab-bar - it means that I want my image "bottom" css property will be just the same as the ion-tab-bar css "height" property value.

I have already tried this inside the tabs page:

ionViewDidEnter() {
    document.getElementById('mask').style.bottom = document.getElementById('tabsbar').style.height;
}

But the style property returned empty fields...

Is there some other way? maybe with ngStyle?

Body:
you could go the jquery way:

function hallo(){
    $("#num1").css("bottom", $("#num2").css("height"));
}

#num1{
position: absolute;
bottom: 100px;
background-color: red;
padding: 15px;
width: 100px;
height: 50px;
}
#num2{
position: absolute;
top: 0;
left: 100px;
background-color: green;
padding: 15px;
width: 100px;
height: 150px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div id="num1">
</div>
<div id="num2">

<button onclick="hallo();">I position red div at bottom: 150px</button>
</div>


问:
driver.find_element_by_css_selector running slow toward end of page
I have a from selenium import webdriver temperature web scraper working from weather.com using Python. The web scraper at the beginning of the page finds the correct high and low temperature almost instantly. However, toward the end of the page, it gets increasingly slower (takes 7 seconds toward the end). This is probably because the scraper has to go through more HTML to find the correct data(?). Here is the main part of the code:

```<code>high = driver.find_element_by_css_selector('#twc-scrollabe > table > tbody > tr:nth-child(' + str(j) + ') > td.temp > div > span:nth-child(1)').text
low = driver.find_element_by_css_selector('#twc-scrollabe > table > tbody > tr:nth-child(' + str(j) + ') > td.temp > div > span:nth-child(3)').text
    date = driver.find_element_by_css_selector('#twc-scrollabe > table > tbody > tr:nth-child(' + str(j) + ') > td:nth-child(2) > div > span').text

#auth > div > div > div > div > div > form > button

#twc-scrollabe > table > tbody > tr:nth-child(1) > td:nth-child(2) > div > span
#twc-scrollabe > table > tbody > tr:nth-child(2) > td:nth-child(2) > div > span
</code>```

Is there an easy (or complex) fix to this? And if you think there is no easy solution, that would be great help too (which could be the case?)

答:
Is any content that you're looking for generated by JavaScript? If it's only HTML you could avoid headless browser and use requests and bs4:

```<code>$ python test.py
Got response: 200
Today JUN 1  80°/61°
Sun   JUN 2  70°/47°
Mon   JUN 3  63°/45°
Tue   JUN 4  74°/57°
Wed   JUN 5  75°/64°
Thu   JUN 6  77°/63°
Fri   JUN 7  77°/64°
Sat   JUN 8  81°/66°
Sun   JUN 9  81°/65°
Mon   JUN 10 80°/63°
Tue   JUN 11 80°/63°
Wed   JUN 12 81°/62°
Thu   JUN 13 80°/63°
Fri   JUN 14 81°/63°
Sat   JUN 15 81°/63°
Total: 0.66s, request: 0.60s
</code>```

test.py

```<code>import requests
import time

from bs4 import BeautifulSoup

URL = 'https://weather.com/weather/tenday/l/USPA1290:1:US'

def fetch(url):
    with requests.Session() as s:
        r = s.get(URL, timeout=5)
        return r

def main():
    start_t = time.time()
    resp = fetch(URL)
    print(f'Got response: {resp.status_code}')
    html = resp.text
    bs = BeautifulSoup(html, 'html.parser')
    tds = bs.find_all('td', class_='twc-sticky-col', attrs={'headers': 'day'})
    for td in tds:
        date_time = td.find_next('span', class_='date-time')
        day_detail = td.find_next('span', class_='day-detail')
        temp = td.find_next('td', class_='temp', attrs={'headers': 'hi-lo'})
        hi_lo = '/'.join(i.text for i in temp.find_all('span', class_=''))
        print(f'{date_time.text:5} {day_detail.text:6} {hi_lo}')
    end_t = time.time()
    elapsed_t = end_t - start_t
    r_time = resp.elapsed.total_seconds()
    print(f'Total: {elapsed_t:.2f}s, request: {r_time:.2f}s')

if __name__ == '__main__':
    main()
</code>```

Body:
I have a from selenium import webdriver temperature web scraper working from weather.com using Python. The web scraper at the beginning of the page finds the correct high and low temperature almost instantly. However, toward the end of the page, it gets increasingly slower (takes 7 seconds toward the end). This is probably because the scraper has to go through more HTML to find the correct data(?). Here is the main part of the code:

high = driver.find_element_by_css_selector('#twc-scrollabe > table > tbody > tr:nth-child(' + str(j) + ') > td.temp > div > span:nth-child(1)').text
low = driver.find_element_by_css_selector('#twc-scrollabe > table > tbody > tr:nth-child(' + str(j) + ') > td.temp > div > span:nth-child(3)').text
    date = driver.find_element_by_css_selector('#twc-scrollabe > table > tbody > tr:nth-child(' + str(j) + ') > td:nth-child(2) > div > span').text

#auth > div > div > div > div > div > form > button

#twc-scrollabe > table > tbody > tr:nth-child(1) > td:nth-child(2) > div > span
#twc-scrollabe > table > tbody > tr:nth-child(2) > td:nth-child(2) > div > span

Is there an easy (or complex) fix to this? And if you think there is no easy solution, that would be great help too (which could be the case?)

Body:
Is any content that you're looking for generated by JavaScript? If it's only HTML you could avoid headless browser and use requests and bs4:

$ python test.py
Got response: 200
Today JUN 1  80°/61°
Sun   JUN 2  70°/47°
Mon   JUN 3  63°/45°
Tue   JUN 4  74°/57°
Wed   JUN 5  75°/64°
Thu   JUN 6  77°/63°
Fri   JUN 7  77°/64°
Sat   JUN 8  81°/66°
Sun   JUN 9  81°/65°
Mon   JUN 10 80°/63°
Tue   JUN 11 80°/63°
Wed   JUN 12 81°/62°
Thu   JUN 13 80°/63°
Fri   JUN 14 81°/63°
Sat   JUN 15 81°/63°
Total: 0.66s, request: 0.60s

test.py

import requests
import time

from bs4 import BeautifulSoup

URL = 'https://weather.com/weather/tenday/l/USPA1290:1:US'

def fetch(url):
    with requests.Session() as s:
        r = s.get(URL, timeout=5)
        return r

def main():
    start_t = time.time()
    resp = fetch(URL)
    print(f'Got response: {resp.status_code}')
    html = resp.text
    bs = BeautifulSoup(html, 'html.parser')
    tds = bs.find_all('td', class_='twc-sticky-col', attrs={'headers': 'day'})
    for td in tds:
        date_time = td.find_next('span', class_='date-time')
        day_detail = td.find_next('span', class_='day-detail')
        temp = td.find_next('td', class_='temp', attrs={'headers': 'hi-lo'})
        hi_lo = '/'.join(i.text for i in temp.find_all('span', class_=''))
        print(f'{date_time.text:5} {day_detail.text:6} {hi_lo}')
    end_t = time.time()
    elapsed_t = end_t - start_t
    r_time = resp.elapsed.total_seconds()
    print(f'Total: {elapsed_t:.2f}s, request: {r_time:.2f}s')

if __name__ == '__main__':
    main()


问:
Round to the closest .25
Does anyone know of a way to round to the closest .25 in t-sql?  Currently I am rounding down using

```<code>floor(value * 4)/4
</code>```

My client is changing their algorithm and wants to do a midpoint round to the closest quarter.  If the value is less than .125 round to 0.00, if the value is greater than or equal to .125 round up to .25.

答:
I needed to round to an arbitrary precision & rounding strategy.

rounding to *.25

```<code>DECLARE @roundamt DECIMAL(16,2) = .25, @value DECIMAL(18, 2) = 1.7688
SELECT  ROUND(  (@value - FLOOR(@value)) / @roundamt, 0 ) * @roundamt + FLOOR(@value)
</code>```

-- result = 1.750000

different rounding strategies like 0.02, 0.25, 0.5, 0.75

```<code>SELECT
    x.roundamt, ROUND(  (@value - FLOOR(@value)) / roundamt, 0 ) * roundamt + FLOOR(@value)
FROM
    ( VALUES (0.02), (0.25), (0.5), (0.75) )x(roundamt)
</code>```

Title: Round to the closest .25

Body:
Does anyone know of a way to round to the closest .25 in t-sql?  Currently I am rounding down using

floor(value * 4)/4

My client is changing their algorithm and wants to do a midpoint round to the closest quarter.  If the value is less than .125 round to 0.00, if the value is greater than or equal to .125 round up to .25.

Body:
I needed to round to an arbitrary precision & rounding strategy.

rounding to *.25

DECLARE @roundamt DECIMAL(16,2) = .25, @value DECIMAL(18, 2) = 1.7688
SELECT  ROUND(  (@value - FLOOR(@value)) / @roundamt, 0 ) * @roundamt + FLOOR(@value)

-- result = 1.750000

different rounding strategies like 0.02, 0.25, 0.5, 0.75

SELECT
    x.roundamt, ROUND(  (@value - FLOOR(@value)) / roundamt, 0 ) * roundamt + FLOOR(@value)
FROM
    ( VALUES (0.02), (0.25), (0.5), (0.75) )x(roundamt)


问:
How to find "By Name" in mongoose
I am trying to get database values using a specific name. I want to  get all the books an author written.

This is my code to get the first name of the author and search for all the books he's written in BookDB using Like operator as in mysql

```<code>//get books by author name
router.route('/authorName').get((req, res) => {
    let authorName = req.params.authorName; //how can i pass this value to below regex command
    BookDB.find({"firstName": /authorName/}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});
</code>```

Problem: How can I pass authorName to the {"firstName": /authorName/}.
The way I have written, it is not set the authorName properly.

答:
I am not sure in the mongoose part, but you can also create regular expressions as:
new RegExp(exp: string, flags: string)

Note if you use this format,  the start and end slash has no special meaning, they would mean the string starts with a slash

Title: How to find "By Name" in mongoose

Body:
I am trying to get database values using a specific name. I want to  get all the books an author written.

This is my code to get the first name of the author and search for all the books he's written in BookDB using Like operator as in mysql

//get books by author name
router.route('/authorName').get((req, res) => {
    let authorName = req.params.authorName; //how can i pass this value to below regex command
    BookDB.find({"firstName": /authorName/}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});

Problem: How can I pass authorName to the {"firstName": /authorName/}.
The way I have written, it is not set the authorName properly.


问:
C++ alloc array of objects
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

```<code>ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}
</code>```

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)

答:
You could optimize this, with removing str and fileName:

out[ i ].open( ss.str().c_str() );

Also, I'd recommend you yo use std::vector not to carry about memory allocation and deallocation.

std::vector< std::ofstream >

Title: C++ alloc array of objects

Body:
I've got this issue with allocation of an array of some objects that I need to initialize with some constructor. Let me show what I mean:

ofstream* out = new ofstream[10];

for(int i = 0; i < 10; i++){
    stringstream ss;
    ss << "file" << i << ".txt";
    string str(ss.str());
    char *fileName = (char*)str.c_str();
    out[i] = ofstream(fileName); //Now, this is wrong
}

And I need some help on the wrong marked line. How do I allocate each member of that array?

And thank you for not pointing me to other posts (I looked on a lot before posting)


问:
How do we override the default indexing limit in mongoDB?
I have an AWS Cognito JWT of more than 125 characters for which I need to create indexing in MongoDB. But the problem is MongoDB indexing accepts the character of max limit, 125. How can we set the max limit or is there any way to increase the default character limit.

I tried indexing the JWT(around 150 characters) where I have the following error.

```<code>  MongoError: WiredTigerIndex::insert: key too large to index, failing  1025 { : "abc@xyz.com", "asdfghjkertyjk......"}
</code>```

This how I created schema index.

```<code>schemaName.index({ email: 1, token: 1 });
</code>```

答:
I would go with a different approach, as indexing a large text/string field is not always the best option.

Use SHA1 or MD5 to generate a unique checksum of the JWT string (which will give you a constant string length) and save that field. Index and search by that field

Another option is to decode the JWT token to JSON and store it as an embedded document - and then you can index the document (but it's risky option IMHO)

Body:
I have an AWS Cognito JWT of more than 125 characters for which I need to create indexing in MongoDB. But the problem is MongoDB indexing accepts the character of max limit, 125. How can we set the max limit or is there any way to increase the default character limit.

I tried indexing the JWT(around 150 characters) where I have the following error.

  MongoError: WiredTigerIndex::insert: key too large to index, failing  1025 { : "abc@xyz.com", "asdfghjkertyjk......"}

This how I created schema index.

schemaName.index({ email: 1, token: 1 });


问:
cout does not name a type despite wrapped functions and namespace std
I am getting the error 'cout does not name a type' (line 36 ie main function) along with a couple of other errors in main().

All code is wrapped well within the functions and I have used

using namespace std;
```

<p>but I am still getting this error along with other ~identifier~ was not declared in this scope errors in the main function. </p>

<p>Code:</p>

<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include<cmath>

using namespace std;

double discriminant (double a, double b, double c){
    return (pow(b,2) - (4 * a * c));
}

double* compute_roots(double a, double b, double c){
    double* x;
    double x1,x2;
    double d = discriminant(a,b,c);
    if (d>0){
        cout<<"Two real roots"<<endl;
    }
    else if (d=0){
        cout<<"One unique solution"<<endl;
    }
    else
        {
        cout<<"Does not support complex roots";
        //throw "Negative roots!";
        return x;
    }
    x1 = (-b + sqrt(d))/(2*a);
    x2 = (-b - sqrt(d))/(2*a);
    x[0] = x1;
    x[1] = x2;
    return x;
}

int main{
    double a=2.0,b=5,c=3.1;
    double* res=compute_roots(a,b,c);
    cout<<res[0];
    cout<<res[1];
    return 0;
}
</code>```

答:
the main function misses (). and you are using d = 0 as the condition for else if not an error but it is not what you want. you also have memory leak.
this is probably what you need:

```<code>#include<iostream>
#include<cmath>
#include <memory>

using namespace std;

double discriminant(double a, double b, double c) {
    return (pow(b, 2) - (4 * a * c));
}
void deleter(double* x) {
    delete[] x;
}
shared_ptr<double> compute_roots(double a, double b, double c) {
    shared_ptr<double> x;
    x.reset(new double[2], deleter);
    double x1, x2;
    double d = discriminant(a, b, c);
    if (d > 0) {
        cout << "Two real roots" << endl;
    }
    else if (d == 0) {
        cout << "One unique solution" << endl;
    }
    else
    {
        cout << "Does not support complex roots";
        //throw "Negative roots!";
        return x;
    }
    x1 = (-b + sqrt(d)) / (2 * a);
    x2 = (-b - sqrt(d)) / (2 * a);
    x.get()[0] = x1;
    x.get()[1] = x2;
    return x;
}

int main() {
    double a = 2.0, b = 5, c = 3.1;
    shared_ptr<double> res = compute_roots(a, b, c);
    cout << res.get()[0];
    cout << res.get()[1];
    return 0;
}
</code>```

Body:
I am getting the error 'cout does not name a type' (line 36 ie main function) along with a couple of other errors in main().

All code is wrapped well within the functions and I have used

using namespace std;

but I am still getting this error along with other ~identifier~ was not declared in this scope errors in the main function.

Code:

#include<iostream>
#include<cmath>

using namespace std;

double discriminant (double a, double b, double c){
    return (pow(b,2) - (4 * a * c));
}

double* compute_roots(double a, double b, double c){
    double* x;
    double x1,x2;
    double d = discriminant(a,b,c);
    if (d>0){
        cout<<"Two real roots"<<endl;
    }
    else if (d=0){
        cout<<"One unique solution"<<endl;
    }
    else
        {
        cout<<"Does not support complex roots";
        //throw "Negative roots!";
        return x;
    }
    x1 = (-b + sqrt(d))/(2*a);
    x2 = (-b - sqrt(d))/(2*a);
    x[0] = x1;
    x[1] = x2;
    return x;
}

int main{
    double a=2.0,b=5,c=3.1;
    double* res=compute_roots(a,b,c);
    cout<<res[0];
    cout<<res[1];
    return 0;
}

Body:
the main function misses (). and you are using d = 0 as the condition for else if not an error but it is not what you want. you also have memory leak.
this is probably what you need:

#include<iostream>
#include<cmath>
#include <memory>

using namespace std;

double discriminant(double a, double b, double c) {
    return (pow(b, 2) - (4 * a * c));
}
void deleter(double* x) {
    delete[] x;
}
shared_ptr<double> compute_roots(double a, double b, double c) {
    shared_ptr<double> x;
    x.reset(new double[2], deleter);
    double x1, x2;
    double d = discriminant(a, b, c);
    if (d > 0) {
        cout << "Two real roots" << endl;
    }
    else if (d == 0) {
        cout << "One unique solution" << endl;
    }
    else
    {
        cout << "Does not support complex roots";
        //throw "Negative roots!";
        return x;
    }
    x1 = (-b + sqrt(d)) / (2 * a);
    x2 = (-b - sqrt(d)) / (2 * a);
    x.get()[0] = x1;
    x.get()[1] = x2;
    return x;
}

int main() {
    double a = 2.0, b = 5, c = 3.1;
    shared_ptr<double> res = compute_roots(a, b, c);
    cout << res.get()[0];
    cout << res.get()[1];
    return 0;
}


问:
xamarin form cannot keep last state
I am trying to keep the state of some variable of my xamarin form when I close the app and start it but is not working

I have 2 variable "isconnected" and "eric"

```<code>var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();
</code>```

After closing the app when I restart it and trying to get the values of my variable like this :

```<code>((bool)App.Current.Properties["UserIsConnected"] ))
((string)App.Current.Properties["userName"] ))
</code>```

I have this error:

```<code>System.Collections.Generic.KeyNotFoundException: The given key 'UserIsConnected' was not present in the dictionary.
</code>```

How can I saved my variable and get them when restart the app?

thanks in advance for your help

答:
You seem to be saving a property with the key "isconnected" and trying to retrieve it with a different key ("UserIsConnected").

EDIT:

OK, thanks for clearing that the error I pointed out was a typo. As for the problem, try this instead:

```<code>App.Current.Properties.Add("UserIsConnected", true);
await App.Current.SavePropertiesAsync();
</code>```

And make sure you check if the key exists before using it:

```<code>if (App.Current.Properties.ContainsKey("UserIsConnected"))
{
    //Do something awesome.
}
</code>```

Title: xamarin form cannot keep last state

Body:
I am trying to keep the state of some variable of my xamarin form when I close the app and start it but is not working

I have 2 variable "isconnected" and "eric"

var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();

After closing the app when I restart it and trying to get the values of my variable like this :

((bool)App.Current.Properties["UserIsConnected"] ))
((string)App.Current.Properties["userName"] ))

I have this error:

System.Collections.Generic.KeyNotFoundException: The given key 'UserIsConnected' was not present in the dictionary.

How can I saved my variable and get them when restart the app?

thanks in advance for your help

Body:
You seem to be saving a property with the key "isconnected" and trying to retrieve it with a different key ("UserIsConnected").

EDIT:

OK, thanks for clearing that the error I pointed out was a typo. As for the problem, try this instead:

App.Current.Properties.Add("UserIsConnected", true);
await App.Current.SavePropertiesAsync();

And make sure you check if the key exists before using it:

if (App.Current.Properties.ContainsKey("UserIsConnected"))
{
    //Do something awesome.
}