问:
HTML Text before and after (Prefix/Suffix) Input field
I need to do have in HTML text show up before and after an input field, on the same line. The prefix and suffix are added at run time, and may or may not be there. I have tried  and  and combinations there of. Here is what I have now:

Here is what I am trying to achieve (remembering that the values will sometimes not be there, so I would like the text input recover that space when they are not there:

Here is my current code (I did cut out some class defs to make it more readable):

```<code><div>
    <div>Prefix and Suffix</div>
    <div class="row">
        <span style="display:inline-block">Test<input type="text" class="input">Dollars</span>
    </div>
</div>
</code>```

I would prefer a solution that does not use tables (just div) but if that is the only way to do it, so be it.

答:
using flex seems to work just fine for me. Might be worth a try.</p>

```<code>   <div style="display:flex;">
       <div>Test </div>
       <input type="text">
       <div> Dollars</div>
    </div>
</code>```

Body:
I need to do have in HTML text show up before and after an input field, on the same line. The prefix and suffix are added at run time, and may or may not be there. I have tried  and  and combinations there of. Here is what I have now:

Here is what I am trying to achieve (remembering that the values will sometimes not be there, so I would like the text input recover that space when they are not there:

Here is my current code (I did cut out some class defs to make it more readable):

Prefix and Suffix

        Test<input type="text" class="input">Dollars

I would prefer a solution that does not use tables (just div) but if that is the only way to do it, so be it.

Body:
using flex seems to work just fine for me. Might be worth a try.

   <div style="display:flex;">
       <div>Test&nbsp;</div>
       <input type="text">
       <div>&nbsp;Dollars</div>
    </div>


来源: stackexchange

问:
load variables from in memory setting file
i have settings.py file that looks like:

```<code>DEBUG = True
CACHE_IP = '0.0.0.0'
DB_SETTINGS = {
    'SERVERS': ['127.0.0.1:80'],
    'MAX_IDLE_TIME' : 180,
}
</code>```

this file is stored at external cloud storage.

I have a process the get the url to this file, and load it into memory (not to disk). when loading it into memory it will be string type and looks like:

```<code>"DEBUG = True\n CACHE_IP = '0.0.0.0'\n DB_SETTINGS = {\n    'SERVERS': ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n"
</code>```

How for example i can get the values from this string? i mean, how can i get a dictionary where key=verb name from file, and value = value from file? is there any pythonic way for this?

so my dictionary will look like:

```<code>{'DEBUG': True, 'CACHE_IP' = '0.0.0.0', 'DB_SETTINGS': {...}}
</code>```

答:
Your requirement is very specific but this kind of requirements do arise. So, I tried to solve this using method below:

```<code>In [102]: import ast # Do not use eval(its unsafe)

In [103]: string = "DEBUG = True\n CACHE_IP = '0.0.0.0'\n DB_SETTINGS = {\n    '
     ...: SERVERS': ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n"
     ...:

In [104]: def parse_key_val(string):
     ...:     tmp_dict = {}
     ...:     for r in re.split('(?<![{},])\n (?!{)', string):
     ...:         key, val = r.split(" = ")
     ...:         if '{' in val:
     ...:             val = ast.literal_eval(val)
     ...:         tmp_dict[key] = val
     ...:     return tmp_dict
     ...:

In [105]: parse_key_val(string)
Out[105]:
{'CACHE_IP': "'0.0.0.0'",
 'DB_SETTINGS': {'MAX_IDLE_TIME': 180, 'SERVERS': ['127.0.0.1:80']},
 'DEBUG': 'True'}
</code>```

This solution works great for the string you provided but it might(or not) fail in some complex cases. But this solution gives a good starting point of how to start. You might need to make some modifications to make it work for complex cases.

Now coming to the program, the important parts here to understand are:

```<code>re.split('(?<![{},])\n (?!{)', string)
</code>```

and

```<code>val = ast.literal_eval(val)
</code>```

The pattern (?<![{},])\n (?!{) in re.split means, split the string on character \n but only if it is not after { or } or , and not before {. This regex is created to not split \n line character in dict strings.

Not the second part val = ast.literal_eval(val) builds on top of the above regex step as above step doesn't break the dict string. The resulting dict part of string after split is:

```<code>"DB_SETTINGS = {\n    'SERVERS': ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n"
</code>```

With ast.literal_eval the task of parsing dict, nested dict and list inside it very easy. That it!

One more thing, do not use eval as one of the solution suggests here, it's a security risk.

You can read more about ast here

ContentLicense: CC BY-SA 3.0

Body:
i have settings.py file that looks like:

DEBUG = True
CACHE_IP = '0.0.0.0'
DB_SETTINGS = {
    'SERVERS': ['127.0.0.1:80'],
    'MAX_IDLE_TIME' : 180,
}

this file is stored at external cloud storage.

I have a process the get the url to this file, and load it into memory (not to disk). when loading it into memory it will be string type and looks like:

"DEBUG = True\n CACHE_IP = '0.0.0.0'\n DB_SETTINGS = {\n    'SERVERS': ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n"

How for example i can get the values from this string? i mean, how can i get a dictionary where key=verb name from file, and value = value from file? is there any pythonic way for this?

so my dictionary will look like:

{'DEBUG': True, 'CACHE_IP' = '0.0.0.0', 'DB_SETTINGS': {...}}

Body:
Your requirement is very specific but this kind of requirements do arise. So, I tried to solve this using method below:

In [102]: import ast # Do not use eval(its unsafe)

In [103]: string = "DEBUG = True\n CACHE_IP = '0.0.0.0'\n DB_SETTINGS = {\n    '
     ...: SERVERS': ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n"
     ...:

In [104]: def parse_key_val(string):
     ...:     tmp_dict = {}
     ...:     for r in re.split('(?<![{},])\n (?!{)', string):
     ...:         key, val = r.split(" = ")
     ...:         if '{' in val:
     ...:             val = ast.literal_eval(val)
     ...:         tmp_dict[key] = val
     ...:     return tmp_dict
     ...:

In [105]: parse_key_val(string)
Out[105]:
{'CACHE_IP': "'0.0.0.0'",
 'DB_SETTINGS': {'MAX_IDLE_TIME': 180, 'SERVERS': ['127.0.0.1:80']},
 'DEBUG': 'True'}

This solution works great for the string you provided but it might(or not) fail in some complex cases. But this solution gives a good starting point of how to start. You might need to make some modifications to make it work for complex cases.

Now coming to the program, the important parts here to understand are:

re.split('(?<![{},])\n (?!{)', string)

and

val = ast.literal_eval(val)

The pattern (?<![{},])\n (?!{) in re.split means, split the string on character \n but only if it is not after { or } or , and not before {. This regex is created to not split \n line character in dict strings.

Not the second part val = ast.literal_eval(val) builds on top of the above regex step as above step doesn't break the dict string. The resulting dict part of string after split is:

"DB_SETTINGS = {\n    'SERVERS': ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n"

With ast.literal_eval the task of parsing dict, nested dict and list inside it very easy. That it!

One more thing, do not use eval as one of the solution suggests here, it's a security risk.

You can read more about ast here


问:
Control Where Pages Are Inserted
I am using the below syntax to split a master pdf into multiple sub pdfs.  My issue is that the pages are inserted in reverse order, so instead of going 1, 2, 3, 4 the input goes 4, 3, 2, 1.

What would I need to change so that the order of pages in the new workbook goes 1, 2, 3 4?

```<code>    For i = 1 To PNum
        Set newPDF = CreateObject("AcroExch.pdDoc")
        newPDF.Create
        NewName = "R:" & i & ".pdf"
        newPDF.InsertPages -1, PDDoc, i, 4, 0
        newPDF.Save 1, NewName
        newPDF.Close
        Set newPDF = Nothing
Next i
</code>```

答:
In the first parameter (-1) you are telling Acrobat to insert your new pages before page 1. Acrobat page numbers are zero based so the line should read...

```<code>newPDF.InsertPages newPDF.GetNumPages-1, PDDoc, i, 4, 0
</code>```

... to insert new pages at the end of the new PDF document.

Title: Control Where Pages Are Inserted

Body:
I am using the below syntax to split a master pdf into multiple sub pdfs.  My issue is that the pages are inserted in reverse order, so instead of going 1, 2, 3, 4 the input goes 4, 3, 2, 1.

What would I need to change so that the order of pages in the new workbook goes 1, 2, 3 4?

    For i = 1 To PNum
        Set newPDF = CreateObject("AcroExch.pdDoc")
        newPDF.Create
        NewName = "R:" & i & ".pdf"
        newPDF.InsertPages -1, PDDoc, i, 4, 0
        newPDF.Save 1, NewName
        newPDF.Close
        Set newPDF = Nothing
Next i

Body:
In the first parameter (-1) you are telling Acrobat to insert your new pages before page 1. Acrobat page numbers are zero based so the line should read...

newPDF.InsertPages newPDF.GetNumPages-1, PDDoc, i, 4, 0

... to insert new pages at the end of the new PDF document.


问:
INT stays the same outside FOR loop
Function "f_vowels" works; it prints the number of common vowels the two strings have. The other one, "two_c", should work as well; it gives true if the two strings share at least two common letters in the same position. My problem is the third one, cause it should print those letters but always prints the message "Strings don't have 2 common letters". I think I know why: I'm increasing "dim" with a FOR loop, but the boolean function's still working with the original "dim". How do I fix this?</p>

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

// functions' calls

void f_vowels(string, string);
bool two_c(int);
void print_2c(string, string, int, int);

// main
int main(){
string s1, s2;
int i, j, vowels;
int l1, l2;
char vow, c1, c2;

cout << "Enter your string: ";
getline(cin, s1);
cout << "\n";

cout << "Enter your string: ";
getline(cin, s2);
cout << "\n";

f_vowels(s1, s2);

int dim=0;
char common[dim];

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    common[dim++];
    }
}

two_c(dim);

if (two_c(dim)==true){
print_2c(s1, s2, l1, l2);
}

else cout << "Strings don't have 2 common letters.";

}

//functions

//common vowels

void f_vowels(string s1, string s2){

int l1=s1.length();
char c1[l1];
s1.copy(c1, l1);

int l2=s2.length();
char c2[l2];
s2.copy(c2, l2);

int vowels=0;
char vow[]={'a','e','i','o','u','A','E','I','O','U'};

for (int i=0; i<10; i++){
    for (int j=0; j<l1 && j<l2; j++){
    if (c1[j]=vow[i] && c2[j]==vow[i]){
        vowels++;
        }
      }
    }
    cout << vowels << "\n\n";
    }

 // true if strings have at least 2 common letters in the same position

bool two_c(int dim){

if (dim<2){
return false;
}
else return true;

}

// print boolean function

void print_2c(string s1, string s2, int l1, int l2){

int dim=0;
char common[dim];

    for (int i=0; i<l1 && i<l2; i++){
        for (int j=0; j<l1 && j<l2; j++){
            if (s1[i]==s2[i])
            common[j]=s1[i];
            cout << common[j] << "is a common letter. \n";
            }
      }
}
</code>```

答:
You are creating a char array with size 0.

```<code>int dim=0;//<-- Here!!
char common[dim];
</code>```

Change dim for the proper length (s1 or s2 length) and I think you would solve your problem

Title: INT stays the same outside FOR loop

Body:
Function "f_vowels" works; it prints the number of common vowels the two strings have. The other one, "two_c", should work as well; it gives true if the two strings share at least two common letters in the same position. My problem is the third one, cause it should print those letters but always prints the message "Strings don't have 2 common letters". I think I know why: I'm increasing "dim" with a FOR loop, but the boolean function's still working with the original "dim". How do I fix this?

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

// functions' calls

void f_vowels(string, string);
bool two_c(int);
void print_2c(string, string, int, int);

// main
int main(){
string s1, s2;
int i, j, vowels;
int l1, l2;
char vow, c1, c2;

cout << "Enter your string: ";
getline(cin, s1);
cout << "\n";

cout << "Enter your string: ";
getline(cin, s2);
cout << "\n";

f_vowels(s1, s2);

int dim=0;
char common[dim];

for (int i=0; i<l1 && i<l2; i++){
    if (s1[i]==s2[i])
    {
    common[dim++];
    }
}

two_c(dim);

if (two_c(dim)==true){
print_2c(s1, s2, l1, l2);
}

else cout << "Strings don't have 2 common letters.";

}

//functions

//common vowels

void f_vowels(string s1, string s2){

int l1=s1.length();
char c1[l1];
s1.copy(c1, l1);

int l2=s2.length();
char c2[l2];
s2.copy(c2, l2);

int vowels=0;
char vow[]={'a','e','i','o','u','A','E','I','O','U'};

for (int i=0; i<10; i++){
    for (int j=0; j<l1 && j<l2; j++){
    if (c1[j]=vow[i] && c2[j]==vow[i]){
        vowels++;
        }
      }
    }
    cout << vowels << "\n\n";
    }

 // true if strings have at least 2 common letters in the same position

bool two_c(int dim){

if (dim<2){
return false;
}
else return true;

}

// print boolean function

void print_2c(string s1, string s2, int l1, int l2){

int dim=0;
char common[dim];

    for (int i=0; i<l1 && i<l2; i++){
        for (int j=0; j<l1 && j<l2; j++){
            if (s1[i]==s2[i])
            common[j]=s1[i];
            cout << common[j] << "is a common letter. \n";
            }
      }
}

Body:
You are creating a char array with size 0.

int dim=0;//<-- Here!!
char common[dim];

Change dim for the proper length (s1 or s2 length) and I think you would solve your problem


问:
How to pass List<E> from RecyclerView Adapter to RecyclerView Holder?
I've been trying to find the answer to my question above but no post seems to help. I have a RecyclerView Adapter where I get the data as List from a database:

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {

    public List<Note> noteList;
    private View.OnLongClickListener longClickListener;
    private Context context;

    public RecyclerViewAdapter(List<Note> noteList, View.OnLongClickListener longClickListener, Context context) {
        this.noteList = noteList;
        this.longClickListener = longClickListener;
        this.context = context;
    }
</code>```

And a ViewHolder where I have an onClickListener to find the position of the view clicked using getLayoutPosition():

```<code>static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView noteTitleText;
        private TextView noteDescriptionText;
        private TextView dateText;
        private TextView weekText;

        RecyclerViewHolder(View view) {
            super(view);

            noteTitleText = (TextView) view.findViewById(R.id.noteTitleText);
            noteDescriptionText = (TextView) view.findViewById(R.id.noteDescriptionText);
            dateText = (TextView) view.findViewById(R.id.dateText);
            weekText = (TextView) view.findViewById(R.id.weekText);

            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int position = getLayoutPosition();

            // I want the noteList from the RecyclerViewAdapter here.
            Note note = noteList.get(position);

            Log.d("Item Clicked", String.valueOf(position));

        }
    }
</code>```

The purpose is that I need the noteList with all the notes from the RecyclerViewAdapter in the onClick() method to populate an Activity using an intent. How should I go about this?

答:
After trying out solutions for an hour, here's what I settled on. Instead of implementing OnClickListener in ViewHolder, I implemented it in RecyclerViewAdapter in onBindViewHolder() method, as:</p>

```<code>@Override
public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {
        final Note note = noteList.get(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // The note and noteList can be accessed here.
            }
        });
    }
</code>```

Body:
I've been trying to find the answer to my question above but no post seems to help. I have a RecyclerView Adapter where I get the data as List from a database:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {

    public List<Note> noteList;
    private View.OnLongClickListener longClickListener;
    private Context context;

    public RecyclerViewAdapter(List<Note> noteList, View.OnLongClickListener longClickListener, Context context) {
        this.noteList = noteList;
        this.longClickListener = longClickListener;
        this.context = context;
    }

And a ViewHolder where I have an onClickListener to find the position of the view clicked using getLayoutPosition():

static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView noteTitleText;
        private TextView noteDescriptionText;
        private TextView dateText;
        private TextView weekText;

        RecyclerViewHolder(View view) {
            super(view);

            noteTitleText = (TextView) view.findViewById(R.id.noteTitleText);
            noteDescriptionText = (TextView) view.findViewById(R.id.noteDescriptionText);
            dateText = (TextView) view.findViewById(R.id.dateText);
            weekText = (TextView) view.findViewById(R.id.weekText);

            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int position = getLayoutPosition();

            // I want the noteList from the RecyclerViewAdapter here.
            Note note = noteList.get(position);

            Log.d("Item Clicked", String.valueOf(position));

        }
    }

The purpose is that I need the noteList with all the notes from the RecyclerViewAdapter in the onClick() method to populate an Activity using an intent. How should I go about this?

Body:
After trying out solutions for an hour, here's what I settled on. Instead of implementing OnClickListener in ViewHolder, I implemented it in RecyclerViewAdapter in onBindViewHolder() method, as:

@Override
public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {
        final Note note = noteList.get(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // The note and noteList can be accessed here.
            }
        });
    }


问:
css being applied to all elements in array
When I run this function the CSS is being applied to all the buttons. How do I modify so that the CSS only gets modified for the buttons where the buttonAttr attribute equals disabled?</p>

```<code>$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});
</code>```

答:
You shouldn't check boolean attributes using the attr function. Use prop instead to return the actual value.

```<code>$('.product_tile .addtocartbutton').each(function(){
    $(this).prop('disabled') ? $(this).css('background','#ccc') : $(this).css('background','#EEDED1');
});
</code>```

Body:
When I run this function the CSS is being applied to all the buttons. How do I modify so that the CSS only gets modified for the buttons where the buttonAttr attribute equals disabled?

$('.product_tile .addtocartbutton').each(function(){
    var $this = $(this);
    var buttonAttr = $this.attr('disabled');

    if($this.attr('disabled') = 'disabled'){
        $this.css('background','#ccc');
    } else {
        $this.css('background','#EEDED1');
    }
});

Body:
You shouldn't check boolean attributes using the attr function. Use prop instead to return the actual value.

$('.product_tile .addtocartbutton').each(function(){
    $(this).prop('disabled') ? $(this).css('background','#ccc') : $(this).css('background','#EEDED1');
});


问:
Computing wrong value of integral using simpsons rule
I wrote the following piece of code for Simpson's rule integration to approximate sin. The equation is in this attachment. I wrote separate loops for the even and odd terms, as they are shown grouped in the attachment.

```<code>import math

x1=0
x2=math.pi
N=6
delta_x=(x2-x1)/N
f=math.sin
sum=f(0)

#odd summation
for i in range (1,N+1):
    sum=sum+f(x1+(2*i+1)*delta_x)

sum=4*sum
print(sum)

#even summation

for i in range(2,N+1):
    sumeven=0
    sumeven=sumeven+f(x1+(2*i)*delta_x)
sumeven=2*sumeven

sumeven=sumeven+f(N)
print(sumeven)

integral=(delta_x/3)*(sum+sumeven)
print(integral)
</code>```

But when I print the values, it gives me very small negative numbers.

Can anyone see what is wrong with my code?

答:
First of all, learn some basic debugging.  You've done only two simple print lines for this code, neither of which traces the more detailed problems.  See this lovely debug blog for help.  I added some instrumentation, cleaned up some style, and ran the code again, tracing the logic and data flow somewhat better.  Diagnosis below.

```<code>sum_odd = f(0)

# odd summation
for i in range (1, N+1):
    x_val = x1 + (2*i+1)*delta_x
    sum_odd = sum_odd + f(x_val)
    print (x_val/math.pi, "pi", f(x_val), sum_odd)

sum_odd = 4*sum_odd

print(sum_odd)

# even summation
for i in range(2, N+1):
    sum_even = 0
    x_val = x1 + (2*i)*delta_x
    sum_even = sum_even + f(x_val)
    print (x_val/math.pi, "pi", f(x_val), sum_even)
</code>```

Output:

```<code>0.5 pi 1.0 1.0
0.8333333333333333 pi 0.5000000000000003 1.5000000000000004
1.1666666666666665 pi -0.4999999999999997 1.0000000000000007
1.5 pi -1.0 6.661338147750939e-16
1.8333333333333333 pi -0.5000000000000004 -0.4999999999999998
2.1666666666666665 pi 0.4999999999999993 -4.996003610813204e-16
-1.9984014443252818e-15
0.6666666666666666 pi 0.8660254037844387 0.8660254037844387
1.0 pi 1.2246467991473532e-16 1.2246467991473532e-16
1.3333333333333333 pi -0.8660254037844384 -0.8660254037844384
1.6666666666666665 pi -0.866025403784439 -0.866025403784439
2.0 pi -2.4492935982947064e-16 -2.4492935982947064e-16
-0.27941549819892636
-0.04876720424671586
</code>```

DIAGNOSIS

You have two immediate problems:

You initialize sum_even inside the loop, which discards prior computations for that half of the series.  Move it before the loop.

You integrated over twice the specified range; this, alone, will get you a tiny value (ideally, this would be 0, the integral for a full cycle of the function).

Fix the initialization, fix the limits, and you should see good results, more like this:

```<code>0.16666666666666666 pi 0.49999999999999994 0.49999999999999994
0.5 pi 1.0 1.5
0.8333333333333333 pi 0.5000000000000003 2.0000000000000004
8.000000000000002
0.3333333333333333 pi 0.8660254037844386 0.8660254037844386
0.6666666666666666 pi 0.8660254037844387 1.7320508075688772
1.0 pi 1.2246467991473532e-16 1.7320508075688774
3.184686116938829
1.9520959854268212
</code>```

Also, I strongly recommend that you work through tutorials on debugging and coding style; these will help you in future work.  I know from experience.  :-)

