问:
Need to loop through & modify cells in an Excel sheet... Where do I start?
What I'm working with

I need to modify a file (exported from salesforce) where rows have a unique ID, a name, and a column with the unique ID of another row from this table, identifying it as a "child" of that item.

ID  (columnA)

Name  (columnB)

ParentID  (columnC)

Image of unaffected data:

What I need to accomplish

My goal is to loop through the entire spreadsheet (55,000 rows) and change the ParentID to the value from the parent's Name column.

My pseudo-code solution

```<code>foreach row starting from the top {
    varA = [current row number for this loop];
    varX = [value in varA:columnC];
    if (varX == [regex value]) {
        foreach row starting from the top {
            varB = [current row number for this loop];
            if ([value in varB:columnA] == varX) {
                foreach row starting from the top {
                    varC = [current row number for this loop];
                    if (varC:columnC = varB:columnA) {
                        [varC:columnC] = [varB:columnB];
                    }
                }
                break second foreach loop;
            }
        }
    }
}
</code>```

Image of data after manual fix:

Research I've done so far

I am working with excel, and I found resources discussing how to create a new macro, and some that even have examples, but I'm not confident that's going to be the right place for this. I also have a friend who is suggesting that it would be better to modify the file using Pandas, but that isn't something I'm familiar with either.

My question:

Where do I start? ...What is the proper tool to write a script to modify all of this?

Also, if possible, can you suggest a resource for me to use as reference when using the proper tool for this job?

答:
The following For loop would fix your problem:

```<code>Sub UpdateID()

Dim lastrow As Long
Dim x As Long, y As Long, z As Long
Dim ParentName As String

lastrow = Cells(Rows.Count, "A").End(xlUp).Row

For x = 2 To lastrow
    If Left(Cells(x, 3), 2) = 0 Then
        For y = 2 To lastrow
            If Cells(x, 3).Value = Cells(y, 1).Value Then
            ParentName = Cells(y, 2).Value
            Exit For
            End If
        Next y
    End If

    For z = 2 To lastrow
        If Cells(z, 3).Value <> "" And Cells(x, 3).Value = Cells(z, 3).Value Then
        Cells(z, 3).Value = ParentName
        End If
    Next z
Next x

End Sub
</code>```

Body:
What I'm working with

I need to modify a file (exported from salesforce) where rows have a unique ID, a name, and a column with the unique ID of another row from this table, identifying it as a "child" of that item.

ID  (columnA)

Name  (columnB)

ParentID  (columnC)

Image of unaffected data:

What I need to accomplish

My goal is to loop through the entire spreadsheet (55,000 rows) and change the ParentID to the value from the parent's Name column.

My pseudo-code solution

foreach row starting from the top {
    varA = [current row number for this loop];
    varX = [value in varA:columnC];
    if (varX == [regex value]) {
        foreach row starting from the top {
            varB = [current row number for this loop];
            if ([value in varB:columnA] == varX) {
                foreach row starting from the top {
                    varC = [current row number for this loop];
                    if (varC:columnC = varB:columnA) {
                        [varC:columnC] = [varB:columnB];
                    }
                }
                break second foreach loop;
            }
        }
    }
}

Image of data after manual fix:

Research I've done so far

I am working with excel, and I found resources discussing how to create a new macro, and some that even have examples, but I'm not confident that's going to be the right place for this. I also have a friend who is suggesting that it would be better to modify the file using Pandas, but that isn't something I'm familiar with either.

My question:

Where do I start? ...What is the proper tool to write a script to modify all of this?

Also, if possible, can you suggest a resource for me to use as reference when using the proper tool for this job?

Body:
The following For loop would fix your problem:

Sub UpdateID()

Dim lastrow As Long
Dim x As Long, y As Long, z As Long
Dim ParentName As String

lastrow = Cells(Rows.Count, "A").End(xlUp).Row

For x = 2 To lastrow
    If Left(Cells(x, 3), 2) = 0 Then
        For y = 2 To lastrow
            If Cells(x, 3).Value = Cells(y, 1).Value Then
            ParentName = Cells(y, 2).Value
            Exit For
            End If
        Next y
    End If

    For z = 2 To lastrow
        If Cells(z, 3).Value <> "" And Cells(x, 3).Value = Cells(z, 3).Value Then
        Cells(z, 3).Value = ParentName
        End If
    Next z
Next x

End Sub


来源: stackexchange

问:
to read an array of object in typescript
I am try to read an object from an Array.
pVal is my array of objects.
I need to get the value of "group" depending on value of id.
I want to display, if the id is 1 , it should display "VKC", need help here. </p>

<p>This is code I tried </p>

```<code>this.arr = userData; // -> json
this.pId = this.arr.pId; // value is 1 or 2 or 3

pVal: Array<Object> = [{id:1, group:'VKC'},
{id:2, group:'ABC'},
{id:10, group:'DEF'},
{id:3, group:'GHI'},
{id:5, group:'JKL'},]

alert(this.pVal['1'].group);
this.pInd = this.pVal[this.pId].group;
</code>```

答:
if the id is 1, it should display "VKC"

The rule for what to display is already part of the object. If you only want to display id 1, you can do something like this:

```<code>for(let obj of this.pVal){
   if(obj.id === 1)
      alert(obj.group);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am try to read an object from an Array.
pVal is my array of objects.
I need to get the value of "group" depending on value of id.
I want to display, if the id is 1 , it should display "VKC", need help here.

This is code I tried

this.arr = userData; // -> json
this.pId = this.arr.pId; // value is 1 or 2 or 3

pVal: Array<Object> = [{id:1, group:'VKC'},
{id:2, group:'ABC'},
{id:10, group:'DEF'},
{id:3, group:'GHI'},
{id:5, group:'JKL'},]

alert(this.pVal['1'].group);
this.pInd = this.pVal[this.pId].group;

Body:
if the id is 1, it should display "VKC"

The rule for what to display is already part of the object. If you only want to display id 1, you can do something like this:

for(let obj of this.pVal){
   if(obj.id === 1)
      alert(obj.group);
}


问:
runtime_version versus runtime-version in cloudml-samples/flowers/sample.sh
In Google's sample code found at cloudml-samples/flowers/sample.sh, between lines 52 and 64, is the argument "runtime_version":

```<code># Training on CloudML is quick after preprocessing.  If you ran the above
# commands asynchronously, make sure they have completed before calling this one.
gcloud ml-engine jobs submit training "$JOB_ID" \
  --stream-logs \
  --module-name trainer.task \
  --package-path trainer \
  --staging-bucket "$BUCKET" \
  --region us-central1 \
  --runtime_version=1.0 \
  -- \
  --output_path "${GCS_PATH}/training" \
  --eval_data_paths "${GCS_PATH}/preproc/eval*" \
  --train_data_paths "${GCS_PATH}/preproc/train*"
</code>```

Shouldn't "runtime_version" be replaced with "runtime-version" to avoid an error?

答: Yes. I've submitted a PR (in the future, never hesitate to do so yourself)</p>

Body:
In Google's sample code found at cloudml-samples/flowers/sample.sh, between lines 52 and 64, is the argument "runtime_version":

# Training on CloudML is quick after preprocessing.  If you ran the above
# commands asynchronously, make sure they have completed before calling this one.
gcloud ml-engine jobs submit training "$JOB_ID" \
  --stream-logs \
  --module-name trainer.task \
  --package-path trainer \
  --staging-bucket "$BUCKET" \
  --region us-central1 \
  --runtime_version=1.0 \
  -- \
  --output_path "${GCS_PATH}/training" \
  --eval_data_paths "${GCS_PATH}/preproc/eval*" \
  --train_data_paths "${GCS_PATH}/preproc/train*"

Shouldn't "runtime_version" be replaced with "runtime-version" to avoid an error?


问:
How to switch on System.Type?
In C# 7+, can I switch directly on a System.Type?

When I try:

```<code>    switch (Type)
    {
      case typeof(int):
        break;
    }
</code>```

it tells me that typeof(int) needs to be a constant expression.

Is there some syntatic sugar that allows me to avoid case nameof(int): and directly compare the types for equality? nameof(T) in a case statement is not completely good because namespaces. So although name collision is probably not be applicable for int, it will be applicable for other comparisons.

In other words, I'm trying to be more type-safe than this:

```<code>    switch (Type.Name)
    {
      case nameof(Int32):
      case nameof(Decimal):
        this.value = Math.Max(Math.Min(0, Maximum), Minimum); // enforce minimum
        break;
    }