Body:
I wrote the following piece of code for Simpson's rule integration to approximate sin. The equation is in this attachment. I wrote separate loops for the even and odd terms, as they are shown grouped in the attachment.

import math

x1=0
x2=math.pi
N=6
delta_x=(x2-x1)/N
f=math.sin
sum=f(0)

#odd summation
for i in range (1,N+1):
    sum=sum+f(x1+(2*i+1)*delta_x)

sum=4*sum
print(sum)

#even summation

for i in range(2,N+1):
    sumeven=0
    sumeven=sumeven+f(x1+(2*i)*delta_x)
sumeven=2*sumeven

sumeven=sumeven+f(N)
print(sumeven)

integral=(delta_x/3)*(sum+sumeven)
print(integral)

But when I print the values, it gives me very small negative numbers.

Can anyone see what is wrong with my code?

Body:
First of all, learn some basic debugging.  You've done only two simple print lines for this code, neither of which traces the more detailed problems.  See this lovely debug blog for help.  I added some instrumentation, cleaned up some style, and ran the code again, tracing the logic and data flow somewhat better.  Diagnosis below.

sum_odd = f(0)

# odd summation
for i in range (1, N+1):
    x_val = x1 + (2*i+1)*delta_x
    sum_odd = sum_odd + f(x_val)
    print (x_val/math.pi, "pi", f(x_val), sum_odd)

sum_odd = 4*sum_odd

print(sum_odd)

# even summation
for i in range(2, N+1):
    sum_even = 0
    x_val = x1 + (2*i)*delta_x
    sum_even = sum_even + f(x_val)
    print (x_val/math.pi, "pi", f(x_val), sum_even)

Output:

0.5 pi 1.0 1.0
0.8333333333333333 pi 0.5000000000000003 1.5000000000000004
1.1666666666666665 pi -0.4999999999999997 1.0000000000000007
1.5 pi -1.0 6.661338147750939e-16
1.8333333333333333 pi -0.5000000000000004 -0.4999999999999998
2.1666666666666665 pi 0.4999999999999993 -4.996003610813204e-16
-1.9984014443252818e-15
0.6666666666666666 pi 0.8660254037844387 0.8660254037844387
1.0 pi 1.2246467991473532e-16 1.2246467991473532e-16
1.3333333333333333 pi -0.8660254037844384 -0.8660254037844384
1.6666666666666665 pi -0.866025403784439 -0.866025403784439
2.0 pi -2.4492935982947064e-16 -2.4492935982947064e-16
-0.27941549819892636
-0.04876720424671586

DIAGNOSIS

You have two immediate problems:

You initialize sum_even inside the loop, which discards prior computations for that half of the series.  Move it before the loop.

You integrated over twice the specified range; this, alone, will get you a tiny value (ideally, this would be 0, the integral for a full cycle of the function).

Fix the initialization, fix the limits, and you should see good results, more like this:

0.16666666666666666 pi 0.49999999999999994 0.49999999999999994
0.5 pi 1.0 1.5
0.8333333333333333 pi 0.5000000000000003 2.0000000000000004
8.000000000000002
0.3333333333333333 pi 0.8660254037844386 0.8660254037844386
0.6666666666666666 pi 0.8660254037844387 1.7320508075688772
1.0 pi 1.2246467991473532e-16 1.7320508075688774
3.184686116938829
1.9520959854268212

Also, I strongly recommend that you work through tutorials on debugging and coding style; these will help you in future work.  I know from experience.  :-)


问:
java | Return a reversed array by FOR loop
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

```<code>    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }
  }
  return nums2;
}
</code>```

But it is throwing out three exact same numbers.

答:
There are so many efficient ways to do it but to make you understand i am gonna modify your own code