</code>```

答:
The (already linked) new pattern matching feature allows this.

Ordinarily, you'd switch on a value:

```<code>switch (this.value) {
  case int intValue:
    this.value = Math.Max(Math.Min(intValue, Maximum), Minimum);
    break;
  case decimal decimalValue:
    this.value = Math.Max(Math.Min(decimalValue, Maximum), Minimum);
    break;
}
</code>```

But you can use it to switch on a type, if all you have is a type:

```<code>switch (type) {
  case Type intType when intType == typeof(int):
  case Type decimalType when decimalType == typeof(decimal):
    this.value = Math.Max(Math.Min(this.value, Maximum), Minimum);
    break;
}
</code>```

Note that this is not what the feature is intended for, it becomes less readable than a traditional if...else if...else if...else chain, and the traditional chain is what it compiles to anyway. I do not recommend using pattern matching like this.

ContentLicense: CC BY-SA 4.0

Title: How to switch on System.Type?

Body:
In C# 7+, can I switch directly on a System.Type?

When I try:

    switch (Type)
    {
      case typeof(int):
        break;
    }

it tells me that typeof(int) needs to be a constant expression.

Is there some syntatic sugar that allows me to avoid case nameof(int): and directly compare the types for equality? nameof(T) in a case statement is not completely good because namespaces. So although name collision is probably not be applicable for int, it will be applicable for other comparisons.

In other words, I'm trying to be more type-safe than this:

    switch (Type.Name)
    {
      case nameof(Int32):
      case nameof(Decimal):
        this.value = Math.Max(Math.Min(0, Maximum), Minimum); // enforce minimum
        break;
    }

Body:
The (already linked) new pattern matching feature allows this.

Ordinarily, you'd switch on a value:

switch (this.value) {
  case int intValue:
    this.value = Math.Max(Math.Min(intValue, Maximum), Minimum);
    break;
  case decimal decimalValue:
    this.value = Math.Max(Math.Min(decimalValue, Maximum), Minimum);
    break;
}

But you can use it to switch on a type, if all you have is a type:

switch (type) {
  case Type intType when intType == typeof(int):
  case Type decimalType when decimalType == typeof(decimal):
    this.value = Math.Max(Math.Min(this.value, Maximum), Minimum);
    break;
}

Note that this is not what the feature is intended for, it becomes less readable than a traditional if...else if...else if...else chain, and the traditional chain is what it compiles to anyway. I do not recommend using pattern matching like this.


问:
caching sql result set in java
I know that caching the resultset of frequently used sql statements is better for the performance I am searching about the best way to cache sql result set in java. I found some codes but, it requires adding new jar files to netbeans.
Can anybody help me how can do that without needing to additional apis?</p>

答:
You could make a linked list of results. With the cache trigger pointing to the start of the list. Since linked lists act like a wrapper around whatever you want you can make the results as generic as you want.
 This won't require another api but you will have to implement this all on your own and hopefully you understand why we don't like reinventing the wheel.</p>

ContentLicense: CC BY-SA 2.5

Title: caching sql result set in java


问:
Rotate ImageView using CGAffineTransform and PanGestureRecognizer
I'm trying to rotate an ImageView I have using CGAffineTransform. Basically, what I want to happen is that every time the x-coordinate increases, I want the ImageView to rotate a little more.

I did the math and I want the ImageView to rotate 1.6º every 1 x-coordinate. This is what I have so far in the gesture recognizer function:

```<code>@objc func personDragRecognizer(recognizer: UIPanGestureRecognizer) {

    let rotationAngle: CGFloat = 1.6

    let translation = recognizer.translation(in: rView)
    if let view = recognizer.view {
        view.center = CGPoint(x:view.center.x +  translation.x, y:view.center.y + translation.y)
        view.transform = CGAffineTransform(rotationAngle: rotationAngle)
    }
    recognizer.setTranslation(CGPoint.zero, in: rView)

    if recognizer.view?.center == CGPoint(x: 197.5, y: 232.5)  {
        PlaygroundPage.current.liveView = eeView
    }
</code>```

The problem with this is that it rotates to 576º bc that's 1.6 times 360. And it doesn't keep on rotating it only does it once. I want it to continually rotate.

If anyone could help the help would be immensely appreciated. Thanks so so much in advance!!

Cheers,
Theo

答:
I'm not sure if I fully understood the feature you're trying to implement. Here is a sample for UIView subclass responsible for image rotation.

```<code>class CustomView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)

        let panGR = UIPanGestureRecognizer(target: self, action: #selector(panGestureDetected(sender:)))
        self.gestureRecognizers = [panGR]
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var gestureBeginning: CGFloat = 0.0

    func panGestureDetected(sender: UIPanGestureRecognizer) {
        guard sender.numberOfTouches > 0 else { return }

        let touchPoint = sender.location(ofTouch: 0, in: self)

        switch sender.state {
        case .began:
            gestureBeginning = touchPoint.x
            print("gestureBeginning: \(gestureBeginning)")
        case .changed:
            let progress = touchPoint.x - gestureBeginning
            print("progress: \(progress)")
            let rotationAngle: CGFloat = 1.6 * progress
            let view = self.subviews[0]
            let rads =  rotationAngle * .pi / 180
            view.transform = CGAffineTransform(rotationAngle: rads)
        default:
            break
        }
    }
}
</code>```

To run it on a playground:

```<code>let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png"))
imageView.frame = CGRect(origin: CGPoint(x: 50.0, y: 50.0), size: CGSize(width: 150.0, height: 150.0))

let containerView = CustomView(frame: CGRect(origin: .zero, size: CGSize(width: 250.0, height: 250.0)))
containerView.addSubview(imageView)

PlaygroundPage.current.liveView = containerView
PlaygroundPage.current.needsIndefiniteExecution = true
</code>```

Body:
I'm trying to rotate an ImageView I have using CGAffineTransform. Basically, what I want to happen is that every time the x-coordinate increases, I want the ImageView to rotate a little more.

I did the math and I want the ImageView to rotate 1.6º every 1 x-coordinate. This is what I have so far in the gesture recognizer function:

@objc func personDragRecognizer(recognizer: UIPanGestureRecognizer) {

    let rotationAngle: CGFloat = 1.6

    let translation = recognizer.translation(in: rView)
    if let view = recognizer.view {
        view.center = CGPoint(x:view.center.x +  translation.x, y:view.center.y + translation.y)
        view.transform = CGAffineTransform(rotationAngle: rotationAngle)
    }
    recognizer.setTranslation(CGPoint.zero, in: rView)

    if recognizer.view?.center == CGPoint(x: 197.5, y: 232.5)  {
        PlaygroundPage.current.liveView = eeView
    }

The problem with this is that it rotates to 576º bc that's 1.6 times 360. And it doesn't keep on rotating it only does it once. I want it to continually rotate.

If anyone could help the help would be immensely appreciated. Thanks so so much in advance!!

Cheers,
Theo

Body:
I'm not sure if I fully understood the feature you're trying to implement. Here is a sample for UIView subclass responsible for image rotation.

class CustomView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)

        let panGR = UIPanGestureRecognizer(target: self, action: #selector(panGestureDetected(sender:)))
        self.gestureRecognizers = [panGR]
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var gestureBeginning: CGFloat = 0.0

    func panGestureDetected(sender: UIPanGestureRecognizer) {
        guard sender.numberOfTouches > 0 else { return }

        let touchPoint = sender.location(ofTouch: 0, in: self)

        switch sender.state {
        case .began:
            gestureBeginning = touchPoint.x
            print("gestureBeginning: \(gestureBeginning)")
        case .changed:
            let progress = touchPoint.x - gestureBeginning
            print("progress: \(progress)")
            let rotationAngle: CGFloat = 1.6 * progress
            let view = self.subviews[0]
            let rads =  rotationAngle * .pi / 180
            view.transform = CGAffineTransform(rotationAngle: rads)
        default:
            break
        }
    }
}

To run it on a playground:

let imageView = UIImageView(image: #imageLiteral(resourceName: "image.png"))
imageView.frame = CGRect(origin: CGPoint(x: 50.0, y: 50.0), size: CGSize(width: 150.0, height: 150.0))

let containerView = CustomView(frame: CGRect(origin: .zero, size: CGSize(width: 250.0, height: 250.0)))
containerView.addSubview(imageView)

PlaygroundPage.current.liveView = containerView
PlaygroundPage.current.needsIndefiniteExecution = true


问:
Decimal integer to binary in C
Please give me some feedback on how to make my code better or more efficient. It should convert a decimal integer to binary.

```<code>#include <stdio.h>

binarydigits(int div, int dis)
{
    int numit;
    numit=0;

    do
    {
        ++numit;
        div /= dis;
    }
    while (div!=1);
    ++numit;
    return numit;
}

main()
{
    int x, nb, i;

    printf("\n Input an decimal integer number to be converted: ");
    scanf("%d", &x);
    fflush(stdin);

    if (x==0 || x==1)
    {
        printf("\n\n %d in binary : %d", x, x);
    }

    else
    {
        printf("\n\n %d in binary : ", x);
        nb = binarydigits(x, 2);
        // the function 'binarydigits' returns how many binary digits are needed to represent 'x'
        int remind[nb];
        // an array of 'nb' elements is declared. Each element of this array will hold a binary digit
        for(i=(nb-1) ; i>=0 ; --i, x/=2)
        {
            remind[i] = x%2;
        }
        //this 'for' structure saves the remainder of 'x/2' (x%2) in an element of the 'remind[nb]' array

        for (i=nb ; i>0 ; --i)
        {
            printf("%d", remind[nb-i]);
        }
        //this 'for' structure prints the elements of the 'remind[nb]' array in increasing order

    }

    getch();
    return 0;

}
</code>```

Any tips on how to make this better would be nice.

答:
How to make my code better or more efficient?

My advice to you is to stop trying to learn C by trial-and-error method. You should obtain a good book and study it first. It is impossible to create a fast and efficient C program without mastering pointers, bitwise operators and memory manipulations.

Simply, to make your code fast, you should completelly delete your code (I am not going to list all of your bad-practice things here) and start understanding my example:

```<code>int main(void){
  char *s = (char*)malloc(33);
  char *t = s;
  int a;

  s += 33;
  *s = 0;

  printf("Enter a number: ");
  scanf("%d", &a);
  printf("That number in binary: ");
  while(a){
    *(--s) = a & 1 ? '1' : '0';
    a >>= 1;
  }
  printf("%s\n", s);

  free(t);
  return 0;
}
</code>```

Explanation: we have pointer (if you don't know pointers, well you should probably first learn them) s which points to the end of a string. While number from input (number a) is nonzero, we put its last binary digit in the string, decrease pointer and divide a integrally by 2 (this is a >>= 1 instruction). When a is 0, just print the string.

Title: Decimal integer to binary in C

Body:
Please give me some feedback on how to make my code better or more efficient. It should convert a decimal integer to binary.

#include <stdio.h>

binarydigits(int div, int dis)
{
    int numit;
    numit=0;

    do
    {
        ++numit;
        div /= dis;
    }
    while (div!=1);
    ++numit;
    return numit;
}

main()
{
    int x, nb, i;

    printf("\n Input an decimal integer number to be converted: ");
    scanf("%d", &x);
    fflush(stdin);

    if (x==0 || x==1)
    {
        printf("\n\n %d in binary : %d", x, x);
    }

    else
    {
        printf("\n\n %d in binary : ", x);
        nb = binarydigits(x, 2);
        // the function 'binarydigits' returns how many binary digits are needed to represent 'x'
        int remind[nb];
        // an array of 'nb' elements is declared. Each element of this array will hold a binary digit
        for(i=(nb-1) ; i>=0 ; --i, x/=2)
        {
            remind[i] = x%2;
        }
        //this 'for' structure saves the remainder of 'x/2' (x%2) in an element of the 'remind[nb]' array

        for (i=nb ; i>0 ; --i)
        {
            printf("%d", remind[nb-i]);
        }
        //this 'for' structure prints the elements of the 'remind[nb]' array in increasing order

    }

    getch();
    return 0;

}

Any tips on how to make this better would be nice.

Body:
How to make my code better or more efficient?

My advice to you is to stop trying to learn C by trial-and-error method. You should obtain a good book and study it first. It is impossible to create a fast and efficient C program without mastering pointers, bitwise operators and memory manipulations.

Simply, to make your code fast, you should completelly delete your code (I am not going to list all of your bad-practice things here) and start understanding my example:

int main(void){
  char *s = (char*)malloc(33);
  char *t = s;
  int a;

  s += 33;
  *s = 0;

  printf("Enter a number: ");
  scanf("%d", &a);
  printf("That number in binary: ");
  while(a){
    *(--s) = a & 1 ? '1' : '0';
    a >>= 1;
  }
  printf("%s\n", s);

  free(t);
  return 0;
}

Explanation: we have pointer (if you don't know pointers, well you should probably first learn them) s which points to the end of a string. While number from input (number a) is nonzero, we put its last binary digit in the string, decrease pointer and divide a integrally by 2 (this is a >>= 1 instruction). When a is 0, just print the string.


问:
Setting data on ViewHolder
I am using a RecyclerView in my project and I am having an issue where my RecyclerView is being populated by the same values as if the values are being overwritten inside the forEach in onBindViewHolder below:

```<code>   class ProfListAdapter extends RecyclerView.Adapter<ViewHolder>{
    private LayoutInflater mLayoutInflater;
    public ProfListAdapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType){
        return new ViewHolder(mLayoutInflater
        .inflate(R.layout.recycler_view, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position){
    System.out.println(position);
        final String profName;
        Integer k = 0;
        for (Integer key : mData.keySet()) {
            viewHolder.setData(mData.get(key));
        }

    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            Intent intent = ProfPager.newIntent(getActivity(), position);
            startActivity(intent);
        }
    });
    }
    @Override
    public int getItemCount() {
    return mData.size();
}
}