public int[] reverse3(int[] nums) {

```<code>      int[] nums2 = new int[3];

      for (int i = nums.length - 1; i >= 0; i--) {

         for (int j = (nums.length-1) - i; j < nums.length; j++) {

              nums2[j] = nums[i];

        }
      }

      return nums2;
    }
</code>```

or let's do a a little bit modification rather than using nums.length() again and again we can put it inside a variable

public int[] reverse3(int[] nums) {

```<code>      int[] nums2 = new int[3];
      int length = nums.length;
      for (int i = length - 1; i >= 0; i--) {

         for (int j = (length-1) - i; j < length; j++) {

              nums2[j] = nums[i];

        }
      }

      return nums2;
    }
</code>```

Remember it is not an efficient way but to make you understand i just modify the logic. Using nested loops like that will decrease the performance so better avoid it and try to do it in much more optimized way..

Body:
I am stuck with an exercise which tells me to create a reversed array from the given one.

After some thinking I made such code:

    public int[] reverse3(int[] nums) {

  int[] nums2 = new int[3];

  for (int i = nums.length - 1; i >= 0; i--) {

     for (int j = 0; j < nums.length; j++) {

          nums2[j] = nums[i];

    }
  }
  return nums2;
}

But it is throwing out three exact same numbers.

Body:
There are so many efficient ways to do it but to make you understand i am gonna modify your own code

public int[] reverse3(int[] nums) {

      int[] nums2 = new int[3];

      for (int i = nums.length - 1; i >= 0; i--) {

         for (int j = (nums.length-1) - i; j < nums.length; j++) {

              nums2[j] = nums[i];

        }
      }

      return nums2;
    }

or let's do a a little bit modification rather than using nums.length() again and again we can put it inside a variable

public int[] reverse3(int[] nums) {

      int[] nums2 = new int[3];
      int length = nums.length;
      for (int i = length - 1; i >= 0; i--) {

         for (int j = (length-1) - i; j < length; j++) {

              nums2[j] = nums[i];

        }
      }

      return nums2;
    }

Remember it is not an efficient way but to make you understand i just modify the logic. Using nested loops like that will decrease the performance so better avoid it and try to do it in much more optimized way..


问:
Nested JSON Feed Returns Error
I'm new to JSON feeds and swift 4 in general. I'm having trouble printing data from a nested JSON feed. First off, I'm unsure if I'm calling the array properly in my do statement. Second, when I build the app, I get the following long error. Could anyone help me decipher this? My code is at the bottom of the post. Thank you in advance.

2017-12-06 12:58:48.604154-0500 PlayerRankDOTA2[91584:6694163] [BoringSSL] Function boringssl_context_get_peer_sct_list: line 1754 received sct extension length is less than sct data length
  Error jsonErr dataCorrupted(Swift.DecodingError.Context(codingPath: [PlayerRankDOTA2.PlayerStatsParent.(CodingKeys in _053A446F694D6B16CE13A0E302B3B14A).rankings, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), PlayerRankDOTA2.PlayerStats.(CodingKeys in _053A446F694D6B16CE13A0E302B3B14A).score], debugDescription: "Parsed JSON number <3099.96838722024> does not fit in Int.", underlyingError: nil))"

```<code>import UIKit

struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
    let personaname: String
    let score: Int
    let solo_competitive_rank: Int
    let avatar: String
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrlString = "https://api.opendota.com/api/rankings"
        guard let url = URL(string: jsonUrlString) else {return}
        URLSession.shared.dataTask(with: url) { (data, response, error)  in
            guard let data = data else {return}
            //let dataAsString = String(data: data, encoding: .utf8)
            //print(dataAsString)
            do{
                let playerStatsParent = try JSONDecoder().decode(PlayerStatsParent.self, from: data)
                print(playerStatsParent.rankings)
            } catch let jsonErr {
                print("Error jsonErr", jsonErr)
            }
        }.resume()
    }

    let jsonUrlString = "https://api.opendota.com/api/rankings"

}
</code>```

答:
You have to make several changes to your PlayerStats. First of all, score has to be Double, since that's the format the API is returning. Secondly, all values can be null in the JSON response. One way to tackle this issue is to define all properties as optionals.

```<code>struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}
</code>```

After changing your PlayerStats struct to the above format, the decoding works just fine.

Title: Nested JSON Feed Returns Error

Body:
I'm new to JSON feeds and swift 4 in general. I'm having trouble printing data from a nested JSON feed. First off, I'm unsure if I'm calling the array properly in my do statement. Second, when I build the app, I get the following long error. Could anyone help me decipher this? My code is at the bottom of the post. Thank you in advance.

2017-12-06 12:58:48.604154-0500 PlayerRankDOTA2[91584:6694163] [BoringSSL] Function boringssl_context_get_peer_sct_list: line 1754 received sct extension length is less than sct data length
  Error jsonErr dataCorrupted(Swift.DecodingError.Context(codingPath: [PlayerRankDOTA2.PlayerStatsParent.(CodingKeys in _053A446F694D6B16CE13A0E302B3B14A).rankings, Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 0", intValue: Optional(0)), PlayerRankDOTA2.PlayerStats.(CodingKeys in _053A446F694D6B16CE13A0E302B3B14A).score], debugDescription: "Parsed JSON number <3099.96838722024> does not fit in Int.", underlyingError: nil))"

import UIKit

struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
    let personaname: String
    let score: Int
    let solo_competitive_rank: Int
    let avatar: String
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let jsonUrlString = "https://api.opendota.com/api/rankings"
        guard let url = URL(string: jsonUrlString) else {return}
        URLSession.shared.dataTask(with: url) { (data, response, error)  in
            guard let data = data else {return}
            //let dataAsString = String(data: data, encoding: .utf8)
            //print(dataAsString)
            do{
                let playerStatsParent = try JSONDecoder().decode(PlayerStatsParent.self, from: data)
                print(playerStatsParent.rankings)
            } catch let jsonErr {
                print("Error jsonErr", jsonErr)
            }
        }.resume()
    }

    let jsonUrlString = "https://api.opendota.com/api/rankings"

}

Body:
You have to make several changes to your PlayerStats. First of all, score has to be Double, since that's the format the API is returning. Secondly, all values can be null in the JSON response. One way to tackle this issue is to define all properties as optionals.

struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}

After changing your PlayerStats struct to the above format, the decoding works just fine.


问:
Keycloak retrieve custom attributes to KeycloakPrincipal
In my rest service i can obtain the principal information after authentication using

```<code>KeycloakPrincipal kcPrincipal = (KeycloakPrincipal) servletRequest.getUserPrincipal();
</code>```

statement.

Keycloak principal doesn't contain all the information i need about the authenticated user.
Is it possible to customize my own principal type?
On the keycloak-server-end I've developed a user federation provider. I saw that UserModel makes possible to add a set of custom attributes to my user.

Is it possible to insert my custom principal in that code?

Is it possible to retrieve this attributes from keycloak principal?

What is the way?

答:
Select Users > Lookup > click on ID > go to attributes tab > Add attribute > e.g.: phone > Save

Select Clients > click on Client ID > go to Mappers Tab > create mapper

Get custom attributes

UPDATE

Add 'phone' attribute on Group level, assign user to that group, and you get 'phone' attribute from group level for all users

Go back to mapper and update 'phone' with 'Aggregate attribute values = true' and 'Multivalued=true', and you get 'phone' as list with both attributes from group and user level. If you keep 'Aggregate attribute values = false' or 'Multivalued=false', you get just one value, where 'phone' attribute from user will override 'phone' attribute from group (which make sense)

ContentLicense: CC BY-SA 4.0

Body:
In my rest service i can obtain the principal information after authentication using

KeycloakPrincipal kcPrincipal = (KeycloakPrincipal) servletRequest.getUserPrincipal();

statement.

Keycloak principal doesn't contain all the information i need about the authenticated user.
Is it possible to customize my own principal type?
On the keycloak-server-end I've developed a user federation provider. I saw that UserModel makes possible to add a set of custom attributes to my user.

Is it possible to insert my custom principal in that code?

Is it possible to retrieve this attributes from keycloak principal?

What is the way?


问:
Intellij does not support sass variables inside a CSS3 calc( function
I have the following sass code in a .scss file which works perfectly.

```<code>$headerHeight: 90px;

.basePageContent {
  height: calc(100% - $headerHeight);
  width: 100%;
  position: absolute;
  top: $headerHeight;
  bottom: 0;
  display: block;
}
</code>```

But Intellij shows it as invalid code.  Could this be an invalid setting on my IDE or is Intellij wrong?

I am on the following build

IntelliJ IDEA 2017.3 (Ultimate Edition) Build #IU-173.3727.127, built
  on November 27, 2017 JRE: 1.8.0_152-release-1024-b6 x86_64 JVM:
  OpenJDK 64-Bit Server VM by JetBrains s.r.o Mac OS X 10.13.1

答:
IDE works fine. Read about interpolation.</p>

```<code>$headerHeight: 90px;

.basePageContent {
  height: calc(100% - #{$headerHeight});
  width: 100%;
  position: absolute;
  top: $headerHeight;
  bottom: 0;
  display: block;
}
</code>```

Body:
I have the following sass code in a .scss file which works perfectly.

$headerHeight: 90px;

.basePageContent {
  height: calc(100% - $headerHeight);
  width: 100%;
  position: absolute;
  top: $headerHeight;
  bottom: 0;
  display: block;
}

But Intellij shows it as invalid code.  Could this be an invalid setting on my IDE or is Intellij wrong?

I am on the following build

IntelliJ IDEA 2017.3 (Ultimate Edition) Build #IU-173.3727.127, built
  on November 27, 2017 JRE: 1.8.0_152-release-1024-b6 x86_64 JVM:
  OpenJDK 64-Bit Server VM by JetBrains s.r.o Mac OS X 10.13.1

Body:
IDE works fine. Read about interpolation.

$headerHeight: 90px;

.basePageContent {
  height: calc(100% - #{$headerHeight});
  width: 100%;
  position: absolute;
  top: $headerHeight;
  bottom: 0;
  display: block;
}


问:
How to trigger Jenkins builds for PR for a specific fork in Bitbucket
We have a "blessed" repository, and every team forks this repository with auto-sync enabled (blessed -> fork). In their own forked repo, the team creates their feature branches. Then they make a pull request towards the main branch on the blessed repository.
Because of the auto-sync, they cannot change the pipeline configuration in their own repo.
We would like Jenkins to limit the pull request discovery to pull requests originating from only one fork of one team.
How can we do this.

答:
Forks are effectively separate repositories - they have different paths, different ownership, and different permissions, even though they have some shared code history.

If you're having Bitbucket send webhooks to Jenkins to trigger builds, then remove that configuration for any fork that should not have it. If you're having Jenkins poll for updates, then update Jenkins so that it only polls on the fork(s) that should build through Jenkins. And if you're moving to Pipelines, then the Pipelines YAML is distinct for each fork.


问:
Unable to get the indented out put from the python program
I am writing a script that capture the traffic of an given interface. But while executing the program, i just getting the message says:

```<code>"Process finished with exit code 0"
</code>```

Please note below my code:

```<code>import socket
from struct import *
import datetime
import pcapy
import sys

def main(argv):
    devices = pcapy.findalldevs()
    print (devices)

    for d in devices:
        print "Available devices are ", d

    #Device to be sniffed

    input_dev = raw_input("Enter deice name to sniff")

    print "Following device would be printed", input_dev

    #open
    #device
    # Arguments here are:
    #   device
    #   snaplen (maximum number of bytes to capture _per_packet_)
    #   promiscious mode (1 for true)
    #   timeout (in milliseconds)

    cap = pcapy.open_live(input_dev,65536,1,0)

    #Interating all packets captured in to a variable
    while(1):
        (header, packet) = cap.next()
        parse_packet(packet)

        #Convert a string of 6 characters of ethernet address into a dash separated hex string
    def  eth_addr(a):
        b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]), ord(a[1]), ord(a[2]), ord(a[3]), ord(a[4]), ord(a[5]))

    # Parsing captured packets

    def parse_packet(packet):

        eth_length = 14

        # Get the protocol used from the captured packet
        eth_header = packet[:eth_length]
        eth = unpack('!6s6sH', eth_header)
        eth_protocol = socket.ntohs(eth[2])
        print 'Destination MAC : ' + eth_addr(packet[0:6])+'Source MAC: ' + eth_addr(packet[0:12]) + 'Protocol: ' +str(eth_protocol)

        # Parse the IP packet
        #
        if eth_protocol == 8:
         #Parse IP header
        #take first 20 characters for the ip header
           ip_header = packet[eth_length:20+eth_length]

        #Now unpack them
        iph = unpack('!BBHHHBBH4s4s', ip_header)
        version_ihl = iph[0]
        version = version_ihl >> 4
        ihl = version_ihl & oxf # need to know what is the oxf
        iph_length = ihl * 4

        ttl = iph[5]
        print "ttl value is = ", str(ttl)

        protocol =  ip[6]
        print "protocol = ", str(protocol)

        s_addr = socket.inet_ntoa(iph[8]);
        print "source address = ", str(s_addr)

        d_address = socket.inet_ntoa(iph[9])
        print "Destination address = ", str(d_address)

        #Parsing TCP header

        if protocol == 6:

            #if protocol = 6, it would be TCP
            t = iph_length + eth_length
            tcp_heder = packet

            #Unpack the packet
            tcph = unpack('!HHLLBBHHH', tcp_heder)

            source_port = tcph[0]
            print "Source port =", source_port

            dst_port = tcph[1]
            print "Dst port =", dst_port

            ack_no = tcph[3]
            print "ack_No = ", ack_no

            doff_deserverved = tcph[4]
            print "doff_deserved = ", doff_deserverved
            tcp_length = doff_deserverved >> 4

            h_size = eth_length + iph_length + tcp_length * 4
            data_size = len(packet) - h_size

            #get the data from the packet
            data = packet[data_size:]
            print "Data is = ", data

        elif protocol == 1:
            u = iph_length + eth_length
            icmp_length = 4
            icmp_header= packet[u:u+4]

            #Now unpack them
            icmp = unpack('!BBH' , icmp_header)

            icmp_type = icmp[0]
            print "Type is = ", icmp

            code = icmp[1]
            print "Code is = ", code

            checkSum = icmp[3]
            print "Check sum is ", checkSum

            h_size = eth_length + iph_length + icmp_length
            data_sze = len(packet)- h_size
            print "Data size = ", data_size

            #Get Data from the packet
            data2 = packet[h_size:]
            print "Data is = ", data2

         #Parsing UDP packet
        elif protocol == 17:
            u = iph_length + eth_length
            udph_leungth = 8
            udp_header = packet[u:u+8]

            #Now unpack them
            udp_packet = unpack('!HHHH', udp_header)

            s_port = udp_packet[0]
            print "Source Port = ", s_port

            d_port = udp_packet[1]
            print "Udp Packet = ", d_port

            lenth_of_packet = udp_packet[2]
            print "Length of packet = ", lenth_of_packet

            check_sum = udp_packet[3]
            print "check sum is ", check_sum

            h_size_of_packet = eth_length + iph_length + udph_leungth

            actaul_size = len(packet) - h_size_of_packet

            #Retrieving data packet from the size

            data = packet[h_size_of_packet]

            print "Actual Data = ", data

            #IF there any other some protocol
        else:
            print "Protol other than TCP/UDP/ICMP"

    main(sys.argv)
</code>```

Please let me know what would be the reason for not producing the indented out put or any other ways to get the same.

答:
There are multiple indentation problems in your code.
I suggest you revisit your code.</p>

OwnerDisplayName: umesh

Body:
I am writing a script that capture the traffic of an given interface. But while executing the program, i just getting the message says:

"Process finished with exit code 0"

Please note below my code:

import socket
from struct import *
import datetime
import pcapy
import sys

def main(argv):
    devices = pcapy.findalldevs()
    print (devices)

    for d in devices:
        print "Available devices are ", d

    #Device to be sniffed

    input_dev = raw_input("Enter deice name to sniff")

    print "Following device would be printed", input_dev

    #open
    #device
    # Arguments here are:
    #   device
    #   snaplen (maximum number of bytes to capture _per_packet_)
    #   promiscious mode (1 for true)
    #   timeout (in milliseconds)

    cap = pcapy.open_live(input_dev,65536,1,0)

    #Interating all packets captured in to a variable
    while(1):
        (header, packet) = cap.next()
        parse_packet(packet)

        #Convert a string of 6 characters of ethernet address into a dash separated hex string
    def  eth_addr(a):
        b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]), ord(a[1]), ord(a[2]), ord(a[3]), ord(a[4]), ord(a[5]))

    # Parsing captured packets

    def parse_packet(packet):

        eth_length = 14

        # Get the protocol used from the captured packet
        eth_header = packet[:eth_length]
        eth = unpack('!6s6sH', eth_header)
        eth_protocol = socket.ntohs(eth[2])
        print 'Destination MAC : ' + eth_addr(packet[0:6])+'Source MAC: ' + eth_addr(packet[0:12]) + 'Protocol: ' +str(eth_protocol)

        # Parse the IP packet
        #
        if eth_protocol == 8:
         #Parse IP header
        #take first 20 characters for the ip header
           ip_header = packet[eth_length:20+eth_length]

        #Now unpack them
        iph = unpack('!BBHHHBBH4s4s', ip_header)
        version_ihl = iph[0]
        version = version_ihl >> 4
        ihl = version_ihl & oxf # need to know what is the oxf
        iph_length = ihl * 4

        ttl = iph[5]
        print "ttl value is = ", str(ttl)

        protocol =  ip[6]
        print "protocol = ", str(protocol)

        s_addr = socket.inet_ntoa(iph[8]);
        print "source address = ", str(s_addr)

        d_address = socket.inet_ntoa(iph[9])
        print "Destination address = ", str(d_address)

        #Parsing TCP header

        if protocol == 6:

            #if protocol = 6, it would be TCP
            t = iph_length + eth_length
            tcp_heder = packet

            #Unpack the packet
            tcph = unpack('!HHLLBBHHH', tcp_heder)

            source_port = tcph[0]
            print "Source port =", source_port

            dst_port = tcph[1]
            print "Dst port =", dst_port

            ack_no = tcph[3]
            print "ack_No = ", ack_no

            doff_deserverved = tcph[4]
            print "doff_deserved = ", doff_deserverved
            tcp_length = doff_deserverved >> 4

            h_size = eth_length + iph_length + tcp_length * 4
            data_size = len(packet) - h_size

            #get the data from the packet
            data = packet[data_size:]
            print "Data is = ", data

        elif protocol == 1:
            u = iph_length + eth_length
            icmp_length = 4
            icmp_header= packet[u:u+4]

            #Now unpack them
            icmp = unpack('!BBH' , icmp_header)

            icmp_type = icmp[0]
            print "Type is = ", icmp

            code = icmp[1]
            print "Code is = ", code

            checkSum = icmp[3]
            print "Check sum is ", checkSum

            h_size = eth_length + iph_length + icmp_length
            data_sze = len(packet)- h_size
            print "Data size = ", data_size

            #Get Data from the packet
            data2 = packet[h_size:]
            print "Data is = ", data2

         #Parsing UDP packet
        elif protocol == 17:
            u = iph_length + eth_length
            udph_leungth = 8
            udp_header = packet[u:u+8]

            #Now unpack them
            udp_packet = unpack('!HHHH', udp_header)

            s_port = udp_packet[0]
            print "Source Port = ", s_port

            d_port = udp_packet[1]
            print "Udp Packet = ", d_port

            lenth_of_packet = udp_packet[2]
            print "Length of packet = ", lenth_of_packet

            check_sum = udp_packet[3]
            print "check sum is ", check_sum

            h_size_of_packet = eth_length + iph_length + udph_leungth

            actaul_size = len(packet) - h_size_of_packet

            #Retrieving data packet from the size

            data = packet[h_size_of_packet]

            print "Actual Data = ", data

            #IF there any other some protocol
        else:
            print "Protol other than TCP/UDP/ICMP"

    main(sys.argv)