class ViewHolder extends RecyclerView.ViewHolder {
    private TextView mTextView;
    private ViewHolder(View itemView){
        super(itemView);
        mTextView = (TextView) itemView.findViewById(R.id._prof); // galleryimage
    }
    private void setData(String profName){
        mTextView.setText(profName);
        System.out.println("setData" + profName);
    }
}
</code>```

When I log out to the console I can see that the value in setData() is getting the correct item to display. However, what is being displayed inside the fragment is just the last profName that is comes across in the forEach. What could be causing this behaviour? Here is a link to the entire fragment: https://pastebin.com/xS7CSbbK

If I use the position, it does not always coincide with the key in the Hashmap that stores the SQLite _id.

答:
Setting data on ViewHolder

You may not need the for each loop inside the onBindViewHolder, instead try to set data using the position value available at onBindViewHolder. cheers :)

Title: Setting data on ViewHolder

Body:
I am using a RecyclerView in my project and I am having an issue where my RecyclerView is being populated by the same values as if the values are being overwritten inside the forEach in onBindViewHolder below:

   class ProfListAdapter extends RecyclerView.Adapter<ViewHolder>{
    private LayoutInflater mLayoutInflater;
    public ProfListAdapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType){
        return new ViewHolder(mLayoutInflater
        .inflate(R.layout.recycler_view, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position){
    System.out.println(position);
        final String profName;
        Integer k = 0;
        for (Integer key : mData.keySet()) {
            viewHolder.setData(mData.get(key));
        }

    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v){
            Intent intent = ProfPager.newIntent(getActivity(), position);
            startActivity(intent);
        }
    });
    }
    @Override
    public int getItemCount() {
    return mData.size();
}
}

class ViewHolder extends RecyclerView.ViewHolder {
    private TextView mTextView;
    private ViewHolder(View itemView){
        super(itemView);
        mTextView = (TextView) itemView.findViewById(R.id._prof); // galleryimage
    }
    private void setData(String profName){
        mTextView.setText(profName);
        System.out.println("setData" + profName);
    }
}

When I log out to the console I can see that the value in setData() is getting the correct item to display. However, what is being displayed inside the fragment is just the last profName that is comes across in the forEach. What could be causing this behaviour? Here is a link to the entire fragment: https://pastebin.com/xS7CSbbK

If I use the position, it does not always coincide with the key in the Hashmap that stores the SQLite _id.


问:
MySQL query to check a row's cells for value and return column name
I have been struggling with a certain query all day and I decided to ask for help.

I need a query that checks an entire table row and all its table cells for a value 'yes' and then it needs to give me the names of the columns where this is true.

To clarify with an example:
in the table above I need to check the fruit row for all the cells with the value 'yes' and have the corresponding column names returned to me. In this case the result would be 'banana', 'apple' and 'pear'.

I hope that example helps.

```<code>-- pseudo code
SELECT `COLUMN_NAMES`
FROM `My_Table`
ROW `fruit`
WHERE `value` = 'yes';
</code>```

I'd also like to note that I can't rearrange my database. The db structure can't be changed because we are already doing queries like SELECT 'property' WHERE 'Banana' = 'yes'(which would return 'fruit'). I need it to work the other way around too.

答:
i recommend you try to change the requirement to return 'banana, apple, pear'.  if you can do that, then you can hard code if statements into your query in the following pattern:</p>

```<code>select concat(
         if (`banana`='yes',  'banana,', ''),
         if (`apple` ='yes',  'apple,',  ''),
         if (`pear`  ='yes',  'pear,',   ''),
         if (`beef`  ='yes',  'beef,',   ''),
         if (`water` ='yes',  'water,',  '')
   ) as properties
from table1
where ...
</code>```

Body:
I have been struggling with a certain query all day and I decided to ask for help.

I need a query that checks an entire table row and all its table cells for a value 'yes' and then it needs to give me the names of the columns where this is true.

To clarify with an example:
in the table above I need to check the fruit row for all the cells with the value 'yes' and have the corresponding column names returned to me. In this case the result would be 'banana', 'apple' and 'pear'.

I hope that example helps.

-- pseudo code
SELECT `COLUMN_NAMES`
FROM `My_Table`
ROW `fruit`
WHERE `value` = 'yes';

I'd also like to note that I can't rearrange my database. The db structure can't be changed because we are already doing queries like SELECT 'property' WHERE 'Banana' = 'yes'(which would return 'fruit'). I need it to work the other way around too.

Body:
i recommend you try to change the requirement to return 'banana, apple, pear'.  if you can do that, then you can hard code if statements into your query in the following pattern:

select concat(
         if (`banana`='yes',  'banana,', ''),
         if (`apple` ='yes',  'apple,',  ''),
         if (`pear`  ='yes',  'pear,',   ''),
         if (`beef`  ='yes',  'beef,',   ''),
         if (`water` ='yes',  'water,',  '')
   ) as properties
from table1
where ...


问:
Is it possible to have zero cost abstractions on Scala Native?
I was reading the documentation of the Rust language, and I was immediately interested in Scala Native, thinking about mature libraries and insanely optimized algorithms. I've two questions here

Is it possible to have zero-cost abstractions in Scala Native (similar to Rust)?

Can we do away with the BOEHM GC which is nevertheless present in all Scala Native installations, so it is usable on embedded systems?

答:
for Q1: if by "zero cost abstractions" you are referring to smth analogue to type classes and compile time dispatch, I would answer this: yes, Scala does provide type classes, implemented using implicit parameters and compile time dispatch of typeclass functions (ie the implicit object holding the type class functions is identified at compile time and passed in automatically to all functions using the typeclass), and just reasoning out loud, since scala-native it emits llvm from the same internal representation as the standard scalac compiler, the runtime mechanism should be pretty similar, types may also be erased as in the JVM target (unless LLVM is super intelligent and manages to re-infer types and to do its own dispatch but I doubt it).

```<code>object Main extends App {

  // the typeclass
  trait M[A] {
    def zero: A
    def add(a1: A, a2: A): A
  }

  // the typeclass instance for Boolean
  implicit object BooleanM extends M[Boolean] {
    def zero: Boolean = false
    def add(a1: Boolean, a2: Boolean): Boolean = a1 || a2
  }
  // the typeclass instance for Int
  implicit object IntM extends M[Int] {
    def zero: Int = 0
    def add(a1: Int, a2: Int): Int = {
      require(a1 >= 0 && a2 >=0)
      a1 + a2
    }
  }
  // the typeclass instance for String
  implicit object StringM extends M[String] {
    def zero: String = ""
    def add(a1: String, a2: String): String = a1 + a2
  }

  // a generic method that uses the typeclass
  def justDoingMyThang[A: M](a1: A, a2:A): A = {
    val tc = implicitly[M[A]]
    tc.add(tc.zero, tc.add(a1, a2))
  }

  // the generic method used on types for which it is defined
  println( justDoingMyThang(false, true).toString )
  println( justDoingMyThang(1, 2).toString )
  println( justDoingMyThang("foo", "bar").toString )
}
</code>```

still, the generic method that uses the typeclass is not specialized at all and calling it on either type involves first getting the implicit object using "implicitly" (a method call), and then calling a typeclass method on the implicit object (hence perhaps some V-table inspection ?).

So, there is no hardwired function call here, there some degree of indirection so the cost might be close to zero but not exactly zero.

I guess we can use @specialized as follows to get even more compile time specialization

```<code> def justDoingMyThang[@specialized(Boolean,Int) A: M](a1: A, a2:A): A = {
    val tc = implicitly[M[A]]
    tc.add(tc.zero, tc.add(a1, a2))
  }
</code>```

but any call on a non-value type will somehow use the generic version of the method. I should look at the generated code to be sure but I'm too lazy tonight...

for Q2: I saw in the documentation of scala-native that the GC config flag "none" was scheduled for inclusion in v.0.2.x, so perhaps we can hope for static allocation and more embedded friendliness.

Body:
for Q1: if by "zero cost abstractions" you are referring to smth analogue to type classes and compile time dispatch, I would answer this: yes, Scala does provide type classes, implemented using implicit parameters and compile time dispatch of typeclass functions (ie the implicit object holding the type class functions is identified at compile time and passed in automatically to all functions using the typeclass), and just reasoning out loud, since scala-native it emits llvm from the same internal representation as the standard scalac compiler, the runtime mechanism should be pretty similar, types may also be erased as in the JVM target (unless LLVM is super intelligent and manages to re-infer types and to do its own dispatch but I doubt it).

object Main extends App {

  // the typeclass
  trait M[A] {
    def zero: A
    def add(a1: A, a2: A): A
  }

  // the typeclass instance for Boolean
  implicit object BooleanM extends M[Boolean] {
    def zero: Boolean = false
    def add(a1: Boolean, a2: Boolean): Boolean = a1 || a2
  }
  // the typeclass instance for Int
  implicit object IntM extends M[Int] {
    def zero: Int = 0
    def add(a1: Int, a2: Int): Int = {
      require(a1 >= 0 && a2 >=0)
      a1 + a2
    }
  }
  // the typeclass instance for String
  implicit object StringM extends M[String] {
    def zero: String = ""
    def add(a1: String, a2: String): String = a1 + a2
  }

  // a generic method that uses the typeclass
  def justDoingMyThang[A: M](a1: A, a2:A): A = {
    val tc = implicitly[M[A]]
    tc.add(tc.zero, tc.add(a1, a2))
  }

  // the generic method used on types for which it is defined
  println( justDoingMyThang(false, true).toString )
  println( justDoingMyThang(1, 2).toString )
  println( justDoingMyThang("foo", "bar").toString )
}

still, the generic method that uses the typeclass is not specialized at all and calling it on either type involves first getting the implicit object using "implicitly" (a method call), and then calling a typeclass method on the implicit object (hence perhaps some V-table inspection ?).

So, there is no hardwired function call here, there some degree of indirection so the cost might be close to zero but not exactly zero.

I guess we can use @specialized as follows to get even more compile time specialization

 def justDoingMyThang[@specialized(Boolean,Int) A: M](a1: A, a2:A): A = {
    val tc = implicitly[M[A]]
    tc.add(tc.zero, tc.add(a1, a2))
  }

but any call on a non-value type will somehow use the generic version of the method. I should look at the generated code to be sure but I'm too lazy tonight...

for Q2: I saw in the documentation of scala-native that the GC config flag "none" was scheduled for inclusion in v.0.2.x, so perhaps we can hope for static allocation and more embedded friendliness.


问:
how to avoid servlet-api.jar and jsp-api.jar copying into tomcat deployment
I'm using myeclipse and to compile successfully I have servlet-api.jar and jsp-api.jar in the java build path library. The problem occurs when the myeclipse deploy the web application to tomcat and these two jars interfering with tomcat version of these two jars. I want to avoid these two jars including in webapp WEB-INF/lib directory. I'm not using ant, just using myelcipse sandbox tomcat server to deploy. Thanks.</p>

答:
Firstly, you're better off using the Server Runtime library that provides the necessary classes and interfaces for compiling servlets and JSPs, instead of relying on manually added JARs like servlet-api.jar and jsp-api.jar.

Secondly, if these are not manually added JARs, but rather embedded due to another dependency, you might want to check whether it is possible to restrict MyEclipse from embedding these JARs when building the WAR/EAR file. Usually this is achieved by opening the Properties dialog of the dynamic web project, and then unchecking these JARs in the Java EE Module dependencies property page (the individual JARs should appear listed in the Web Libraries tab).


问:
Argparse: Check if any arguments have been passed
My script should start a demo mode, when the no parameters are given. I tried this:

```<code>args = parser.parse_args()
if len(args) == 0:
    run_demo()
else:
    # evaluate args
</code>```

Which gives a *** TypeError: object of type 'Namespace' has no len() as args is no list.

How would I achieve what I want?

答:
Let us assume the following example to extend Yours for completeness:

```<code>#!/usr/bin/env python3

import argparse

...
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('input', nargs='?' action='store')
    parser.add_argument('-l', '--length', type=int, action='store')
    parser.add_argument('-v', '--verbose', action='store_true')
    args = parser.parse_args()
    if (args.input == None and args.length == None):
        parser.print_help()
    else:
        print(args)

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

Your Namespace object, mentioned by @Ben, in this example is args. From the strings in parser.add_argument a variable is created. You can access it through args.input or args.length or args.verbose. You can verify this by executing print(args) which will actually show something like this:

```<code>Namespace(input=None, length=None, verbose=False)
</code>```

since verbose is set to True, if present and input and length are just variables, which don't have to be instantiated (no arguments provided).

Also helpful can be group = parser.add_mutually_exclusive_group() if you want to ensure, two attributes cannot be provided simultaneously.

For further reference, please refer to:

https://docs.python.org/3/howto/argparse.html
Well structured HOWTO

https://docs.python.org/3/library/argparse.html
Argparse module documentation

Body:
My script should start a demo mode, when the no parameters are given. I tried this:

args = parser.parse_args()
if len(args) == 0:
    run_demo()
else:
    # evaluate args

Which gives a *** TypeError: object of type 'Namespace' has no len() as args is no list.

How would I achieve what I want?

Body:
Let us assume the following example to extend Yours for completeness:

#!/usr/bin/env python3

import argparse

...
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('input', nargs='?' action='store')
    parser.add_argument('-l', '--length', type=int, action='store')
    parser.add_argument('-v', '--verbose', action='store_true')
    args = parser.parse_args()
    if (args.input == None and args.length == None):
        parser.print_help()
    else:
        print(args)

if __name__ == '__main__':
    main()

Your Namespace object, mentioned by @Ben, in this example is args. From the strings in parser.add_argument a variable is created. You can access it through args.input or args.length or args.verbose. You can verify this by executing print(args) which will actually show something like this:

Namespace(input=None, length=None, verbose=False)

since verbose is set to True, if present and input and length are just variables, which don't have to be instantiated (no arguments provided).

Also helpful can be group = parser.add_mutually_exclusive_group() if you want to ensure, two attributes cannot be provided simultaneously.

For further reference, please refer to:

https://docs.python.org/3/howto/argparse.html
Well structured HOWTO

https://docs.python.org/3/library/argparse.html
Argparse module documentation


问:
Static Nested Type
So i have nested type classes that go something like this:

```<code>namespace MyNamespace
{
    public class User
    {
        private int id = 0;
        private string userId = "";
        private string userPassword = "";

        public int Id
        {
            get { return id; }
            set { id = value; }
        }

        public string UserId
        {
            get { return userId; }
            set { userId = value; }
        }

        public string UserPassword
        {
            get { return userPassword; }
            set { userPassword = value; }
        }

        public User()
        {
            id = 0;
            userId = "";
            userPassword = "";
        }

        public static class SignonInfo
        {
            private static string sesstoken = "";
            private static DateTime sessstart = new DateTime();

            public static string SessToken
            {
                get { return sesstoken; }
                set { sesstoken = value; }
            }

            public static DateTime SessStart
            {
                get { return sessstart; }
                set { sessstart = value; }
            }
        }
    }
}
</code>```

My end goal here was to be able to access the nested static class like this:

```<code>User user = new User();
string token = user.SignonInfo.SessToken;
</code>```

I'm trying to avoid instantiating the class like this:

```<code>User.SignonInfo user = new User.SignonInfo()
</code>```

I need to be able to access properties of both User and SignonInfo classes.

Could someone help me to get on track or slap me about and tell me i'm doing it all wrong?

TIA

答:
You are trying to access your nested class as if it were a member of the instance of the outer class.

Change

string token = user.SignonInfo.SessToken;

to

User.SignonInfo.SessToken;

Note, that you do not get an instance of the static nested type per outer instance, there is only one for the entire outer class.

Title: Static Nested Type

Body:
So i have nested type classes that go something like this:

namespace MyNamespace
{
    public class User
    {
        private int id = 0;
        private string userId = "";
        private string userPassword = "";

        public int Id
        {
            get { return id; }
            set { id = value; }
        }

        public string UserId
        {
            get { return userId; }
            set { userId = value; }
        }

        public string UserPassword
        {
            get { return userPassword; }
            set { userPassword = value; }
        }

        public User()
        {
            id = 0;
            userId = "";
            userPassword = "";
        }

        public static class SignonInfo
        {
            private static string sesstoken = "";
            private static DateTime sessstart = new DateTime();

            public static string SessToken
            {
                get { return sesstoken; }
                set { sesstoken = value; }
            }

            public static DateTime SessStart
            {
                get { return sessstart; }
                set { sessstart = value; }
            }
        }
    }
}

My end goal here was to be able to access the nested static class like this:

User user = new User();
string token = user.SignonInfo.SessToken;

I'm trying to avoid instantiating the class like this:

User.SignonInfo user = new User.SignonInfo()

I need to be able to access properties of both User and SignonInfo classes.

Could someone help me to get on track or slap me about and tell me i'm doing it all wrong?

TIA


问:
DocusignAPI: UNKNOWN_RECIPIENT
I have 2 envelope with 2 different document but same recipient information:

My data json below:
Envelope 1:

```<code>   {
      "envelopeId": "a2c6bb90-bc62-4c54-84f0-47b31ae559ea",
      "uri": "/envelopes/a2c6bb90-bc62-4c54-84f0-47b31ae559ea",
      "statusDateTime": "2017-03-28T06:11:41.9255402Z",
      "status": "sent"
    }
    {
      "templateId": "14c79646-7849-4f15-801e-af85875b9d2a",
      "templateRoles": [
        {
          "email": "nguyenvannhu0405@gmail.com",
          "roleName": "Client",
          "name": "Nguyen Nhu",
          "clientUserId": "1091",
        },
        {
          "email": "nguyenvannhu.1234@gmail.com",
          "roleName": "Signer2",
          "name": "Nguyen Nhu 2",
          "clientUserId": "1092",
          "tabs": {
          }
        }
      ],
      "status": "sent",
      "emailSubject": "Test File Contract.pdf"
    }
</code>```

Envelope 2:

```<code>{
  "envelopeId": "e0cb2849-7f5c-456d-ae95-0372d2d333f2",
  "uri": "/envelopes/e0cb2849-7f5c-456d-ae95-0372d2d333f2",
  "statusDateTime": "2017-03-28T06:17:39.0928408Z",
  "status": "sent"
}
{
  "templateId": "1080a8a2-d5be-4402-99f7-cbab35910d8d",
  "templateRoles": [
    {
      "email": "nguyenvannhu0405@gmail.com",
      "roleName": "Client",
      "name": "Nguyen Nhu",
      "clientUserId": "1091",
      "tabs": {

      }
    },
    {
      "email": "nguyenvannhu.1234@gmail.com",
      "roleName": "Signer2",
      "name": "Nguyen Nhu 2",
      "clientUserId": "1092",
      "tabs": {

  "status": "sent",
  "emailSubject": "Test File.pdf"
}
</code>```

Problem is When Client sign in URL, I change Client name(Nguyen Nhu to Nguyen Nhu 12). I sign normal for envelope 1 and envelope 2.

Envelope 1 is completed

But when Co-Client also do the same:change Signer2 name(Nguyen Nhu 2 to Nguyen Nhu 22).

I only sign for envelope 1 and envelope 2 get error:

```<code>DocuSign.eSign.Client.ApiException: Error calling CreateRecipientView: {
  "errorCode": "UNKNOWN_ENVELOPE_RECIPIENT",
  "message": "The recipient you have identified is not a valid recipient of the specified envelope."
}
   at DocuSign.eSign.Api.EnvelopesApi.CreateRecipientViewWithHttpInfo(String accountId, String envelopeId, RecipientViewRequest recipientViewRequest)
   at DocuSign.eSign.Api.EnvelopesApi.CreateRecipientView(String accountId, String envelopeId, RecipientViewRequest recipientViewRequest)
   at Docusigndll.Docusign.GetUrlDocumentSign(String accountId, String envelopeId, Recipient recipient, String urlRedirect) in d:\soft\Docusigndll\Docusigndll\Docusign.cs:line 269
</code>```

I vaguely think error is because CliendUserId is the same in envelope 1 and envelope 2 when I change name of Co-Client(sign in envelope 1) and Docusign save in database new name of Co-Client.In envelope 2 old name of Co-Client are difference from Name of Recipient save in database of Docusign. => Error.But why Client name I also do the same it isn't get error.

Hope everybody help me
Thanks a lot

答:
Once you send an envelope and you are ready to generate a signing URL you need to correctly identify the recipient who will sign using their:

Recipient Name

Recipient Email

ClientUserId

RecipientId