Please let me know what would be the reason for not producing the indented out put or any other ways to get the same.


问:
Why do I get a castError when I try to push an object to an array in MongoDB and Nodejs?
I have a mongoDB and I am trying to make a Nodejs server to manipulate the data in the database. I get a castError when I try to push a Comment to the Comments array in a BlogPost object.

Source code below, please tell me if you're missing important information.
Thanks in advance!

The route:

```<code>routes.post('/comments/push/:id', function(req, res) {
const blogPostId = req.param('id');
const commentProps = req.body;

BlogPost.findById(blogPostId)
  .then((blogPost) => {
    blogPost.comments.push(commentProps);
    return blogPost.save();
  })
    .then((blogPost) => res.status(200).json({
    'status': 'Comment is deleted.',
    'comment': blogPost
}))
.catch((error) => res.status(400).json(error)) });
</code>```

The BlogPost schema:

```<code>const BlogPostSchema = new Schema({
content: {
type: String,
validate: {
  validator: (content) => content.length > 5,
  message: 'Content must contain at least 6 characters.'
},
required: [true, 'Content must be filled in.']
},
rating: Number,
user: { type: Schema.Types.ObjectId, ref: 'user' },
board: {type: Schema.Types.ObjectId, ref: 'board'},
comments: [{
  type: Schema.Types.ObjectId,
  ref: 'comment'
  }]
});
</code>```

The Comment schema:

```<code>const CommentSchema = new Schema({
content: {
type: String,
validate: {
  validator: (content) => content.length > 5,
  message: 'Content must contain at least 6 characters.'
},
required: [true, 'Content must be filled in.']
},
user: { type: Schema.Types.ObjectId, ref: 'user' },
rating: Number

// board: Board
});
</code>```

Here is the error in postman:
postman screen

Help would be greatly appreciated!

答:
first make sure what's you are receiving in req.body, it's not good
to store directly from req.body.

second ref. comments Schema aspect a objectId while req.body is
Object itself. i'm not sure what are you going to do but it
something like blogPost.comments.push(req.body.someValidId);

third why 2 queries for simple update. you can use $push, $addToSet to push directly to comments or $pull to remove from comments.

```<code>BlogPost.findOneAndUpdate({
    _id:blogPostId
}, {
    $addToSet:{
        comments : someValidId
    }
}, {
    new :true,
    upsert:false
})
.then((blogPost) => {
    res.status(200).json({
        'status': 'Comment is deleted.',
        'comment': blogPost
    })
})
.catch((error) =>
    res.status(400).json(error))
});
</code>```

Body:
I have a mongoDB and I am trying to make a Nodejs server to manipulate the data in the database. I get a castError when I try to push a Comment to the Comments array in a BlogPost object.

Source code below, please tell me if you're missing important information.
Thanks in advance!

The route:

routes.post('/comments/push/:id', function(req, res) {
const blogPostId = req.param('id');
const commentProps = req.body;

BlogPost.findById(blogPostId)
  .then((blogPost) => {
    blogPost.comments.push(commentProps);
    return blogPost.save();
  })
    .then((blogPost) => res.status(200).json({
    'status': 'Comment is deleted.',
    'comment': blogPost
}))
.catch((error) => res.status(400).json(error)) });

The BlogPost schema:

const BlogPostSchema = new Schema({
content: {
type: String,
validate: {
  validator: (content) => content.length > 5,
  message: 'Content must contain at least 6 characters.'
},
required: [true, 'Content must be filled in.']
},
rating: Number,
user: { type: Schema.Types.ObjectId, ref: 'user' },
board: {type: Schema.Types.ObjectId, ref: 'board'},
comments: [{
  type: Schema.Types.ObjectId,
  ref: 'comment'
  }]
});

The Comment schema:

const CommentSchema = new Schema({
content: {
type: String,
validate: {
  validator: (content) => content.length > 5,
  message: 'Content must contain at least 6 characters.'
},
required: [true, 'Content must be filled in.']
},
user: { type: Schema.Types.ObjectId, ref: 'user' },
rating: Number

// board: Board
});

Here is the error in postman:
postman screen

Help would be greatly appreciated!

Body:
first make sure what's you are receiving in req.body, it's not good
to store directly from req.body.

second ref. comments Schema aspect a objectId while req.body is
Object itself. i'm not sure what are you going to do but it
something like blogPost.comments.push(req.body.someValidId);

third why 2 queries for simple update. you can use $push, $addToSet to push directly to comments or $pull to remove from comments.

BlogPost.findOneAndUpdate({
    _id:blogPostId
}, {
    $addToSet:{
        comments : someValidId
    }
}, {
    new :true,
    upsert:false
})
.then((blogPost) => {
    res.status(200).json({
        'status': 'Comment is deleted.',
        'comment': blogPost
    })
})
.catch((error) =>
    res.status(400).json(error))
});


问:
need to be able to add strings (paths) to an XML file using shell script
I need to be able to add strings (paths) to an XML file using shell script,
This is the XML that I have:

```<code><?xml version="1.0" encoding="utf-8" standalone="no"?>
<configurations>
    <smtpHost>smtp3.gmail.com</smtpHost>
    <smtpPort>25</smtpPort>
    <emailFrom>GitPushNotifier@gmail.com</emailFrom>
    <emailSubject>Push notification</emailSubject>
    <!-- Stash general URL-->
    <gitViewerURL>http://server0005.gmail.net:7990/projects/</gitViewerURL>
    <rule>
        <name>test_12.55.4</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.4</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.10</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.10</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.6</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.6</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
</configurations>
</code>```