If any one of these are incorrect then the platform will not be able to identify the recipient and you will receive the UNKNOWN_RECIPIENT error you're seeing.

To verify the information that's being set you should do a GET request on the envelope recipients after it's been sent but before you attempt to generate the recipient signing URL.  You can use the EnvelopeRecipients: list API for that.

Looking at your question it looks like you are changing the recipient name after the envelope is sent but before you create the signing URL?  If that's the case then you may need to do a proper envelope correction to update the recipient information in the envelope, THEN make your signing URL request with the updated info and it should work.

For info on how to make an envelope correction see the envelopeViews: createCorrect API request.

And for general info on the Embedded Signing API flow see the Embedding DocuSign features page.

Title: DocusignAPI: UNKNOWN_RECIPIENT

Body:
I have 2 envelope with 2 different document but same recipient information:

My data json below:
Envelope 1:

   {
      "envelopeId": "a2c6bb90-bc62-4c54-84f0-47b31ae559ea",
      "uri": "/envelopes/a2c6bb90-bc62-4c54-84f0-47b31ae559ea",
      "statusDateTime": "2017-03-28T06:11:41.9255402Z",
      "status": "sent"
    }
    {
      "templateId": "14c79646-7849-4f15-801e-af85875b9d2a",
      "templateRoles": [
        {
          "email": "nguyenvannhu0405@gmail.com",
          "roleName": "Client",
          "name": "Nguyen Nhu",
          "clientUserId": "1091",
        },
        {
          "email": "nguyenvannhu.1234@gmail.com",
          "roleName": "Signer2",
          "name": "Nguyen Nhu 2",
          "clientUserId": "1092",
          "tabs": {
          }
        }
      ],
      "status": "sent",
      "emailSubject": "Test File Contract.pdf"
    }

Envelope 2:

{
  "envelopeId": "e0cb2849-7f5c-456d-ae95-0372d2d333f2",
  "uri": "/envelopes/e0cb2849-7f5c-456d-ae95-0372d2d333f2",
  "statusDateTime": "2017-03-28T06:17:39.0928408Z",
  "status": "sent"
}
{
  "templateId": "1080a8a2-d5be-4402-99f7-cbab35910d8d",
  "templateRoles": [
    {
      "email": "nguyenvannhu0405@gmail.com",
      "roleName": "Client",
      "name": "Nguyen Nhu",
      "clientUserId": "1091",
      "tabs": {

      }
    },
    {
      "email": "nguyenvannhu.1234@gmail.com",
      "roleName": "Signer2",
      "name": "Nguyen Nhu 2",
      "clientUserId": "1092",
      "tabs": {

  "status": "sent",
  "emailSubject": "Test File.pdf"
}

Problem is When Client sign in URL, I change Client name(Nguyen Nhu to Nguyen Nhu 12). I sign normal for envelope 1 and envelope 2.

Envelope 1 is completed

But when Co-Client also do the same:change Signer2 name(Nguyen Nhu 2 to Nguyen Nhu 22).

I only sign for envelope 1 and envelope 2 get error:

DocuSign.eSign.Client.ApiException: Error calling CreateRecipientView: {
  "errorCode": "UNKNOWN_ENVELOPE_RECIPIENT",
  "message": "The recipient you have identified is not a valid recipient of the specified envelope."
}
   at DocuSign.eSign.Api.EnvelopesApi.CreateRecipientViewWithHttpInfo(String accountId, String envelopeId, RecipientViewRequest recipientViewRequest)
   at DocuSign.eSign.Api.EnvelopesApi.CreateRecipientView(String accountId, String envelopeId, RecipientViewRequest recipientViewRequest)
   at Docusigndll.Docusign.GetUrlDocumentSign(String accountId, String envelopeId, Recipient recipient, String urlRedirect) in d:\soft\Docusigndll\Docusigndll\Docusign.cs:line 269

I vaguely think error is because CliendUserId is the same in envelope 1 and envelope 2 when I change name of Co-Client(sign in envelope 1) and Docusign save in database new name of Co-Client.In envelope 2 old name of Co-Client are difference from Name of Recipient save in database of Docusign. => Error.But why Client name I also do the same it isn't get error.

Hope everybody help me
Thanks a lot


问:
create five bullet points programmatically in react? Users can add tasks, but I want to start with initial variable number of bullets
I want to avoid hardcoding
 X times, and instead want to programmatically render them.

Here is what I have right now:

```<code><ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
</code>```

I can render them using a for loop, but is there a more elegant way?

Thanks

答:
I would do something like:

Set initial state in constructor ()

```<code>this.state = {
  tasks: [
    {
      name: '',
      complete: false
    },
    {
      name: '',
      complete: false
    },
    {
      name: '',
      complete: false
    },
    {
      name: '',
      complete: false
    },
    {
      name: '',
      complete: false
    }
  ]
}
</code>```

Then in render ()

```<code><ul>
  { this.state.tasks.map(task => <li>{task.name}</li> }
</ul>
</code>```

Note, you will get an error if you don't set a key prop.

Body:
I want to avoid hardcoding
 X times, and instead want to programmatically render them.

Here is what I have right now:

I can render them using a for loop, but is there a more elegant way?

Thanks

Body:
I would do something like:

Set initial state in constructor ()

this.state = {
  tasks: [
    {
      name: '',
      complete: false
    },
    {
      name: '',
      complete: false
    },
    {
      name: '',
      complete: false
    },
    {
      name: '',
      complete: false
    },
    {
      name: '',
      complete: false
    }
  ]
}

Then in render ()

<ul>
  { this.state.tasks.map(task => <li>{task.name}</li> }
</ul>

Note, you will get an error if you don't set a key prop. <li key={task.uniquevaluehere}>


问:
Properly handling errors with Node/Express
Which is the proper way to return errors with your server in general (node/express) and reject a promise?

A) Like this: res.json({status: 1, message: 'Test missing phone.', error: 'phone'})

And then pull the error 'code' out of error and the message out of messsage on your front end, resulting in a fulfilled promise that has an error and message in it.

B) Like this;

```<code>res.status(500)
res.json({message: 'Test missing phone.'})
</code>```

And then just pull message out and call .reject with the message. Or res.error or something.

Do either of these cause a 'rejected' promise or 'error' callback that would make frontend stuff easier?

Should I be causing promise/callback rejection when I get an error, or just send a fulfilled promise with an error in the object like A?

Which of these is the 'correct' way to return an error from your server to your front end?

Currently I use method A, but it seems pretty dumb because I have to handle the error twice, backend (to actually send the custom error) and frontend (to check if the fulfilled promise has an error object, and then display a popup). Method B would eliminate the 'checking if the fulfilled promise has an error object' part, since a rejected promise is an error by nature.

EDIT: I'm using React Native as frontend.

EDIT2: If you res.status(500).json({test: 'Test missing phone.'}) on your backend you can console.log(error.response.data) on the frontend to make "B" a viable option.

答:
Adding in the res.status(500) is proper in terms of best practices. If you say that there are 'errors with your server' you should definitely label the response as such - i.e. response code 500 which indicates exactly that.

While you know what kind of responses to expect, if this were a project you were developing with others or an API to be shared to the public, it would seem counterintuitive to not get a 500. Sending that 500 will make handling the error more straightforward whether using promises or vanilla ajax.

That said, no reason you can't also include the full JSON object that you mentioned from part A (i.e. {status: 1, message: 'Test missing phone.', error: 'phone'}) to provide more info to your front end.

Body:
Which is the proper way to return errors with your server in general (node/express) and reject a promise?

A) Like this: res.json({status: 1, message: 'Test missing phone.', error: 'phone'})

And then pull the error 'code' out of error and the message out of messsage on your front end, resulting in a fulfilled promise that has an error and message in it.

B) Like this;

res.status(500)
res.json({message: 'Test missing phone.'})

And then just pull message out and call .reject with the message. Or res.error or something.

Do either of these cause a 'rejected' promise or 'error' callback that would make frontend stuff easier?

Should I be causing promise/callback rejection when I get an error, or just send a fulfilled promise with an error in the object like A?

Which of these is the 'correct' way to return an error from your server to your front end?

Currently I use method A, but it seems pretty dumb because I have to handle the error twice, backend (to actually send the custom error) and frontend (to check if the fulfilled promise has an error object, and then display a popup). Method B would eliminate the 'checking if the fulfilled promise has an error object' part, since a rejected promise is an error by nature.

EDIT: I'm using React Native as frontend.

EDIT2: If you res.status(500).json({test: 'Test missing phone.'}) on your backend you can console.log(error.response.data) on the frontend to make "B" a viable option.


答:
```<code>const list = [{name: 'tom'}, {name: 'frank'}, {name: 'Joe'}];
const renderList = this.props.list.map(function (result) {
            return (
                <li id="search-result" key={result.name} className="list-group-item list-group-item-action">{result.name}</li>
            );
        });
<ul>
{renderList}
</ul>
</code>```

Title: create five bullet points programmatically in react? Users can add tasks, but I want to start with initial variable number of bullets


问:
Complex mathematical horizontal parallax easing function
I'm currently diving into parallax effects on the web.

Parallax scrolling is a technique in computer graphics and web design, where background images move by the camera slower than foreground images, creating an illusion of depth in a 2D scene and adding to the immersion.
  ~ Wikipedia

I want to create a little container (could be an image, or any block level element) and move it across the screen horizontally as the user scrolls.

The effect should be scalable across all viewports. Meaning that the hight and the width of the element that the element is moving across should not matter.

When the user has scrolled half of the height of the screen the "moving element" should be in the exact center. Since the user will have scrolled half of the screen the element will be vertically already. We're only worried about horizontally right now.

I've thought about this question for a while and came up with a pretty good idea of how.

Take the hight and the width of the element you want the "moving element" to move across. For example a screen that is 1000px tall and 600px wide.

Divide the width by the height. For example (600px / 1000px = 3/5 = 0.6)

Take the amount of pixels the user scrolled and multiply it by the number we just created. For example (500px * 0.6 = 300px). As you can see this is the exact center.

Move the element across the screen by the amount of pixels just calculated.

This calculation works fine even for every screen size, however it's linear. Meaning that the element will move at the same speed across the screen all the time. Let me show you what I mean.

Let's draw out a screen size. (Let's say 1000 * 500)

Calculate two points for this graph ->

screen factor: (500 / 1000) = 0.5
  1. The first point is going to be easy. Let's say we scrolled exactly 0px -> (0.5 * 0) = 0
  The "Moving element" will not have moved at all.
  2. For the second element we'll take the center. Just for convenience.

The vertical center is at 500px -> (0.5 * 500) = 250 px (Exactly the horizontal center)

Put the results in a graph and draw a line through the points.

In the graph above you can see that whenever the user scrolls down the "moving element" will follow the line (the values on the x-axis).