And I need to add additional path to the  subnode only for one version (let's say for test_12.55.10), The path's I want to add are:

Server/./resources/schema/v12_55_10/./.-dbSchemaDescriptor.xml,
Server/./resources/SpringIOC/dataupgrader/v12_55_10/./.-dataUpgrader.xml,
Server/./java/com/hp/mqm/dataupgrader/v12_55_10/./..java,
Server/./resources/indexes/v12_55_10/.*.index

I want to use sed or "xmlstarlet" as I saw other people suggested,
So the output that I want to get is:

```<code><path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml,Server/.*/resources/schema/v12_55_10/.*/.*-dbSchemaDescriptor\.xml,
Server/.*/resources/SpringIOC/dataupgrader/v12_55_10/.*/.*-dataUpgrader\.xml,
Server/.*/java/com/hp/mqm/dataupgrader/v12_55_10/.*/.*\.java,
Server/.*/resources/indexes/v12_55_10/.*\.index</path>
</code>```

答:
Here's one way you could do it with xmlstarlet like you originally requested...

```<code>name="test_12.55.10"
path=", Server/./resources/schema/v12_55_10/./.-dbSchemaDescriptor.xml, Server/./resources/SpringIOC/dataupgrader/v12_55_10/./.-dataUpgrader.xml, Server/./java/com/hp/mqm/dataupgrader/v12_55_10/./..java, Server/./resources/indexes/v12_55_10/.*.index"

xmlstarlet ed -L -a "/*/rule[name='$name']/path/text()" --type text -n "" -v "$path" input.xml
</code>```

Caution: This will modify the file in place. (because of -L)

This could be a one-liner if you didn't use the variables.

Body:
I need to be able to add strings (paths) to an XML file using shell script,
This is the XML that I have:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<configurations>
    <smtpHost>smtp3.gmail.com</smtpHost>
    <smtpPort>25</smtpPort>
    <emailFrom>GitPushNotifier@gmail.com</emailFrom>
    <emailSubject>Push notification</emailSubject>

    <gitViewerURL>http://server0005.gmail.net:7990/projects/</gitViewerURL>
    <rule>
        <name>test_12.55.4</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.4</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.10</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.10</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
    <rule>
        <name>test_12.55.6</name>
        <repo>test</repo>
        <branch>refs/heads/12.55.6</branch>
        <emailTo>test@gmail.com</emailTo>
        <path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml</path>
    </rule>
</configurations>

And I need to add additional path to the  subnode only for one version (let's say for test_12.55.10), The path's I want to add are:

Server/./resources/schema/v12_55_10/./.-dbSchemaDescriptor.xml,
Server/./resources/SpringIOC/dataupgrader/v12_55_10/./.-dataUpgrader.xml,
Server/./java/com/hp/mqm/dataupgrader/v12_55_10/./..java,
Server/./resources/indexes/v12_55_10/.*.index

I want to use sed or "xmlstarlet" as I saw other people suggested,
So the output that I want to get is:

<path>Server/.*/resources/schema/v.*/.*/.*-dbSchemaDescriptor\.xml,Server/.*/resources/SpringIOC/dataupgrader/v.*/.*/.*-dataUpgrader\.xml,Server/.*/java/com/hp/test/dataupgrader/v.*/.*/.*\.java,Server/.*/resources/indexes/v.*/.*\.index,Server/.*/resources/SpringIOC/vanilla/.*\.xml,Server/.*/resources/schema/v12_55_10/.*/.*-dbSchemaDescriptor\.xml,
Server/.*/resources/SpringIOC/dataupgrader/v12_55_10/.*/.*-dataUpgrader\.xml,
Server/.*/java/com/hp/mqm/dataupgrader/v12_55_10/.*/.*\.java,
Server/.*/resources/indexes/v12_55_10/.*\.index</path>

Body:
Here's one way you could do it with xmlstarlet like you originally requested...

name="test_12.55.10"
path=", Server/./resources/schema/v12_55_10/./.-dbSchemaDescriptor.xml, Server/./resources/SpringIOC/dataupgrader/v12_55_10/./.-dataUpgrader.xml, Server/./java/com/hp/mqm/dataupgrader/v12_55_10/./..java, Server/./resources/indexes/v12_55_10/.*.index"

xmlstarlet ed -L -a "/*/rule[name='$name']/path/text()" --type text -n "" -v "$path" input.xml

Caution: This will modify the file in place. (because of -L)

This could be a one-liner if you didn't use the variables.


问:
Can't access Gmail Drafts via Gmail Add-ons
I am trying to access all the drafts in Gmail using Gmail Add-ons, but it logs error like this
    Access denied: : Missing access token for per message scope authorization. [line: 8, function: buildAddon, file: Code]

My onTrigger function looks like this

```<code>function buildAddon(e) {
var cards = [];
var accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);

var draftMessages = GmailApp.getDraftMessages();
for (var i = 0; i < draftMessages.length; i++) {
    cards.push(CardService.newCardBuilder()
        .setHeader(CardService.newCardHeader()
            .setTitle(draftMessages[i].getBody())).build());
}
return cards;
}
</code>```

And the manifest json file looks like this

```<code>{
"oauthScopes": [
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.addons.execute",
    "https://www.googleapis.com/auth/gmail.addons.current.message.action",
    "https://www.googleapis.com/auth/gmail.addons.current.message.metadata",
    "https://www.googleapis.com/auth/gmail.addons.current.message.readonly",
    "https://www.googleapis.com/auth/gmail.addons.current.action.compose"
],
"gmail": {
    "contextualTriggers": [
        {
            "unconditional": {},
            "onTriggerFunction": "buildAddon"
        }
    ],
    "logoUrl": "https://www.gstatic.com/images/icons/material/system/2x/bookmark_black_24dp.png",
    "name": "Draft reminder",
    "version": "TRUSTED_TESTER_V2"
}
}
</code>```

答:
You’re missing the scope for drafts permission.

“https://www.googleapis.com/auth/gmail.compose
Manage drafts and send email”

Here is the reference for scopes:
https://developers.google.com/identity/protocols/googlescopes#gmailv1

Body:
I am trying to access all the drafts in Gmail using Gmail Add-ons, but it logs error like this
    Access denied: : Missing access token for per message scope authorization. [line: 8, function: buildAddon, file: Code]

My onTrigger function looks like this

function buildAddon(e) {
var cards = [];
var accessToken = e.messageMetadata.accessToken;
GmailApp.setCurrentMessageAccessToken(accessToken);

var draftMessages = GmailApp.getDraftMessages();
for (var i = 0; i < draftMessages.length; i++) {
    cards.push(CardService.newCardBuilder()
        .setHeader(CardService.newCardHeader()
            .setTitle(draftMessages[i].getBody())).build());
}
return cards;
}

And the manifest json file looks like this

{
"oauthScopes": [
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://www.googleapis.com/auth/gmail.addons.execute",
    "https://www.googleapis.com/auth/gmail.addons.current.message.action",
    "https://www.googleapis.com/auth/gmail.addons.current.message.metadata",
    "https://www.googleapis.com/auth/gmail.addons.current.message.readonly",
    "https://www.googleapis.com/auth/gmail.addons.current.action.compose"
],
"gmail": {
    "contextualTriggers": [
        {
            "unconditional": {},
            "onTriggerFunction": "buildAddon"
        }
    ],
    "logoUrl": "https://www.gstatic.com/images/icons/material/system/2x/bookmark_black_24dp.png",
    "name": "Draft reminder",
    "version": "TRUSTED_TESTER_V2"
}
}


问:
How to add authorisation logic to the base topic in a Phoenix Channel so that all subtopics gets the same logic
My user_socket have

```<code>defmodule MyappServerWeb.UserSocket do
  use Phoenix.Socket

  ## Channels
  channel "public:login", MyappServerWeb.LoginChannel

  channel "admin:navbar", MyappServerWeb.AdminNavbarChannel
  channel "admin:dash", MyappServerWeb.AdminDashChannel
  channel "admin:user", MyappServerWeb.UserChannel
end
</code>```

Here i have to implement two authorization level, ie, public and admin. All subtopics under these two topic must inherit the same authorization logic i set to the parent topic. How to achieve this? or Am i doing anything wrong? (really new to functional programming)

答:
The common approach to share the logic between different modules would be to use __using__/1 callback from calls to Kernel.use/2.

```<code>defmodule SharedLogic do
  defmacro __using__(opts \\ []) do
    quote do
      defdelegate login(user), to: SharedLogic
      def logged?(user), do: SOME CODE
    end
  end

  def login(user) do
    SOME LOGIC
  end
end
</code>```

And now in your implementations you just do:

```<code>defmodule Admin do
  use SharedLogic
end
</code>```

The above will add login/1 and logged/1 functions to Admin module. Your code already uses this technique for Phoenix.Socket, you might examine it’s code for the inspiration.

I effectively omitted the @behaviour-related stuff, that is usually added to SharedLogic to type-check the modules using SharedLogic, for the sake of simplicity.

More info on Kernel.defdelegate/2.

Body:
My user_socket have

defmodule MyappServerWeb.UserSocket do
  use Phoenix.Socket

  ## Channels
  channel "public:login", MyappServerWeb.LoginChannel

  channel "admin:navbar", MyappServerWeb.AdminNavbarChannel
  channel "admin:dash", MyappServerWeb.AdminDashChannel
  channel "admin:user", MyappServerWeb.UserChannel
end

Here i have to implement two authorization level, ie, public and admin. All subtopics under these two topic must inherit the same authorization logic i set to the parent topic. How to achieve this? or Am i doing anything wrong? (really new to functional programming)

Body:
The common approach to share the logic between different modules would be to use __using__/1 callback from calls to Kernel.use/2.

defmodule SharedLogic do
  defmacro __using__(opts \\ []) do
    quote do
      defdelegate login(user), to: SharedLogic
      def logged?(user), do: SOME CODE
    end
  end

  def login(user) do
    SOME LOGIC
  end
end

And now in your implementations you just do:

defmodule Admin do
  use SharedLogic
end

The above will add login/1 and logged/1 functions to Admin module. Your code already uses this technique for Phoenix.Socket, you might examine it’s code for the inspiration.

I effectively omitted the @behaviour-related stuff, that is usually added to SharedLogic to type-check the modules using SharedLogic, for the sake of simplicity.

More info on Kernel.defdelegate/2.


问:
Swift: NSCoding Implementation For An Object Without Instance Variables
Case in point: Beginner here please bear with me. I just learnt how to persist objects by encoding/decoding & archiving/unarchiving. Problem is now I want to persist a single UIImage. What is the recommended way to do that?

My current implementation that works but looks really weird:

```<code>class Photo: NSObject, NSCoding {

    static let documentsDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
    static let archiveURL = documentsDirectory.appendingPathComponent("photo")

    static func saveToDisk(selectedPhoto: UIImage) {
        NSKeyedArchiver.archiveRootObject(selectedPhoto, toFile: archiveURL.path)
    }

    static func loadFromDisk() -> UIImage? {
        guard let unarchivedPhoto = NSKeyedUnarchiver.unarchiveObject(withFile: archiveURL.path) as? UIImage
            else {return nil}
        return unarchivedPhoto
    }

    func encode(with aCoder: NSCoder) {
    }

    convenience required init?(coder aDecoder: NSCoder) {
        self.init()
    }
}
</code>```

Is there a better way to do it? Many thanks.

答:
Hope this helps

Please add correct file url in place of "filename"

```<code>func convertImageToDataAndWrite()
{
    let img:UIImage = UIImage(named: "img1.png")!
    let data:NSData? = UIImageJPEGRepresentation(img, 0.7)
    if data != nil
    {
        var check:Bool =  NSKeyedArchiver.archiveRootObject(data!, toFile: "filename")

    }

}

func readImagefromFile()
{
    let data:NSData = NSKeyedUnarchiver.unarchiveObjectWithFile("filename") as! NSData!
    var img:UIImage = UIImage(data: data)!

}
</code>```

Thanks.

Body:
Case in point: Beginner here please bear with me. I just learnt how to persist objects by encoding/decoding & archiving/unarchiving. Problem is now I want to persist a single UIImage. What is the recommended way to do that?

My current implementation that works but looks really weird:

class Photo: NSObject, NSCoding {

    static let documentsDirectory = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!
    static let archiveURL = documentsDirectory.appendingPathComponent("photo")

    static func saveToDisk(selectedPhoto: UIImage) {
        NSKeyedArchiver.archiveRootObject(selectedPhoto, toFile: archiveURL.path)
    }

    static func loadFromDisk() -> UIImage? {
        guard let unarchivedPhoto = NSKeyedUnarchiver.unarchiveObject(withFile: archiveURL.path) as? UIImage
            else {return nil}
        return unarchivedPhoto
    }

    func encode(with aCoder: NSCoder) {
    }

    convenience required init?(coder aDecoder: NSCoder) {
        self.init()
    }
}

Is there a better way to do it? Many thanks.

Body:
Hope this helps

Please add correct file url in place of "filename"

func convertImageToDataAndWrite()
{
    let img:UIImage = UIImage(named: "img1.png")!
    let data:NSData? = UIImageJPEGRepresentation(img, 0.7)
    if data != nil
    {
        var check:Bool =  NSKeyedArchiver.archiveRootObject(data!, toFile: "filename")

    }

}

func readImagefromFile()
{
    let data:NSData = NSKeyedUnarchiver.unarchiveObjectWithFile("filename") as! NSData!
    var img:UIImage = UIImage(data: data)!

}

Thanks.


问:
How to center HTML code while using Bootstrap
Part of my code sticks to the left side of the page. I can not figure out a way to put these buttons in the middle of the website. Just trying to make look better if I add center or text block center it does not work it only ads the radio button symbol above the text or it shifts just the symbol to the middle.

```<code>    <div class="jumbotron">
    <h1 class="jumbotron-heading"><center>Bazár Bez Havárie</center></h1>
    <p class="lead text-muted"><center>Vitajte v Bazáry Bez Havárie. Vyberte
    si svoje auto.</center></p><br>
    <h2 class="jumbotron-heading"><center><b>Objednávkový formulár.</b>
    </center></h1><br>
    <form class="form-horizontal" role="form" method="get"
    action="objednavka.php">
    <div class="form-group">
    <label for="name" class="col-sm-2 control-label"><center>Meno</center>
    </label>
    <div class="col-sm-12">
    <input type="text" class="form-control" id="name" name="name"
    placeholder="" value="">
    </div>
    </div>
    <div class="form-group">
    <label for="email" class="col-sm-2 control-label"><center>Email</center>
    </label>
    <div class="col-sm-12">
    <input type="email" class="form-control" id="email" name="email"
    placeholder="" value="">
    </div>
    </div>
    <div class="form-group">
    <label for="adress" class="col-sm-2 control-label">
    <center>Adresa</center></label>
    <div class="col-sm-12">
    <input type="adress" class="form-control" id="address" name="address"
    placeholder="" value="">
    </div>
    </div>

    <h2><b>Auto na vyber</b></h2><br>

   <div class="btn-group" data-toggle="buttons">

   <label class="btn btn-light">
   <input type="radio" name="options" id="option1" value="Ferrari GTC4Lusso"
   autocomplete="off"><center> Ferrari GTC4Lusso </center>
   </label>

   <label class="btn btn-light">
   <input type="radio" name="options" id="option2" value="Porsche Carrera
   GT" autocomplete="off"> <center>Porsche Carrera GT </center>
   </label>

   </div>
   <br><br>
   <h2><b>Farba auta</b></h2><br> <div class="btn-group" data-
   toggle="buttons">
</code>```

Here in the middle

```<code>   <label class="btn btn-sample">
   <label class="btn btn-cierna btn-lg btn-lg">
   <input type="radio" name="tlacidla" id="tlacidla2" value="Čierna"
   autocomplete="off"><center> Čierna </center>
   </label>
   <label class="btn btn-cervena btn-lg btn-lg">
   <input type="radio" name="tlacidla" id="tlacidla3" value="Červená"
    autocomplete="off"><center> Červená </center>
</code>```

Ends here

```<code>   </label>
   </div><br><br>
   <div class="form-group">
</code>```

And this one below too.

```<code>   <input type="submit" name="submit"  value="Potvrdit Objednavku"
    class="btn btn-outline-danger">
    </div>
   </form>
   </div>
</code>```

答:
Hi you can solve it with add simple the center tag before that label. Or of course use CSS to solve it.

 <input type="radio" name="options" id="option1" value="Ferrari  GTC4Lusso"
 autocomplete="off"> Ferrari GTC4Lusso

```

Body:
Part of my code sticks to the left side of the page. I can not figure out a way to put these buttons in the middle of the website. Just trying to make look better if I add center or text block center it does not work it only ads the radio button symbol above the text or it shifts just the symbol to the middle.

Bazár Bez Havárie

Vitajte v Bazáry Bez Havárie. Vyberte
    si svoje auto.

Objednávkový formulár.

    <form class="form-horizontal" role="form" method="get"
    action="objednavka.php">

    Meno

    <input type="text" class="form-control" id="name" name="name"
    placeholder="" value="">

    Email

    <input type="email" class="form-control" id="email" name="email"
    placeholder="" value="">

    Adresa

    <input type="adress" class="form-control" id="address" name="address"
    placeholder="" value="">

Auto na vyber

   <input type="radio" name="options" id="option1" value="Ferrari GTC4Lusso"
   autocomplete="off"> Ferrari GTC4Lusso

   <input type="radio" name="options" id="option2" value="Porsche Carrera
   GT" autocomplete="off"> Porsche Carrera GT

Farba auta

Here in the middle

   <input type="radio" name="tlacidla" id="tlacidla2" value="Čierna"
   autocomplete="off"> Čierna

   <input type="radio" name="tlacidla" id="tlacidla3" value="Červená"
    autocomplete="off"> Červená

Ends here

And this one below too.

   <input type="submit" name="submit"  value="Potvrdit Objednavku"
    class="btn btn-outline-danger">

   </form>

Body:
Hi you can solve it with add simple the center tag before that label. Or of course use CSS to solve it.

<center>
 <label class="btn btn-light">
 <input type="radio" name="options" id="option1" value="Ferrari  GTC4Lusso"
 autocomplete="off"><center> Ferrari GTC4Lusso </center>
 </label>
</center>


问:
Leetcode Add Two Numbers Q: how to create a linkedlist from a number?
In this question: https://leetcode.com/problems/add-two-numbers/description/, I've figured out how to get sum of the digits (i.e. 807), but now I need to convert that number into a linked list (e.g. 7 -> 0 -> 8).

How do I create a linkedlist from a number?

Class function for creating a list node:

```<code>function ListNode(val) {
   this.val = val;
   this.next = null;
}
</code>```

Rest of my code:

```<code>var addTwoNumbers = function(l1, l2) {

    function findVal(linkedList) {
          return linkedList.next == null ? linkedList.val.toString() : linkedList.val.toString() + findVal(linkedList.next);

    }

    var l1num = parseInt(findVal(l1).split('').reverse().join(''));
    var l2num = parseInt(findVal(l2).split('').reverse().join(''));
    var sum = l1num + l2num;

// Create linked list from sum
</code>```

答:
If you turn your number into an array, you can then use the array.prototype.reduce function.

let number = 807;

function ListNode(val) {
  this.val = val;
  this.next = null;
}

// Convert the number into a string and split that into an array of digits
let arr = Array.from(number.toString());

// Iterate through the elements, and create the nodes
let head = arr.reduce((nextNode, curr) => {
  let node = new ListNode(curr);
  node.next = nextNode;
  return node;
}, null);

// Print out the values
let node = head;
while(node) {
  console.log(node.val);
  node = node.next
}```

Body:
In this question: https://leetcode.com/problems/add-two-numbers/description/, I've figured out how to get sum of the digits (i.e. 807), but now I need to convert that number into a linked list (e.g. 7 -> 0 -> 8).

How do I create a linkedlist from a number?

Class function for creating a list node:

function ListNode(val) {
   this.val = val;
   this.next = null;
}

Rest of my code:

var addTwoNumbers = function(l1, l2) {

    function findVal(linkedList) {
          return linkedList.next == null ? linkedList.val.toString() : linkedList.val.toString() + findVal(linkedList.next);

    }

    var l1num = parseInt(findVal(l1).split('').reverse().join(''));
    var l2num = parseInt(findVal(l2).split('').reverse().join(''));
    var sum = l1num + l2num;

// Create linked list from sum


问:
Not matched rows in B join with some row in A
Example data:

```<code>Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A
</code>```

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

```<code>x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1
</code>```

答:
Another way we can do this via a self join and group by on join of two tables like below

```<code>select t1.*,t2.c from Table1 t1 join
(
    select
        a.y,
        sum(case when b.y is null then 0 else 1 end)  as c
    from Table1 a
        full outer join
        Table2 b
    on
        a.y=b.y
    group by a.y
)t2
on ISNULL(t1.y,-1)=ISNULL(t2.y,-1)
</code>```

Working demo

Body:
Example data:

Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1

Body:
Another way we can do this via a self join and group by on join of two tables like below

select t1.*,t2.c from Table1 t1 join
(
    select
        a.y,
        sum(case when b.y is null then 0 else 1 end)  as c
    from Table1 a
        full outer join
        Table2 b
    on
        a.y=b.y
    group by a.y
)t2
on ISNULL(t1.y,-1)=ISNULL(t2.y,-1)

Working demo


问:
Finding every merge/commit in git where a file changed
I have a bunch of work that got "lost" in our git repository.  i.e. I committed a number of files, and someone did a merge somewhere, that "lost" all my changes.  I'm struggling to determine how/where this happened.  When I look at the log of changes to my file using this command from this question:

gitk --all -- version.txt

I get the following screenshot:

This file is managed by our build system, and it should contain the string,

1.0.94.0

AT least, based on what I'm seeing in the above screenshot.  But in fact, it actually contains the string:

1.0.92.0

In digging through the repository, someone performed a merge, and the merge overwrote version.txt with the contents 1.0.92.0.  But that merge did not appear in my gitk output.  Is there a way to run gitk (or git) to show me all the merges and commits that modified my file?

答:
It's worth trying adding --full-history to your gitk command. gitk runs git log (and sometimes git rev-list) with these gitk-controlled options:

```<code># Start off a git log process and arrange to read its output
proc start_rev_list {view} {
    global startmsecs commitidx viewcomplete curview

[mass snippage]

    if {$vcanopt($view)} {
        set revs [parseviewrevs $view $vrevs($view)]
        if {$revs eq {}} {
            return 0
        }
        set args [concat $vflags($view) $revs]
    } else {
        set args $vorigargs($view)
    }

    if {[catch {
        set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
                        --parents --boundary $args "--" $files] r]
    } err]} {
        error_popup "[mc "Error executing git log:"] $err"
        return 0
    }
</code>```

By default, looking at specific files, i.e., when $files is not empty, enables what git log calls History Simplification.  I find the documentation here to be somewhat confusing, but in short, without --full-history, Git will prune some merge parents when the parent contains the file in its current format.

Note that --full-history is not included in the options, but one of them is $args, which is at least sometimes set based on $vflags($view), and $vflags may include --full-history.

If you use git log directly, consider adding both --full-history and -m.  By default, git log does not look at the diffs of merges.  The -m flag causes it to split each merge into one commit-pair per parent (parent-n vs child), and then look at each of those diffs.

I'm not sure if or how this affects gitk since gitk does extra work with git rev-list, but it's possible that adding -m to gitk's options is required as well.

Body:
It's worth trying adding --full-history to your gitk command. gitk runs git log (and sometimes git rev-list) with these gitk-controlled options:

# Start off a git log process and arrange to read its output
proc start_rev_list {view} {
    global startmsecs commitidx viewcomplete curview

[mass snippage]

    if {$vcanopt($view)} {
        set revs [parseviewrevs $view $vrevs($view)]
        if {$revs eq {}} {
            return 0
        }
        set args [concat $vflags($view) $revs]
    } else {
        set args $vorigargs($view)
    }

    if {[catch {
        set fd [open [concat | git log --no-color -z --pretty=raw $show_notes \
                        --parents --boundary $args "--" $files] r]
    } err]} {
        error_popup "[mc "Error executing git log:"] $err"
        return 0
    }

By default, looking at specific files, i.e., when $files is not empty, enables what git log calls History Simplification.  I find the documentation here to be somewhat confusing, but in short, without --full-history, Git will prune some merge parents when the parent contains the file in its current format.

Note that --full-history is not included in the options, but one of them is $args, which is at least sometimes set based on $vflags($view), and $vflags may include --full-history.

If you use git log directly, consider adding both --full-history and -m.  By default, git log does not look at the diffs of merges.  The -m flag causes it to split each merge into one commit-pair per parent (parent-n vs child), and then look at each of those diffs.

I'm not sure if or how this affects gitk since gitk does extra work with git rev-list, but it's possible that adding -m to gitk's options is required as well.


问:
Trying to send checkbox value(s) from form to email in PHP
It has been years since I was in web development but have dabbled in PHP in the past, so I guess you could say I am a newbie at PHP. I am trying to build a simple form for a job application using PHP I want the form to be filled out and then emailed upon submit.

I have researched this site as well as others and am unable to get this to work. I cannot get the job value to show up in email:

Here is my HTML code:

```<code>            <label>Position: check all you are interested in </label><br>
            <input type="checkbox" name="job[]" value="General Pickle Production">General Pickle Production
            <input type="checkbox" name="job[]" value="Fryer">Fryer
            <input type="checkbox" name="job[]" value="Sales">Sales
            <input type="checkbox" name="job[]" value="Manager">Manager
            <input type="checkbox" name="job[]" value="Overnights">Overnights<br>
</code>```

Here is my PHP code:

```<code>    $aJob = $_POST['job'];
     if(empty($aJob))
   {
     echo("You didn't select any job position.");
   }
   else
   {
     $N = count($aJob);

     echo("You selected $N job(s): ");
     for($i=0; $i < $N; $i++)
     {
       echo($aJob[$i] . " ");
     }
   }
</code>```

When I hit submit on the form the above will show each job selected on the form page but I guess I am not sure how to send this to my email upon the submit. Below is the code I have sending the variables to my email:

```<code>    $content = $_POST['name'] . " " . $_POST['lastname'] . " \n";
    $content .= $_POST['address'] . " \n";
    $content .= "Position(s) applied for: " . $_POST['aJob'] . " \n";
</code>```

Do I need to put my for loop in $content section somewhere to display the jobs? I guess I am not sure what that format would look like here?

I appreciate any help you could offer.
Thank you. J

答:
```<code>$content .= "Position(s) applied for: ";
$content .= implode(',' $_POST['aJob']);
</code>```

Body:
It has been years since I was in web development but have dabbled in PHP in the past, so I guess you could say I am a newbie at PHP. I am trying to build a simple form for a job application using PHP I want the form to be filled out and then emailed upon submit.

I have researched this site as well as others and am unable to get this to work. I cannot get the job value to show up in email:

Here is my HTML code:

            Position: check all you are interested in

            <input type="checkbox" name="job[]" value="General Pickle Production">General Pickle Production
            <input type="checkbox" name="job[]" value="Fryer">Fryer
            <input type="checkbox" name="job[]" value="Sales">Sales
            <input type="checkbox" name="job[]" value="Manager">Manager
            <input type="checkbox" name="job[]" value="Overnights">Overnights

Here is my PHP code:

    $aJob = $_POST['job'];
     if(empty($aJob))
   {
     echo("You didn't select any job position.");
   }
   else
   {
     $N = count($aJob);

     echo("You selected $N job(s): ");
     for($i=0; $i < $N; $i++)
     {
       echo($aJob[$i] . " ");
     }
   }

When I hit submit on the form the above will show each job selected on the form page but I guess I am not sure how to send this to my email upon the submit. Below is the code I have sending the variables to my email:

    $content = $_POST['name'] . " " . $_POST['lastname'] . " \n";
    $content .= $_POST['address'] . " \n";
    $content .= "Position(s) applied for: " . $_POST['aJob'] . " \n";

Do I need to put my for loop in $content section somewhere to display the jobs? I guess I am not sure what that format would look like here?

I appreciate any help you could offer.
Thank you. J


问:
Where can I find listings of "taken" identifiers in standard libraries
With the large size of current C/C++ libraries like STL, Win32, Boost, posix etc. the question of what identifiers are problematic arises. Even with namespaces it is nice to be able to select identifiers which don't clash with the most used identifiers of other libraries when desiging a new library designed to work togheter with existing ones.

At least for the C++ standard libraries (including 0x) there should be listings available. It would be reasonable to think that someone has done a tool for this purpose, which reads a set of header files and creates a list of all names ordered by namespace. Anyone who knows of such a tool? The tool should preferably read all headers in a directory tree rather than only those #included by a particular cpp file.

答:
Even with namespaces it is nice to be able to select identifiers which don't clash with the most used identifiers of other libraries when desiging a new library designed to work togheter with existing ones.

I realize that quite a few libraries do that but this attempt is fundamentally misguided.

Don’t design your identifiers so that they don’t clash, design them so that they are clear, short, and descriptive. These should be the only criteria.

Identifier clash is a solved problem, thanks to namespaces. Properly used, name clash simply doesn’t arise.

ContentLicense: CC BY-SA 2.5


问:
Accessing constants from within a class
I seem to be having an issue accessing class constants.  I have a config class that defines some constants

```<code><?php

class Config
{
   //define my constants
   const DB_HOST = "127.0.0.1";
}
</code>```

I then have an application class which should use these constants

```<code>class Application {

    /** @var Config **/
    private $config;

    public function __construct(Config $config) {
        $this->config = $config;
    }

    public function execute() {
        $this->transferFile($this->obtainTextFile());
    }

    private function obtainTextFile() {
        //connect to database and write results to text file

        return $textFile;  //path to the generated file
    }

    private function transferFile($textFile) {
        //return whether the file was successfully SFTP
    }
}
</code>```

Finally, I have a PHP script file to execute things

```<code><?php

require __DIR__ . "/../config/Config.php";
require __DIR__ . "/../classes/Application.php";

$config = new Config();
$app = new Application($config);
$app->execute();
</code>```

Now within my Application Class, I am trying to access the constants.  If this wasnt a class I would generally do something like this

```<code>$config::DB_HOST
</code>```

Being within a class however, it tells me $config is not defined.  So next logical step would be to do

```<code>$this->config::DB_HOST
</code>```

But then it tells me Uniform variable syntax is available in PHP 7 only.  So, then I tried

```<code>self::DB_HOST
</code>```

But this seems to return nothing.  So how can I access these constants?  Do I need to actually create getters within the Config class to access them?

Any advice appreciated

答:
Constants does not need instance of the class they are part of. Reference it static way, i.e.:

```<code>$foo = Config::DB_HOST;
</code>```

or

```<code>$foo = \Some\Namespace\Stuff\Config::DB_HOST;
</code>```

if needed. But that's basically all you need - make the class reachable (but not the object - it's not needed). See http://php.net/manual/en/language.oop5.constants.php

Then I tried self::DB_HOST

This is only useful if you want to reference the const in the same class. Still it's worth understanding the difference between self:: and static::. See http://php.net/manual/en/language.oop5.late-static-bindings.php

Title: Accessing constants from within a class

Body:
I seem to be having an issue accessing class constants.  I have a config class that defines some constants

<?php

class Config
{
   //define my constants
   const DB_HOST = "127.0.0.1";
}

I then have an application class which should use these constants

class Application {

    /** @var Config **/
    private $config;

    public function __construct(Config $config) {
        $this->config = $config;
    }

    public function execute() {
        $this->transferFile($this->obtainTextFile());
    }

    private function obtainTextFile() {
        //connect to database and write results to text file

        return $textFile;  //path to the generated file
    }

    private function transferFile($textFile) {
        //return whether the file was successfully SFTP
    }
}

Finally, I have a PHP script file to execute things

<?php

require __DIR__ . "/../config/Config.php";
require __DIR__ . "/../classes/Application.php";

$config = new Config();
$app = new Application($config);
$app->execute();

Now within my Application Class, I am trying to access the constants.  If this wasnt a class I would generally do something like this

$config::DB_HOST

Being within a class however, it tells me $config is not defined.  So next logical step would be to do

$this->config::DB_HOST

But then it tells me Uniform variable syntax is available in PHP 7 only.  So, then I tried

self::DB_HOST

But this seems to return nothing.  So how can I access these constants?  Do I need to actually create getters within the Config class to access them?

Any advice appreciated

Body:
Constants does not need instance of the class they are part of. Reference it static way, i.e.:

$foo = Config::DB_HOST;

or

$foo = \Some\Namespace\Stuff\Config::DB_HOST;

if needed. But that's basically all you need - make the class reachable (but not the object - it's not needed). See http://php.net/manual/en/language.oop5.constants.php

Then I tried self::DB_HOST

This is only useful if you want to reference the const in the same class. Still it's worth understanding the difference between self:: and static::. See http://php.net/manual/en/language.oop5.late-static-bindings.php