My question

I really hope I described all that well enough to understand. Now on to my question.

What I want to create is a moving element that would go faster on the edge of the screen and slow down a bit in the middle. If we were to draw that out in the same way we just did. (Creating a graph where we can take the amount of pixels scrolled and see where the element should be positioned horizontally) it would look like this:

Sorry for the poor quality of the image but this is the part I'm having problems with.

As you can see in this graph the "moving element" wouldn't be moving all that much in the middle of the graph. (I over did it a bit in my drawing but you get the general idea.)

What I need is a mathematical function that takes three parameters (Screen height, width and the amount of pixels scrolled) and returns the horizontal position of the "moving element".

My idea:

My idea was to position the element in the dead center of the page and then to move it left and right (translations using CSS and JavaScript) based on how far there has been scrolled.

The graph would look something like this:

The (Hand drawn) graph above would be true for a screen that's 1000x600px since the "moving element" translates -300px when no scrolling has been done and 300px when 100% has been scrolled.

However I have no idea on how to create a mathematical function that would be true for every screen size.

To be clear I need a function that "always" starts at Y= (-screen-width/2) and X = 0. It should always cross the point (sreen-height; (screen-width//2)) and the function should be in a form of x^3 (To get the right easing)

I really hope I explained myself well enough and I really hope somebody can help me out here.

答:
You can position it with a function f that actually draws that trajectory.

This is the idea I propose:

Create the function trajectory f such that f(0) = 0, and f(1) = 1 (add more constraints in order to reproduce the effect you are looking for, ex: f(0.5) = 0.5)

Within each scroll event, set x as the amount scrolled and position the element using the coordinates (f(x) * (w - s), x * (h - s)), where w is the document width, h is the document height and s is the size of the element

I can see that cubic functions are plotted like the trajectory you want, so I've been testing with different functions and I've got this working example https://codepen.io/anon/pen/YZJxGa

```<code>var element = $('.element')
var height = $(document).height()
var scrollable = $('body').height() - $(window).height()
var width = $('body').width();

$(window).scroll(function () {
  var winH = $(window).scrollTop()
  var x;

  // Determine the amount of px scrolled since the element first came into view.
  console.log(winH, scrollable)
  x = (winH/scrollable) > 1 ? 1 : (winH/scrollable);

  var posY = x * (height - 120);
  var posX = (-1.000800320128*x
+6.0024009603841*x**2-4.0016006402561*x**3)*(width - 120)

  console.log(posY)

  if (x > 0) {
    console.log(`translate(${posX}px, ${posY}px, 0)`)
    element.css({
      'transform': `translate3d(${posX}px, ${posY}px, 0)`
      })
  }
})
</code>```

You can generate more cubic functions using this tool I've just found http://skisickness.com/2010/04/28/ or solve a couple of systems of linear equations using the fact that you just want to find values for a, b, c and d for f(x) = ax^3 + bx^2 + cx + d

Body:
You can position it with a function f that actually draws that trajectory.

This is the idea I propose:

Create the function trajectory f such that f(0) = 0, and f(1) = 1 (add more constraints in order to reproduce the effect you are looking for, ex: f(0.5) = 0.5)

Within each scroll event, set x as the amount scrolled and position the element using the coordinates (f(x) * (w - s), x * (h - s)), where w is the document width, h is the document height and s is the size of the element

I can see that cubic functions are plotted like the trajectory you want, so I've been testing with different functions and I've got this working example https://codepen.io/anon/pen/YZJxGa

var element = $('.element')
var height = $(document).height()
var scrollable = $('body').height() - $(window).height()
var width = $('body').width();

$(window).scroll(function () {
  var winH = $(window).scrollTop()
  var x;

  // Determine the amount of px scrolled since the element first came into view.
  console.log(winH, scrollable)
  x = (winH/scrollable) > 1 ? 1 : (winH/scrollable);

  var posY = x * (height - 120);
  var posX = (-1.000800320128*x
+6.0024009603841*x**2-4.0016006402561*x**3)*(width - 120)

  console.log(posY)

  if (x > 0) {
    console.log(`translate(${posX}px, ${posY}px, 0)`)
    element.css({
      'transform': `translate3d(${posX}px, ${posY}px, 0)`
      })
  }
})

You can generate more cubic functions using this tool I've just found http://skisickness.com/2010/04/28/ or solve a couple of systems of linear equations using the fact that you just want to find values for a, b, c and d for f(x) = ax^3 + bx^2 + cx + d


问:
python pandas change dataframe to pivoted columns
I have a dataframe that looks as following:

```<code>Type Month  Value
A    1      0.29
A    2      0.90
A    3      0.44
A    4      0.43
B    1      0.29
B    2      0.50
B    3      0.14
B    4      0.07
</code>```

I want to change the dataframe to following format:

```<code>Type    A      B
1      0.29    0.29
2      0.90    0.50
3      0.44    0.14
4      0.43    0.07
</code>```

Is this possible ?

答:
You're having a case of long format table which you want to transform to a wide format.

This is natively handled in pandas:

```<code>df.pivot(index='Month', columns='Type', values='Value')
</code>```

Body:
I have a dataframe that looks as following:

Type Month  Value
A    1      0.29
A    2      0.90
A    3      0.44
A    4      0.43
B    1      0.29
B    2      0.50
B    3      0.14
B    4      0.07

I want to change the dataframe to following format:

Type    A      B
1      0.29    0.29
2      0.90    0.50
3      0.44    0.14
4      0.43    0.07

Is this possible ?

Body:
You're having a case of long format table which you want to transform to a wide format.

This is natively handled in pandas:

df.pivot(index='Month', columns='Type', values='Value')


问:
Changes in package.json for Angular 2 to 4 migration
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

```<code>"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}
</code>```

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

```<code>{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}
</code>```

答:
I normally use the files here for guidance: https://github.com/angular/quickstart

It provides the set of basic seed files needed for an application and it is normally kept up to date with Angular since it is part of the Angular docs at angular.io.

Body:
Currently, the application is on Angular 2.0.0. What are the packages or dependencies that need to be changed for compatibility with Angular 4?
So far i have changed the following,

"dependencies": {
"@angular/common": "4.0.0",
"@angular/compiler": "4.0.0",
"@angular/core": "4.0.0",
"@angular/forms": "4.0.0",
"@angular/http": "4.0.0",
"@angular/platform-browser": "4.0.0",
"@angular/platform-browser-dynamic": "4.0.0",
"@angular/router": "4.0.0",
"@angular/router-deprecated": "2.0.0-rc.2",
"@angular/upgrade": "4.0.0",
"angular2-toaster": "2.0.0",
"rxjs": "^5.0.1",
"typescript": "^2.1.5",
"zone.js": "^0.8.4"
}

Are there any other packages/dependencies that needs to be changed?

Should I make changes to the tsconfig.json?

{

 "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": [
      "es5",
      "es2015",
      "es2017",
      "dom",
      "scripthost"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true,
    "allowNonTsExtensions" : true
  },
  "exclude": [
    "node_modules",
    "typings/main.d.ts",
    "typings/main"
  ],
  "filesGlob": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "!./node_modules/**/*.ts",
    "src/custom_typings.d.ts",
    "typings/browser.d.ts"
  ],
  "awesomeTypescriptLoaderOptions": {
    "resolveGlobs": true,
    "forkChecker": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "atom": { "rewriteTsconfig": false }
}


问:
tcpClient.State analogue in vb.net (versus vb6.0)
I used next code in VB6.0 for Winsock object tcpClient:

```<code>Dim SConst(10) As String
Dim st As Integer

SConst(0) = "Closed"
SConst(1) = "Open"
SConst(2) = "Listening"
SConst(3) = "ConnectionPending"
SConst(4) = "ResolvingHost"
SConst(5) = "HostResolved"
SConst(6) = "Connecting"
SConst(7) = "Connected"
SConst(8) = "Closing"
SConst(9) = "Error"
st = tcpClient.state
TextBox1.Text = SConst(st)
</code>```

Now Im using vb.net and want to do something same.
But there is no .state method now for TcpClient objects!
There is only cpClient.Connected but it returns Boolean so only yes or not. How can I do it alike VB6.0?

Using Visual Vinsent's answer I made this:

```<code>Public Class Form1
    Dim status1 As String
    Dim status2 As String

Private Sub Btn_Connect5001_Click(sender As Object, e As EventArgs)_
                   Handles Btn_Connect5001.Click
        ' Create TcpClient and Connect to
        tcpclnt2 = New TcpClient
        Try
            tcpclnt2.Connect("192.168.1.177", 5001)
        Catch
        End Try
    End Sub

    Private Sub Btn_Disconnect5001_Click(sender As Object, e As EventArgs)_
                     Handles Btn_Disconnect5001.Click
        ' Close TcpClient
        tcpclnt2.Close()
    End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        ' Check status every 300ms
        status2= New IPEndPoint(IPAddress.Parse("192.168.1.177"),5001).GetStatus().ToString()

        TextBox1.Text = Dns.GetHostName + Environment.NewLine +
             "port 1  " + status2 + Environment.NewLine
    End Sub
End Class
</code>```

The problem is: At start status2 is "Unknown", if I connect for the first time status2 is "Established". If I disconnect it became "TimeWait". But If I connect one more time it stay "TimeWait". It never change its value then.

答:
Neither the TcpClient nor its underlying Socket appears to have such an implementation, so I wrote three extension methods which will get that for you.

What they do is that they iterate every active TCP connection on the computer using the IPGlobalProperties class and its GetActiveTcpConnections() method, then they match your connection against the TcpClient's local and remote IP-address.

Extensions.vb

```<code>Imports System.Runtime.CompilerServices
Imports System.Reflection
Imports System.Net
Imports System.Net.Sockets
Imports System.Net.NetworkInformation

Public Module Extensions
    ''' <summary>
    ''' Dynamically gets an object's property by name.
    ''' </summary>
    ''' <param name="Obj">The object which's property to get.</param>
    ''' <param name="PropertyName">The name of the property to get.</param>
    <Extension()> _
    Public Function GetProperty(ByVal Obj As Object, ByVal PropertyName As String) As Object
        Return Obj.GetType().InvokeMember(PropertyName, _
                                           BindingFlags.GetProperty _
                                            Or BindingFlags.IgnoreCase _
                                             Or BindingFlags.Public _
                                              Or BindingFlags.NonPublic _
                                               Or BindingFlags.Instance _
                                                Or BindingFlags.Static, _
                                           Nothing, Obj, Nothing)
    End Function

    ''' <summary>
    ''' Gets the status of a TCP connection.
    ''' </summary>
    ''' <param name="Client">The TcpClient which's status to get.</param>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function GetStatus(ByVal Client As TcpClient) As TcpState
        If Client Is Nothing OrElse Client.Client Is Nothing Then Return TcpState.Unknown
        For Each TcpConnection As TcpConnectionInformation In IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections()

            If TcpConnection.LocalEndPoint.Equals(Client.Client.LocalEndPoint) AndAlso _
                 TcpConnection.RemoteEndPoint.Equals(Client.Client.RemoteEndPoint) Then
                Return TcpConnection.State
            End If

        Next
        Return TcpState.Unknown
    End Function

    ''' <summary>
    ''' Gets the status of a TCP connection.
    ''' </summary>
    ''' <param name="EndPoint">The IPEndPoint (IP-address) of the TCP connection which's status to get.</param>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function GetStatus(ByVal EndPoint As IPEndPoint) As TcpState
        If EndPoint Is Nothing Then Return TcpState.Unknown
        For Each TcpConnection As TcpConnectionInformation In IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections()

            If TcpConnection.LocalEndPoint.Equals(EndPoint) OrElse _
                 TcpConnection.RemoteEndPoint.Equals(EndPoint) Then
                Return TcpConnection.State
            End If

        Next
        Return TcpState.Unknown
    End Function

    ''' <summary>
    ''' Gets the status of a TCP listener.
    ''' </summary>
    ''' <param name="Listener">The TcpListener which's status to get.</param>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function GetStatus(ByVal Listener As TcpListener) As TcpState
        If Listener Is Nothing OrElse Listener.Server Is Nothing Then Return TcpState.Unknown

        'Per the source code, active listeners will always be in the "Listen" state:
        'https://referencesource.microsoft.com/#System/net/System/Net/NetworkInformation/SystemIPGlobalProperties.cs,51fa569e558be704
        If Listener.GetProperty("Active") = True Then Return TcpState.Listen

        Return DirectCast(Listener.LocalEndpoint, IPEndPoint).GetStatus() 'The listener is not in an active state.
    End Function
End Module
</code>```

Now to get the status of a connection you have three options:

Getting the status of a TcpClient:

```<code>Dim Status As String = yourClient.GetStatus().ToString()
</code>```

Getting the status of a TcpListener:

```<code>Dim Status As String = yourListener.GetStatus().ToString()
</code>```

Getting the status of a connection with the specified IP-address:

```<code>Dim Status As String = New IPEndPoint(IPAddress.Parse("your IP-address here"), yourPortHere).GetStatus().ToString()
</code>```

Important notes:

The ToString() call is necessary if you want the status's name (for example Established), otherwise you'll get its enumeration value which is just a normal Integer (for example 3).

Getting the status of a TcpClient or TcpListener will only work if neither they nor their underlying Sockets are disposed. If you wish to get the status of a disconnected TcpClient/-Listener you have to use option no. 3 and get it by its exact IP-address and port.

Disconnected TCP connections can actually be interesting as well because they still exist after being closed and have a state for a little while. Examples of disconnected states are CloseWait or TimeWait.

Read more:

IPGlobalProperties Class - MSDN

IPGlobalProperties.GetActiveTcpConnections() Method - MSDN

System.Net.NetworkInformation Namespace - MSDN

TCP Protocol Operation - Wikipedia (a list of the different TCP connection states)

EDIT:

To fix the problem with connections lingering in a CLOSE_WAIT or TIME_WAIT state you can set the underlying Socket to linger for 0 seconds and then dispose it. Doing so will cause the socket to perform a so-called "hard close" by sending an RST (reset) packet instead of FIN (FIN is what tells a socket that the connection is closed and that it should go into CLOSE-/TIME_WAIT). This method forces the connection to close and no late/retransmitted packets will be mapped to your application after that.

It's actually mentioned on the MSDN documentation:

If the l_onoff member of the linger structure is nonzero and l_linger member is zero, closesocket is not blocked even if queued data has not yet been sent or acknowledged. This is called a hard or abortive close, because the socket's virtual circuit is reset immediately, and any unsent data is lost. On Windows, any recv call on the remote side of the circuit will fail with WSAECONNRESET.

This can be done in a simple extension method (put this in the Extensions module):

```<code>''' <summary>
''' Forces the specified TcpClient to close without sending FIN to the other endpoint. This will stop the connection from going into a TIME_WAIT, CLOSE_WAIT or FIN_* state.
''' </summary>
''' <param name="Client">The TcpClient to close.</param>
''' <remarks></remarks>
<Extension()> _
Public Sub ForceClose(ByVal Client As TcpClient)
    Client.Client.LingerState = New LingerOption(True, 0) 'Set the socket to linger, but for 0 seconds (causes the current connection to send an RST-packet and terminate).
    Client.Client.Dispose() 'Dispose the underlying socket instead of a graceful shutdown.
    Client.Close() 'Close the TcpClient.
End Sub
</code>```

Then just call it like this:

```<code>yourClient.ForceClose()
</code>```

Body:
I used next code in VB6.0 for Winsock object tcpClient:

Dim SConst(10) As String
Dim st As Integer

SConst(0) = "Closed"
SConst(1) = "Open"
SConst(2) = "Listening"
SConst(3) = "ConnectionPending"
SConst(4) = "ResolvingHost"
SConst(5) = "HostResolved"
SConst(6) = "Connecting"
SConst(7) = "Connected"
SConst(8) = "Closing"
SConst(9) = "Error"
st = tcpClient.state
TextBox1.Text = SConst(st)

Now Im using vb.net and want to do something same.
But there is no .state method now for TcpClient objects!
There is only cpClient.Connected but it returns Boolean so only yes or not. How can I do it alike VB6.0?

Using Visual Vinsent's answer I made this:

Public Class Form1
    Dim status1 As String
    Dim status2 As String

Private Sub Btn_Connect5001_Click(sender As Object, e As EventArgs)_
                   Handles Btn_Connect5001.Click
        ' Create TcpClient and Connect to
        tcpclnt2 = New TcpClient
        Try
            tcpclnt2.Connect("192.168.1.177", 5001)
        Catch
        End Try
    End Sub

    Private Sub Btn_Disconnect5001_Click(sender As Object, e As EventArgs)_
                     Handles Btn_Disconnect5001.Click
        ' Close TcpClient
        tcpclnt2.Close()
    End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        ' Check status every 300ms
        status2= New IPEndPoint(IPAddress.Parse("192.168.1.177"),5001).GetStatus().ToString()

        TextBox1.Text = Dns.GetHostName + Environment.NewLine +
             "port 1  " + status2 + Environment.NewLine
    End Sub
End Class

The problem is: At start status2 is "Unknown", if I connect for the first time status2 is "Established". If I disconnect it became "TimeWait". But If I connect one more time it stay "TimeWait". It never change its value then.

Body:
Neither the TcpClient nor its underlying Socket appears to have such an implementation, so I wrote three extension methods which will get that for you.

What they do is that they iterate every active TCP connection on the computer using the IPGlobalProperties class and its GetActiveTcpConnections() method, then they match your connection against the TcpClient's local and remote IP-address.

Extensions.vb

Imports System.Runtime.CompilerServices
Imports System.Reflection
Imports System.Net
Imports System.Net.Sockets
Imports System.Net.NetworkInformation

Public Module Extensions
    ''' <summary>
    ''' Dynamically gets an object's property by name.
    ''' </summary>
    ''' <param name="Obj">The object which's property to get.</param>
    ''' <param name="PropertyName">The name of the property to get.</param>
    <Extension()> _
    Public Function GetProperty(ByVal Obj As Object, ByVal PropertyName As String) As Object
        Return Obj.GetType().InvokeMember(PropertyName, _
                                           BindingFlags.GetProperty _
                                            Or BindingFlags.IgnoreCase _
                                             Or BindingFlags.Public _
                                              Or BindingFlags.NonPublic _
                                               Or BindingFlags.Instance _
                                                Or BindingFlags.Static, _
                                           Nothing, Obj, Nothing)
    End Function

    ''' <summary>
    ''' Gets the status of a TCP connection.
    ''' </summary>
    ''' <param name="Client">The TcpClient which's status to get.</param>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function GetStatus(ByVal Client As TcpClient) As TcpState
        If Client Is Nothing OrElse Client.Client Is Nothing Then Return TcpState.Unknown
        For Each TcpConnection As TcpConnectionInformation In IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections()

            If TcpConnection.LocalEndPoint.Equals(Client.Client.LocalEndPoint) AndAlso _
                 TcpConnection.RemoteEndPoint.Equals(Client.Client.RemoteEndPoint) Then
                Return TcpConnection.State
            End If

        Next
        Return TcpState.Unknown
    End Function

    ''' <summary>
    ''' Gets the status of a TCP connection.
    ''' </summary>
    ''' <param name="EndPoint">The IPEndPoint (IP-address) of the TCP connection which's status to get.</param>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function GetStatus(ByVal EndPoint As IPEndPoint) As TcpState
        If EndPoint Is Nothing Then Return TcpState.Unknown
        For Each TcpConnection As TcpConnectionInformation In IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections()

            If TcpConnection.LocalEndPoint.Equals(EndPoint) OrElse _
                 TcpConnection.RemoteEndPoint.Equals(EndPoint) Then
                Return TcpConnection.State
            End If

        Next
        Return TcpState.Unknown
    End Function

    ''' <summary>
    ''' Gets the status of a TCP listener.
    ''' </summary>
    ''' <param name="Listener">The TcpListener which's status to get.</param>
    ''' <remarks></remarks>
    <Extension()> _
    Public Function GetStatus(ByVal Listener As TcpListener) As TcpState
        If Listener Is Nothing OrElse Listener.Server Is Nothing Then Return TcpState.Unknown

        'Per the source code, active listeners will always be in the "Listen" state:
        'https://referencesource.microsoft.com/#System/net/System/Net/NetworkInformation/SystemIPGlobalProperties.cs,51fa569e558be704
        If Listener.GetProperty("Active") = True Then Return TcpState.Listen

        Return DirectCast(Listener.LocalEndpoint, IPEndPoint).GetStatus() 'The listener is not in an active state.
    End Function
End Module

Now to get the status of a connection you have three options:

Getting the status of a TcpClient:

Dim Status As String = yourClient.GetStatus().ToString()

Getting the status of a TcpListener:

Dim Status As String = yourListener.GetStatus().ToString()

Getting the status of a connection with the specified IP-address:

Dim Status As String = New IPEndPoint(IPAddress.Parse("your IP-address here"), yourPortHere).GetStatus().ToString()

Important notes:

The ToString() call is necessary if you want the status's name (for example Established), otherwise you'll get its enumeration value which is just a normal Integer (for example 3).

Getting the status of a TcpClient or TcpListener will only work if neither they nor their underlying Sockets are disposed. If you wish to get the status of a disconnected TcpClient/-Listener you have to use option no. 3 and get it by its exact IP-address and port.

Disconnected TCP connections can actually be interesting as well because they still exist after being closed and have a state for a little while. Examples of disconnected states are CloseWait or TimeWait.

Read more:

IPGlobalProperties Class - MSDN

IPGlobalProperties.GetActiveTcpConnections() Method - MSDN

System.Net.NetworkInformation Namespace - MSDN

TCP Protocol Operation - Wikipedia (a list of the different TCP connection states)

EDIT:

To fix the problem with connections lingering in a CLOSE_WAIT or TIME_WAIT state you can set the underlying Socket to linger for 0 seconds and then dispose it. Doing so will cause the socket to perform a so-called "hard close" by sending an RST (reset) packet instead of FIN (FIN is what tells a socket that the connection is closed and that it should go into CLOSE-/TIME_WAIT). This method forces the connection to close and no late/retransmitted packets will be mapped to your application after that.

It's actually mentioned on the MSDN documentation:

If the l_onoff member of the linger structure is nonzero and l_linger member is zero, closesocket is not blocked even if queued data has not yet been sent or acknowledged. This is called a hard or abortive close, because the socket's virtual circuit is reset immediately, and any unsent data is lost. On Windows, any recv call on the remote side of the circuit will fail with WSAECONNRESET.

This can be done in a simple extension method (put this in the Extensions module):

''' <summary>
''' Forces the specified TcpClient to close without sending FIN to the other endpoint. This will stop the connection from going into a TIME_WAIT, CLOSE_WAIT or FIN_* state.
''' </summary>
''' <param name="Client">The TcpClient to close.</param>
''' <remarks></remarks>
<Extension()> _
Public Sub ForceClose(ByVal Client As TcpClient)
    Client.Client.LingerState = New LingerOption(True, 0) 'Set the socket to linger, but for 0 seconds (causes the current connection to send an RST-packet and terminate).
    Client.Client.Dispose() 'Dispose the underlying socket instead of a graceful shutdown.
    Client.Close() 'Close the TcpClient.
End Sub

Then just call it like this:

yourClient.ForceClose()


问:
Date Mask Inout as MM/DD/YYYY Using Javascript No jquery
I try to have a Date Mask as MM/DD/YYYY appear as soon as user click on a textbox using only JavaScript or Typescript with using jQuery or any template. I have this JavaScript code:

function DateFormat() {
var date = this.value;
if (date.match(/^\d{4}$/) !== null) {
    this.value = date + '-';
} else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
    this.value = date + '-';
}
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" onclick="DateFormat();"></code>```

but I am getting this error:

Cannot read property 'match' of undefined

I would like to mask appeard like --/--/--when I click on the text box.

答:
The problem is that "this" isn't set to the input in the function, so this.value doesn't refer to anything. Try the following:

function DateFormat(input) {
    var date = input.value;
    if (date.match(/^\d{4}$/) !== null) {
        input.value = date + '-';
    } else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
        input.value = date + '-';
    }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" onclick="DateFormat(this);"></code>```

Body:
I try to have a Date Mask as MM/DD/YYYY appear as soon as user click on a textbox using only JavaScript or Typescript with using jQuery or any template. I have this JavaScript code:

function DateFormat() {
var date = this.value;
if (date.match(/^\d{4}$/) !== null) {
    this.value = date + '-';
} else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
    this.value = date + '-';
}
 }

<input type="text" onclick="DateFormat();">

but I am getting this error:

Cannot read property 'match' of undefined

I would like to mask appeard like --/--/--when I click on the text box.

Body:
The problem is that "this" isn't set to the input in the function, so this.value doesn't refer to anything. Try the following:

function DateFormat(input) {
    var date = input.value;
    if (date.match(/^\d{4}$/) !== null) {
        input.value = date + '-';
    } else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
        input.value = date + '-';
    }
 }

<input type="text" onclick="DateFormat(this);">


问:
listen called on socket more than once -- expected behavior?
I noticed something odd while working with a simple C-based server
program on my Linux (4.10.3) system. I accidentally ended up calling
listen() twice on a socket (from the server process) I had
called bind() on earlier. I noticed that both the listen calls
succeeded without any errors. In fact, it doesn't seem to matter how many
calls to listen I make, all calls to listen succeed.

I was expecting all the calls to listen after the first one to fail
with EADDRINUSE. Am I missing something? Linux/POSIX man pages don't
seem to say anything about this. I did find one reference about
this behavior on the following web-page:

https://www.mkssoftware.com/docs/man3/listen.3.asp

An application may call listen() more than once on the same socket.
  This has the effect of updating the current backlog for the listening
  socket. Should there be more pending connections than the new backlog
  value, the excess pending connections are reset and dropped.

It's unclear to me if this also applies to Linux. And so my question is:
what happens when listen is called on the same socket more than once from
the same process? (Apparently there are no visible side-effects in user space,
but does the Linux kernel do something special in kernel space?)

Thanks.

答:
The Linux kernel adjusts the backlog queue length using the new backlog value, but only for future connection requests. It does not discard any pending connections already in the queue.

Second and subsequent calls to listen() have no other effect, and will not fail unless the socket is of the wrong type (not SOCK_STREAM), or is in the wrong state (already connected to a specific peer, or is already in the process of being closed).


问:
How do I make a scanner for a char array?
Like how do I make it so that the user can input the values for a char array?

Here's my attempt at trying to make it, but got a syntax error:

```<code>    char [] bacteriaStrand = new char[9];
    String bacteria = bac.next();
    bacteriaStrand = bacteria;
</code>```

Here's my entire code so far:

```<code>import java.util.Scanner;
public class SodiknBrukDNAAnalysispt3v1
{
    public static void main(String[] args)
    {
        Scanner bac = new Scanner(System.in);
        char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
        char [] bacteriaStrand = new char[9];
        char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
        System.out.println("NIH Treatment Splicer v. 1");
        System.out.println(" ");
        System.out.print("Treatment Strand: ");
        for (int t = 0; t < treatmentStrand.length; t++)
        {
            System.out.print(treatmentStrand[t]);
        }
        System.out.println(" ");
        System.out.print("Bacterium Strand: ");
        String bacteria = bac.next();
        bacteriaStrand = bacteria;
        for (int b = 0; b < bacteriaStrand.length; b++)
        {
            System.out.print(bacteriaStrand[b]);
            if (bacteriaStrand[b] != 'A' || bacteriaStrand[b] !='C' || bacteriaStrand[b] !='T' || bacteriaStrand[b] !='G')
            {
                System.out.println("Error! You can only input capital A, C, T, and G.");
            }
        }
    }
}
</code>```

答:
Here is an a solution that will work.

Using the suggestions from above (toCharArray).
I have also added List of allowedCharacters for easier comparisons and ensuring the length is 9 before processing it.

You might also want to do to ignore cases.

```<code>bacteria.toUpperCase().toCharArray();
</code>```

This will help

```<code>public class SodiknBrukDNAAnalysispt3v1 {
    public static void main(String[] args) {
        Scanner bac = new Scanner(System.in);
        char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
        char [] bacteriaStrand = new char[9];
        char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
        System.out.println("NIH Treatment Splicer v. 1");
        System.out.println(" ");
        System.out.print("Treatment Strand: ");
        for (int t = 0; t < treatmentStrand.length; t++)
        {
            System.out.print(treatmentStrand[t]);
        }
        System.out.println(" ");
        System.out.print("Bacterium Strand: ");
        String bacteria = bac.next();
        if (bacteria.length() != 9) {
            System.out.println("Error! You are expected to input 9 characters");
            return ;
        }
        bacteriaStrand = bacteria.toCharArray();
        List<Character> allowedCharacters = Arrays.asList('A', 'C', 'T', 'G');
        for (int b = 0; b < bacteriaStrand.length; b++) {
            System.out.print(bacteriaStrand[b]);
            if (!allowedCharacters.contains(bacteriaStrand[b])) {
                System.out.println("Error! You can only input capital A, C, T, and G.");
                return;
            }
        }
    }
}
</code>```

Body:
Like how do I make it so that the user can input the values for a char array?

Here's my attempt at trying to make it, but got a syntax error:

    char [] bacteriaStrand = new char[9];
    String bacteria = bac.next();
    bacteriaStrand = bacteria;

Here's my entire code so far:

import java.util.Scanner;
public class SodiknBrukDNAAnalysispt3v1
{
    public static void main(String[] args)
    {
        Scanner bac = new Scanner(System.in);
        char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
        char [] bacteriaStrand = new char[9];
        char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
        System.out.println("NIH Treatment Splicer v. 1");
        System.out.println(" ");
        System.out.print("Treatment Strand: ");
        for (int t = 0; t < treatmentStrand.length; t++)
        {
            System.out.print(treatmentStrand[t]);
        }
        System.out.println(" ");
        System.out.print("Bacterium Strand: ");
        String bacteria = bac.next();
        bacteriaStrand = bacteria;
        for (int b = 0; b < bacteriaStrand.length; b++)
        {
            System.out.print(bacteriaStrand[b]);
            if (bacteriaStrand[b] != 'A' || bacteriaStrand[b] !='C' || bacteriaStrand[b] !='T' || bacteriaStrand[b] !='G')
            {
                System.out.println("Error! You can only input capital A, C, T, and G.");
            }
        }
    }
}

Body:
Here is an a solution that will work.

Using the suggestions from above (toCharArray).
I have also added List of allowedCharacters for easier comparisons and ensuring the length is 9 before processing it.

You might also want to do to ignore cases.

bacteria.toUpperCase().toCharArray();

This will help

public class SodiknBrukDNAAnalysispt3v1 {
    public static void main(String[] args) {
        Scanner bac = new Scanner(System.in);
        char [] treatmentStrand = {'T','C','G','A','G','A','G','T','A','T','C','C','C','A','G'};
        char [] bacteriaStrand = new char[9];
        char [] splicedStrand = new char[treatmentStrand.length + bacteriaStrand.length];
        System.out.println("NIH Treatment Splicer v. 1");
        System.out.println(" ");
        System.out.print("Treatment Strand: ");
        for (int t = 0; t < treatmentStrand.length; t++)
        {
            System.out.print(treatmentStrand[t]);
        }
        System.out.println(" ");
        System.out.print("Bacterium Strand: ");
        String bacteria = bac.next();
        if (bacteria.length() != 9) {
            System.out.println("Error! You are expected to input 9 characters");
            return ;
        }
        bacteriaStrand = bacteria.toCharArray();
        List<Character> allowedCharacters = Arrays.asList('A', 'C', 'T', 'G');
        for (int b = 0; b < bacteriaStrand.length; b++) {
            System.out.print(bacteriaStrand[b]);
            if (!allowedCharacters.contains(bacteriaStrand[b])) {
                System.out.println("Error! You can only input capital A, C, T, and G.");
                return;
            }
        }
    }
}