问:
concat 2 observable, and get booth their value in the same time
Let's say I have the following : https://stackblitz.com/edit/concat

```<code>import {concat} from "rxjs/observable/concat";
import {fullObserver, stream} from "./utils";

const a = stream('a', 200, 3, 'partial');
const b = stream('b', 200, 3, 'partial');
concat(a, b).subscribe(fullObserver('concat'));
</code>```

This will, subscribe to a, give me the result of a, then subscribe to b, and get the b result.

but, how do I do the follow,

```<code>subscribe to a => a complete
subscribe to b => b complete
get the result of a and b in an array like when booth are completed
</code>```

its like a forkJoin but with a concat, so that all subscription are sequential. How could I do ?

答:
There's toArray() operator that will collect all next notifications and re-emit them in a single array after its source completes (concat will complete after all its source complete).

So in your case it will look like this:

```<code>concat(a, b).pipe(toArray()).subscribe(fullObserver('concat'));
</code>```

Btw, you don't need to be importing "creation operators" such as concat or timer from rxjs/observable/* and you import them from just rxjs.

Body:
Let's say I have the following : https://stackblitz.com/edit/concat

import {concat} from "rxjs/observable/concat";
import {fullObserver, stream} from "./utils";

const a = stream('a', 200, 3, 'partial');
const b = stream('b', 200, 3, 'partial');
concat(a, b).subscribe(fullObserver('concat'));

This will, subscribe to a, give me the result of a, then subscribe to b, and get the b result.

but, how do I do the follow,

subscribe to a => a complete
subscribe to b => b complete
get the result of a and b in an array like when booth are completed

its like a forkJoin but with a concat, so that all subscription are sequential. How could I do ?

Body:
There's toArray() operator that will collect all next notifications and re-emit them in a single array after its source completes (concat will complete after all its source complete).

So in your case it will look like this:

concat(a, b).pipe(toArray()).subscribe(fullObserver('concat'));

Btw, you don't need to be importing "creation operators" such as concat or timer from rxjs/observable/* and you import them from just rxjs.


来源: stackexchange

问:
Why I got many NAs when I try to make subset dataframe
I have dataset as below

df<-data.frame(name=c("alicia","samantha","john","jessie"), age=c(40,-23,30,28), income=c(100, 50, 120,60))

What I am trying to do is to select dataset which does not have negative value and values less than 100.
I've tried

df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]

But I could not delete the values which is greater than 100 and I got many 'NA's, as below.

```<code> #       name age income
 # 1    alicia  40    100
 # 3      john  30    120
 # 4    jessie  28     60
 # NA     <NA>  NA     NA
 # NA.1   <NA>  NA     NA
 # NA.2   <NA>  NA     NA
</code>```

I found the way to delete negative and 100 above values by using apply and subset functions.

My question is why I got additional lines with NAs with my code  df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]  ?

答:
You can add rowSums in your subsetting to get what you want as in your case you get a matrix to use for substting and not a vector:

```<code>df[rowSums(df[,c(2:3)]>=0&df[,(2:3)]<=100) == 2,]
#    name age income
#1 alicia  40    100
#4 jessie  28     60
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have dataset as below

df<-data.frame(name=c("alicia","samantha","john","jessie"), age=c(40,-23,30,28), income=c(100, 50, 120,60))

What I am trying to do is to select dataset which does not have negative value and values less than 100.
I've tried

df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]

But I could not delete the values which is greater than 100 and I got many 'NA's, as below.

 #       name age income
 # 1    alicia  40    100
 # 3      john  30    120
 # 4    jessie  28     60
 # NA     <NA>  NA     NA
 # NA.1   <NA>  NA     NA
 # NA.2   <NA>  NA     NA

I found the way to delete negative and 100 above values by using apply and subset functions.

My question is why I got additional lines with NAs with my code  df[(df[,c(2:3)]>=0&df[,(2:3)]<=100),]  ?

Body:
You can add rowSums in your subsetting to get what you want as in your case you get a matrix to use for substting and not a vector:

df[rowSums(df[,c(2:3)]>=0&df[,(2:3)]<=100) == 2,]
#    name age income
#1 alicia  40    100
#4 jessie  28     60


问:
Access ngForm of parent in child
I have a structure like this:

<form #myForm="ngForm">

    <app-section-a [myForm]="myForm"></app-section-a>
```

<p>and my child component:</p>

<pre class="lang-js prettyprint-override"><code>@Component({
...
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
// ...
@Input() myForm: ElementRef;
</code>```

<input ...>
<button type=submit [disabled]="!myForm.valid">
```

and, this works perfectly to ensure that all the components in the form are counted for validity. The thing is, I don't think I should need to pass the reference to ngForm directly as an input. How do I skip that input and still make this work?

a detail: happens to be an angular 5 project.

答:
Complete working example in this StackBlitz Link.

First of all you do not need to pass ngForm to child component at all. Because you can tell child component is part of parent form group using ControlContainer and NgForm by providing to child-component providers array.

In this example one parent component app.component is loading child component with *ngFor and we just added ControlContainer to providers array of child component. Here, we just need to give different name for each child-component dynamically, for this purpose we need to pass index as @Input() to child component and assign it to name property of inputField.

If any of inputControl has error then, submit button of parent control is disabled.

app.component.html is...

```<code><form #heroForm="ngForm" class="container">
   <div id="parent" *ngFor="let i of [0,1,2]"  >
      <app-child [id]="i+1" [name]="i+1" ></app-child>
   </div>
  <hr>
    {{heroForm.value | json}}
  <hr>
  <div>
     <app-button-submit></app-button-submit>
  </div>
</form>
</code>```

app-button-submit.html

```<code><button type="submit" class="btn btn-success"
  [disabled]="!control.form.valid">Submit</button>
</code>```

We are binding, ControlContainer directly to [disabled] state of button with dependency injection.. see below constructor() class file.

app-button-submit.ts

```<code>import {ControlContainer, NgForm} from '@angular/forms';

@Component({
   selector: 'app-button-submit',
   templateUrl: './button-submit.component.html',
   styleUrls: ['./button-submit.component.css'],
   providers : [{provide : ControlContainer, useExisting : NgForm}]
})
export class ButtonSubmitComponent  {
   constructor(private control : NgForm) { }
}
</code>```

child-component.html

```<code><div class="form-group" >
   <label [for]="Name">Name</label>
      <input type="text"  class="form-control"  [id]="id" required [(ngModel)]="vname" [name]="Name"  #names="ngModel">
        {{vname}}
   <div [hidden]="names.valid || names.pristine" class="alert alert-danger">
      Name is required
   </div>
</div>
</code>```

child.component.ts

```<code>import {ControlContainer, NgForm} from '@angular/forms';

@Component({
   ---,
   viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
 export class ChildComponent implements OnInit {
   @Input('id') id;
   @Input ('name') Name;
 }
</code>```

here, ControlContainer will take care of binding of NgForm of Parent-Component to Child-Component.

Title: Access ngForm of parent in child

Body:
I have a structure like this:

<form #myForm="ngForm">

    <app-section-a [myForm]="myForm"></app-section-a>

and my child component:

@Component({
...
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
// ...
@Input() myForm: ElementRef;

<input ...>
<button type=submit [disabled]="!myForm.valid">

and, this works perfectly to ensure that all the components in the form are counted for validity. The thing is, I don't think I should need to pass the reference to ngForm directly as an input. How do I skip that input and still make this work?

a detail: happens to be an angular 5 project.

Body:
Complete working example in this StackBlitz Link.

First of all you do not need to pass ngForm to child component at all. Because you can tell child component is part of parent form group using ControlContainer and NgForm by providing to child-component providers array.

In this example one parent component app.component is loading child component with *ngFor and we just added ControlContainer to providers array of child component. Here, we just need to give different name for each child-component dynamically, for this purpose we need to pass index as @Input() to child component and assign it to name property of inputField.

If any of inputControl has error then, submit button of parent control is disabled.

app.component.html is...

<form #heroForm="ngForm" class="container">
   <div id="parent" *ngFor="let i of [0,1,2]"  >
      <app-child [id]="i+1" [name]="i+1" ></app-child>
   </div>
  <hr>
    {{heroForm.value | json}}
  <hr>
  <div>
     <app-button-submit></app-button-submit>
  </div>
</form>

app-button-submit.html

<button type="submit" class="btn btn-success"
  [disabled]="!control.form.valid">Submit</button>

We are binding, ControlContainer directly to [disabled] state of button with dependency injection.. see below constructor() class file.

app-button-submit.ts

import {ControlContainer, NgForm} from '@angular/forms';

@Component({
   selector: 'app-button-submit',
   templateUrl: './button-submit.component.html',
   styleUrls: ['./button-submit.component.css'],
   providers : [{provide : ControlContainer, useExisting : NgForm}]
})
export class ButtonSubmitComponent  {
   constructor(private control : NgForm) { }
}

child-component.html

<div class="form-group" >
   <label [for]="Name">Name</label>
      <input type="text"  class="form-control"  [id]="id" required [(ngModel)]="vname" [name]="Name"  #names="ngModel">
        {{vname}}
   <div [hidden]="names.valid || names.pristine" class="alert alert-danger">
      Name is required
   </div>
</div>

child.component.ts

import {ControlContainer, NgForm} from '@angular/forms';

@Component({
   ---,
   viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
 export class ChildComponent implements OnInit {
   @Input('id') id;
   @Input ('name') Name;
 }

here, ControlContainer will take care of binding of NgForm of Parent-Component to Child-Component.


问:
How to use XOR to develop a OTPInputStream in Java
I want to develop a OTPInputStream in Java that extends the InputStream and takes another input stream of key data and provides a stream encrypting / decrypting input stream.I need to develop a test program to show the use of OTPInputStream that uses XOR and arbitrary data.

I tried with this code but I have problem that is

java.io.FileInputStream cannot be cast to java.lang.CharSequence

What should I do here?

```<code>public class Bitwise_Encryption {

    static String file = "" ;
    static String key = "VFGHTrbg";

    private static int[] encrypt(FileInputStream file, String key) {
        int[] output = new int[((CharSequence) file).length()];
        for(int i = 0; i < ((CharSequence) file).length(); i++) {
            int o = (Integer.valueOf(((CharSequence) file).charAt(i)) ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
            output[i] = o;
        }
        return output;
    }

    private static String decrypt(int[] input, String key) {
        String output = "";
        for(int i = 0; i < input.length; i++) {
            output += (char) ((input[i] - 48) ^ (int) key.charAt(i % (key.length() - 1)));
        }
        return output;
    }

    public static void main(String args[]) throws FileNotFoundException {
        FileInputStream file = new FileInputStream("directory");

        encrypt(file,key);
        //decrypt();
        int[] encrypted = encrypt(file,key);

        System.out.println("Encrypted Data is :");
        for(int i = 0; i < encrypted.length; i++)
            System.out.printf("%d,", encrypted[i]);

        System.out.println("");
        System.out.println("---------------------------------------------------");
        System.out.println("Decrypted Data is :");
        System.out.println(decrypt(encrypted,key));

    }
}
</code>```

答:
Think what you want is just file.read() and file.getChannel().size() to read one character at a time and get the size of the file

Try something like this:

```<code>private static int[] encrypt(FileInputStream file, String key) {
  int fileSize = file.getChannel().size();
  int[] output = new int[fileSize];
  for(int i = 0; i < output.length; i++) {
    char char1 = (char) file.read();
    int o = (char1 ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
    output[i] = o;
  }
  return output;
}
</code>```

Will have to do some error handling because file.read() will return -1 if the end of the file has been reached and as pointed out reading one byte at a time is lot of IO operations and can slow down performance. You can keep the data in a buffer and read it another way like this:

```<code>private static int[] encrypt(FileInputStream file, String key) {
  int fileSize = file.getChannel().size();
  int[] output = new int[fileSize];

  int read = 0;
  int offset = 0;
  byte[] buffer = new byte[1024];
  while((read = file.read(buffer)) > 0) {
    for(int i = 0; i < read; i++) {
      char char1 = (char) buffer[i];
      int o = (char1 ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
      output[i + offset] = o;
    }
    offset += read;
  }
  return output;
}
</code>```

This will read in 1024 bytes at a time from the file and store it in your buffer, then you can loop through the buffer to do your logic. The offset value is to store where in our output the current spot is. Also you will have to make sure that i + offset doesn't exceed your array size.

UPDATE

After working with it; i decided to switch to Base64 Encoding/Decoding to remove non-printable characters:

```<code>  private static String encrypt(InputStream file, String key) throws Exception {
    int read = 0;
    byte[] buffer = new byte[1024];
    try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
      while((read = file.read(buffer)) > 0) {
        baos.write(buffer, 0, read);
      }
      return base64Encode(xorWithKey(baos.toByteArray(), key.getBytes()));
    }
  }

  private static String decrypt(String input, String key) {
    byte[] decoded = base64Decode(input);
    return new String(xorWithKey(decoded, key.getBytes()));
  }

  private static byte[] xorWithKey(byte[] a, byte[] key) {
    byte[] out = new byte[a.length];
    for (int i = 0; i < a.length; i++) {
      out[i] = (byte) (a[i] ^ key[i%key.length]);
    }
    return out;
  }

  private static byte[] base64Decode(String s) {
    return Base64.getDecoder().decode(s.trim());
  }

  private static String base64Encode(byte[] bytes) {
    return Base64.getEncoder().encodeToString(bytes);
  }
</code>```

This method is cleaner and doesn't require knowing the size of your InputStream or do any character conversions. It reads your InputStream into an OutputStream to do the Base64 Encoding as well to remove non printable characters.

I have tested this and it works both for encrypting and decrypting.

I got the idea from this answer:

XOR operation with two strings in java

Body:
I want to develop a OTPInputStream in Java that extends the InputStream and takes another input stream of key data and provides a stream encrypting / decrypting input stream.I need to develop a test program to show the use of OTPInputStream that uses XOR and arbitrary data.

I tried with this code but I have problem that is

java.io.FileInputStream cannot be cast to java.lang.CharSequence

What should I do here?

public class Bitwise_Encryption {

    static String file = "" ;
    static String key = "VFGHTrbg";

    private static int[] encrypt(FileInputStream file, String key) {
        int[] output = new int[((CharSequence) file).length()];
        for(int i = 0; i < ((CharSequence) file).length(); i++) {
            int o = (Integer.valueOf(((CharSequence) file).charAt(i)) ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
            output[i] = o;
        }
        return output;
    }

    private static String decrypt(int[] input, String key) {
        String output = "";
        for(int i = 0; i < input.length; i++) {
            output += (char) ((input[i] - 48) ^ (int) key.charAt(i % (key.length() - 1)));
        }
        return output;
    }

    public static void main(String args[]) throws FileNotFoundException {
        FileInputStream file = new FileInputStream("directory");

        encrypt(file,key);
        //decrypt();
        int[] encrypted = encrypt(file,key);

        System.out.println("Encrypted Data is :");
        for(int i = 0; i < encrypted.length; i++)
            System.out.printf("%d,", encrypted[i]);

        System.out.println("");
        System.out.println("---------------------------------------------------");
        System.out.println("Decrypted Data is :");
        System.out.println(decrypt(encrypted,key));

    }
}

Body:
Think what you want is just file.read() and file.getChannel().size() to read one character at a time and get the size of the file

Try something like this:

private static int[] encrypt(FileInputStream file, String key) {
  int fileSize = file.getChannel().size();
  int[] output = new int[fileSize];
  for(int i = 0; i < output.length; i++) {
    char char1 = (char) file.read();
    int o = (char1 ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
    output[i] = o;
  }
  return output;
}

Will have to do some error handling because file.read() will return -1 if the end of the file has been reached and as pointed out reading one byte at a time is lot of IO operations and can slow down performance. You can keep the data in a buffer and read it another way like this:

private static int[] encrypt(FileInputStream file, String key) {
  int fileSize = file.getChannel().size();
  int[] output = new int[fileSize];

  int read = 0;
  int offset = 0;
  byte[] buffer = new byte[1024];
  while((read = file.read(buffer)) > 0) {
    for(int i = 0; i < read; i++) {
      char char1 = (char) buffer[i];
      int o = (char1 ^ Integer.valueOf(key.charAt(i % (key.length() - 1)))) + '0';
      output[i + offset] = o;
    }
    offset += read;
  }
  return output;
}

This will read in 1024 bytes at a time from the file and store it in your buffer, then you can loop through the buffer to do your logic. The offset value is to store where in our output the current spot is. Also you will have to make sure that i + offset doesn't exceed your array size.

UPDATE

After working with it; i decided to switch to Base64 Encoding/Decoding to remove non-printable characters:

  private static String encrypt(InputStream file, String key) throws Exception {
    int read = 0;
    byte[] buffer = new byte[1024];
    try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
      while((read = file.read(buffer)) > 0) {
        baos.write(buffer, 0, read);
      }
      return base64Encode(xorWithKey(baos.toByteArray(), key.getBytes()));
    }
  }

  private static String decrypt(String input, String key) {
    byte[] decoded = base64Decode(input);
    return new String(xorWithKey(decoded, key.getBytes()));
  }

  private static byte[] xorWithKey(byte[] a, byte[] key) {
    byte[] out = new byte[a.length];
    for (int i = 0; i < a.length; i++) {
      out[i] = (byte) (a[i] ^ key[i%key.length]);
    }
    return out;
  }

  private static byte[] base64Decode(String s) {
    return Base64.getDecoder().decode(s.trim());
  }

  private static String base64Encode(byte[] bytes) {
    return Base64.getEncoder().encodeToString(bytes);
  }

This method is cleaner and doesn't require knowing the size of your InputStream or do any character conversions. It reads your InputStream into an OutputStream to do the Base64 Encoding as well to remove non printable characters.

I have tested this and it works both for encrypting and decrypting.

I got the idea from this answer:

XOR operation with two strings in java


问:
I am trying to display data using fetch api but It doesn't display anything
```<code> window.addEventListener('load',()=>{
     let dTitle = document.getElementById('display');
     let dDescription = document.getElementById('description');
     const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
     fetch(api).then(response=>{
       return response.json();
     })
     .then(data=>{
       console.log(data);
       const{title,description}=data.articles;
       //set dom elements
       dTitle.textContent=data.title;
       dDescription.textContent=data.description;
    })
});
</code>```

dTitle, dDescription is not displayed in html tag.
I am new to JavaScript. Please help me.

答:
Try using innerText property. As using innerHTML is susceptible to XSS attacks

```<code>dTitle.innerText = title;
dDescription.innerText = description;
</code>```

    window.addEventListener('load',()=>{
                 let dTitle = document.getElementById('display');
                 let dDescription = document.getElementById('description');
                 const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
                 fetch(api).then(response=>{
                   return response.json();
                 })
                 .then(data=>{
                   console.log(data);
                   const{title,description} = data.articles[0];
                   //set dom elements
                   dTitle.innerText = title;
                   dDescription.innerText= description;
               })
        }); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 id="display"></h2>

<p id="description"></p></code>```

Body:
 window.addEventListener('load',()=>{
     let dTitle = document.getElementById('display');
     let dDescription = document.getElementById('description');
     const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
     fetch(api).then(response=>{
       return response.json();
     })
     .then(data=>{
       console.log(data);
       const{title,description}=data.articles;
       //set dom elements
       dTitle.textContent=data.title;
       dDescription.textContent=data.description;
    })
});

dTitle, dDescription is not displayed in html tag.
I am new to JavaScript. Please help me.

Body:
Try using innerText property. As using innerHTML is susceptible to XSS attacks

dTitle.innerText = title;
dDescription.innerText = description;

    window.addEventListener('load',()=>{
                 let dTitle = document.getElementById('display');
                 let dDescription = document.getElementById('description');
                 const api = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=520bf969179e416aa2c3608591647a76';
                 fetch(api).then(response=>{
                   return response.json();
                 })
                 .then(data=>{
                   console.log(data);
                   const{title,description} = data.articles[0];
                   //set dom elements
                   dTitle.innerText = title;
                   dDescription.innerText= description;
               })
        });

<h2 id="display"></h2>

<p id="description"></p>


问:
Python tkinter : Input text box displaying as a number
This is a part of my ordering program school project. Every time I input something into the entry widget, a random number is dispalyed

```<code>import tkinter
def doneEditing(e1):
    print(e1)

root = tkinter.Tk()
root.minsize(width=800, height=428)
root.maxsize(width=800, height=428)

itemAdded = tkinter.Canvas(root, width = 400, height = 300)
itemAdded.pack()

e1 = tkinter.Entry(root)

itemAdded.create_window(200, 140, window=e1)

done = tkinter.Button(root, text = 'ENTER', command=lambda: doneEditing(e1))
done.place(x=80, y=90 ,width=120 ,height=26, anchor = 's')

root.mainloop()

</code>```

output = .60223280

答:
You should change doneEditing into :

```<code>def doneEditing(e1):
    print(e1.get())
</code>```

In order to get value inside entry box, you need to use get() method.

Further read : https://effbot.org/tkinterbook/entry.htm

Body:
This is a part of my ordering program school project. Every time I input something into the entry widget, a random number is dispalyed

import tkinter
def doneEditing(e1):
    print(e1)

root = tkinter.Tk()
root.minsize(width=800, height=428)
root.maxsize(width=800, height=428)

itemAdded = tkinter.Canvas(root, width = 400, height = 300)
itemAdded.pack()

e1 = tkinter.Entry(root)

itemAdded.create_window(200, 140, window=e1)

done = tkinter.Button(root, text = 'ENTER', command=lambda: doneEditing(e1))
done.place(x=80, y=90 ,width=120 ,height=26, anchor = 's')

root.mainloop()

output = .60223280

Body:
You should change doneEditing into :

def doneEditing(e1):
    print(e1.get())

In order to get value inside entry box, you need to use get() method.

Further read : https://effbot.org/tkinterbook/entry.htm


答:
Break your problem into smaller steps to understand what is happening -

```<code>#1)
df[,c(2:3)] >= 0

#      age income
#[1,]  TRUE   TRUE
#[2,] FALSE   TRUE
#[3,]  TRUE   TRUE
#[4,]  TRUE   TRUE

#2)
df[,(2:3)] <= 100
#      age income
#[1,] TRUE   TRUE
#[2,] TRUE   TRUE
#[3,] TRUE  FALSE
#[4,] TRUE   TRUE

#3)
df[,c(2:3)] >= 0 & df[,(2:3)] <= 100
#      age income
#[1,]  TRUE   TRUE
#[2,] FALSE   TRUE
#[3,]  TRUE  FALSE
#[4,]  TRUE   TRUE
</code>```

Output of 3) is a matrix and now R tries to subset rows where TRUE is present which is row numbers

```<code>which(df[,c(2:3)] >= 0 & df[,(2:3)] <= 100)
#[1] 1 3 4 5 6 8
</code>```

but you have only 4 rows in your dataset so R appends all other rows with greater than 4 with NA

```<code>df[c(1, 3, 4, 5, 6, 8), ]

#       name age income
#1    alicia  40    100
#3      john  30    120
#4    jessie  28     60
#NA     <NA>  NA     NA
#NA.1   <NA>  NA     NA
#NA.2   <NA>  NA     NA
</code>```

Title: Why I got many NAs when I try to make subset dataframe

Body:
Break your problem into smaller steps to understand what is happening -

#1)
df[,c(2:3)] >= 0

#      age income
#[1,]  TRUE   TRUE
#[2,] FALSE   TRUE
#[3,]  TRUE   TRUE
#[4,]  TRUE   TRUE

#2)
df[,(2:3)] <= 100
#      age income
#[1,] TRUE   TRUE
#[2,] TRUE   TRUE
#[3,] TRUE  FALSE
#[4,] TRUE   TRUE

#3)
df[,c(2:3)] >= 0 & df[,(2:3)] <= 100
#      age income
#[1,]  TRUE   TRUE
#[2,] FALSE   TRUE
#[3,]  TRUE  FALSE
#[4,]  TRUE   TRUE

Output of 3) is a matrix and now R tries to subset rows where TRUE is present which is row numbers

which(df[,c(2:3)] >= 0 & df[,(2:3)] <= 100)
#[1] 1 3 4 5 6 8

but you have only 4 rows in your dataset so R appends all other rows with greater than 4 with NA

df[c(1, 3, 4, 5, 6, 8), ]

#       name age income
#1    alicia  40    100
#3      john  30    120
#4    jessie  28     60
#NA     <NA>  NA     NA
#NA.1   <NA>  NA     NA
#NA.2   <NA>  NA     NA


问:
search in sharepoint list using jQuery
I need to implement search in a SharePoint 2013 site home page where in the search results should be probably from a list with list name ListA (with column name Project Name and Project Category).
The search results should only be from the two columns mentioned above.
Once the search results appear, after selecting a particular search result it should re-direct to its particular details page(Projectdetails.aspx)

We're trying to use jQuery/REST API in SharePoint Designer 2013.

Please let me know for any further information.
Thanks in advance!

答:
If you need an Idea to do that, you can do the following:

Create HTML Design in a txt file

This includes creating html for Search input box or any other controls, search button and a div to show search results.

Upload this file somewhere on the site (e.g. Style library/html)

 -

Write Javascript

Write Javascript to perform validation.

Write click event for search button. Use JSOM to retrieve list items based on a CAML Query that takes the input from controls and retrieves list items based on user specified values.

In success handler of your function, retrieve id's for matched items, and use these
id's to create dynamic html to redirect to display form (Details) of the item e.g. ([Item's Title])

Populate the div (that you created in html) with dynamic html (e.g. $('#yourdivid').html(dynamicHTML));

upload this JS file on somewhere on your site (e.g.Style Library/JS)

refer this JS file in your HTML

Create Content Editor Webpart

Go to the page where you want to put your search control and edit the page. Insert a Content editor webpart, and in webpart's configurations, refer the txt (html) file then save the page.
hope this helps

EDIT : To retrieve items from a list using CAML query, you can use JSOM

```<code>function GetSearchResults() {  //search button click handler
// Get textboxes' text.. 'tboxProjectName' and 'tboxProjectCategories' are id's that you assign to textboxes in your html.
var projectNameVal = $('#tboxProjectName').val();
var projectCategoryVal = $('#tboxProjectCategory').val();
//Get SP Context
var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle("ListA");
    var camlQuery = new SP.CamlQuery();
    //you can modify query text according to your data types and applying operators different than <Contains> e.g. <Eq>, <Lt>, <Gt> etc.
    var camlText = '<View><Query><Where><Or><Contains><FieldRef Name="Project_x0020_Name"/><Value Type="Text">' + projectNameVal +'</Value></Contains><Contains><FieldRef Name="Project_x0020_Category"/><Value Type="Text">' + projectCategoryVal +'</Value></Contains></Or></Where></Query></View>';
camlQuery.set_viewXml(camlText);
this.collListItem = list.getItems(camlQuery);
context.load(collListItem);
context.executeQueryAsync(getResultsSuccess,onFailure);
}

function getResultsSuccess() {
    var listItem;
    var html = '';
    var dispFormUrl = "https://yourserver.com/lists/lista/dispform.aspx?ID="
    var listEnumerator = collListItem.getEnumerator();
    while (listEnumerator.moveNext()) {
        listItem = listEnumerator.get_current();
        html += '<a href = "'+dispFormurl+listItem.get_item("ID")+'"><span>'+listItem.get_item("Title")+'</a> <br />'

}
$('#yourdivID').html(html)
    }
function onFailure(sender,args)
{
 alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</code>```

Title: search in sharepoint list using jQuery

Body:
If you need an Idea to do that, you can do the following:

Create HTML Design in a txt file

This includes creating html for Search input box or any other controls, search button and a div to show search results.

Upload this file somewhere on the site (e.g. Style library/html)

 -

Write Javascript

Write Javascript to perform validation.

Write click event for search button. Use JSOM to retrieve list items based on a CAML Query that takes the input from controls and retrieves list items based on user specified values.

In success handler of your function, retrieve id's for matched items, and use these
id's to create dynamic html to redirect to display form (Details) of the item e.g. (<a href="https://serverurl/lists/yourlist/DispForm.aspx?ID=[id-of-matched-item]"><span>[Item's Title]</span></a>)

Populate the div (that you created in html) with dynamic html (e.g. $('#yourdivid').html(dynamicHTML));

upload this JS file on somewhere on your site (e.g.Style Library/JS)

refer this JS file in your HTML

Create Content Editor Webpart

Go to the page where you want to put your search control and edit the page. Insert a Content editor webpart, and in webpart's configurations, refer the txt (html) file then save the page.
hope this helps

EDIT : To retrieve items from a list using CAML query, you can use JSOM

function GetSearchResults() {  //search button click handler
// Get textboxes' text.. 'tboxProjectName' and 'tboxProjectCategories' are id's that you assign to textboxes in your html.
var projectNameVal = $('#tboxProjectName').val();
var projectCategoryVal = $('#tboxProjectCategory').val();
//Get SP Context
var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    var list = web.get_lists().getByTitle("ListA");
    var camlQuery = new SP.CamlQuery();
    //you can modify query text according to your data types and applying operators different than <Contains> e.g. <Eq>, <Lt>, <Gt> etc.
    var camlText = '<View><Query><Where><Or><Contains><FieldRef Name="Project_x0020_Name"/><Value Type="Text">' + projectNameVal +'</Value></Contains><Contains><FieldRef Name="Project_x0020_Category"/><Value Type="Text">' + projectCategoryVal +'</Value></Contains></Or></Where></Query></View>';
camlQuery.set_viewXml(camlText);
this.collListItem = list.getItems(camlQuery);
context.load(collListItem);
context.executeQueryAsync(getResultsSuccess,onFailure);
}

function getResultsSuccess() {
    var listItem;
    var html = '';
    var dispFormUrl = "https://yourserver.com/lists/lista/dispform.aspx?ID="
    var listEnumerator = collListItem.getEnumerator();
    while (listEnumerator.moveNext()) {
        listItem = listEnumerator.get_current();
        html += '<a href = "'+dispFormurl+listItem.get_item("ID")+'"><span>'+listItem.get_item("Title")+'</a> <br />'

}
$('#yourdivID').html(html)
    }
function onFailure(sender,args)
{
 alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


问:
Converting a pandas dataframe to JSON file
I am trying to convert a pandas DataFrame to JSON file. Following image shows my data:
Screenshot of the dataset from Ms. excel

I am using the following code:

```<code>import pandas as pd

os.chdir("G:\\My Drive\\LEC dashboard\\EnergyPlus simulation files\\DEC\\Ahmedabad\\Adaptive set point\\CSV")

df = pd.read_csv('Adap_40-_0_0.1_1.5_0.6.csv')
df2 = df.filter(like = '[C](Hourly)',axis =1)
df3 = df.filter(like = '[C](Hourly:ON)',axis =1)
df4 = df.filter(like = '[%](Hourly)',axis =1)
df5 = df.filter(like = '[%](Hourly:ON)',axis =1)

df6 = pd.concat([df2,df3,df4,df5],axis=1)
df6.to_json("123.json",orient='columns')
</code>```

I the output, I am getting a dictionary in of values. However, I need a list as value.

The output I am getting: The JSON output I am getting by using above code

The out put that is desired: The output that is desired.

I have tried different orientations of json but nothing works.

答:
There might be other ways of doing this but one way is this.

```<code>import json
test = pd.DataFrame({'a':[1,2,3,4,5,6]})
with open('test.json', 'w') as f:
    json.dump(test.to_dict(orient='list'), f)
</code>```

Result file will look like this '{"a": [1, 2, 3, 4, 5, 6]}'

Body:
I am trying to convert a pandas DataFrame to JSON file. Following image shows my data:
Screenshot of the dataset from Ms. excel

I am using the following code:

import pandas as pd

os.chdir("G:\\My Drive\\LEC dashboard\\EnergyPlus simulation files\\DEC\\Ahmedabad\\Adaptive set point\\CSV")

df = pd.read_csv('Adap_40-_0_0.1_1.5_0.6.csv')
df2 = df.filter(like = '[C](Hourly)',axis =1)
df3 = df.filter(like = '[C](Hourly:ON)',axis =1)
df4 = df.filter(like = '[%](Hourly)',axis =1)
df5 = df.filter(like = '[%](Hourly:ON)',axis =1)

df6 = pd.concat([df2,df3,df4,df5],axis=1)
df6.to_json("123.json",orient='columns')

I the output, I am getting a dictionary in of values. However, I need a list as value.

The output I am getting: The JSON output I am getting by using above code

The out put that is desired: The output that is desired.

I have tried different orientations of json but nothing works.

Body:
There might be other ways of doing this but one way is this.

import json
test = pd.DataFrame({'a':[1,2,3,4,5,6]})
with open('test.json', 'w') as f:
    json.dump(test.to_dict(orient='list'), f)

Result file will look like this '{"a": [1, 2, 3, 4, 5, 6]}'


问:
is it possible to reuse TCP port numbers in linux
Is it possible to reuse a listening TCP port in linux in different processes ?

for eg : process A and process B are listening on server=INADDR_ANY and port=10000

if its impossible then how the apache http server is able to listen to port #80  in different process.

Thanks in advance

答:
It is possible to have multiple processes listening on the same port, but as you've seen you cannot do this using distinct sockets, with or without SO_REUSEADDR.

The only way to arrange this is to create the socket, bind() it and call listen(), then duplicate it.  You can duplicate the socket by:

calling fork() - both child processes will inherit the listening socket.  This is what Apache does; or

sending a handle to the listening socket over a UNIX-domain socket connection using a SCM_RIGHTS message.

ContentLicense: CC BY-SA 3.0


问:
Azure Devops pipeline fails when stage not approved
I have two stage pipeline where the second (deployment) stage requires environment with approval. If no one approves the deployment - the build fails after the timeout (30 days max configurable in env approvals) on the approval. This causes weird emails about failed builds from past as the timeout triggers the build failed email to be sent.

Is there anyway to not fail the build when the approval times out?

答:
Azure Devops pipeline fails when stage not approved

Indeed, just like Eric comment, this is a feature on the roadmap to mark the stage as skipped in the case of the approval timeout. The run will be marked successful and no failure email would be raised. Will keep you updated as we make progress.

You could vote and add your comments for this feedback. When there are enough communities vote and add comments for this feedback.

Besides, MS provided advanced approval options to configure approval policies in sprint 160 before we fully get this feature:

You can now use advanced approval options to configure approval
  policies like requester should not approve, require approval from a
  subset of users and approval timeout.

Hope this helps.


问:
Citrus simulator not getting started in browser
I am trying to do the below linked Citrus Simulator sample and when I try to run the http://localhost:8080 or http://localhost:8080/services/rest/ as mentioned in the page to start my simulator, it throws This site can’t be reached localhost refused to connect.

Note: There is no proxy I am using in my browser. It is normal.

Could somebody please help me start the citrus simulator by running the below springboot project.
https://github.com/citrusframework/citrus-simulator-demo

link: https://citrusframework.org/news/2017/09/21/introducing-citrus-simulator/

答: Have you executed the steps described in citrus-simulator-demo#build-and-run? You need to build and run the simulator locally in order to access the UI in the browser. If you see errors while building and running the simulator it will not work until this has been fixed on your local environment.</p>


问:
React Router with optional path parameter
I want to declare a path with an optional path parameter, hence when I add it the page to do something extra (e.g. fill some data):

http://localhost/app/path/to/page <= render the page
  http://localhost/app/path/to/page/pathParam <= render the page with
  some data according to the pathParam

In my react router I have the following paths, in order to support the two options (this is a simplified example):

```<code><Router history={history}>
   <Route path="/path" component={IndexPage}>
      <Route path="to/page" component={MyPage}/>
      <Route path="to/page/:pathParam" component={MyPage}/>
   </Route>
</Router>
</code>```

My question is, can we declare it in one route? If I add only the second row then the route without the parameter is not found.

EDIT#1:

The solution mentioned here about the following syntax did not work for me, is it a proper one? Does it exist in the documentation?

```<code><Route path="/product/:productName/?:urlID?" handler={SomeHandler} />
</code>```

My react-router version is: 1.0.3

答:
for react-router V5 use below syntax for multiple paths

```<code><Route
          exact
          path={[path1, path2]}
          component={component}
        />
</code>```

for V6

```<code><Route path="/teams" element={<Teams />}>
  <Route index element={<TeamsIndex />} />
  <Route path=":teamId" element={<Team />} />
</Route>
</code>```

Body:
I want to declare a path with an optional path parameter, hence when I add it the page to do something extra (e.g. fill some data):

http://localhost/app/path/to/page <= render the page
  http://localhost/app/path/to/page/pathParam <= render the page with
  some data according to the pathParam

In my react router I have the following paths, in order to support the two options (this is a simplified example):

<Router history={history}>
   <Route path="/path" component={IndexPage}>
      <Route path="to/page" component={MyPage}/>
      <Route path="to/page/:pathParam" component={MyPage}/>
   </Route>
</Router>

My question is, can we declare it in one route? If I add only the second row then the route without the parameter is not found.

EDIT#1:

The solution mentioned here about the following syntax did not work for me, is it a proper one? Does it exist in the documentation?

<Route path="/product/:productName/?:urlID?" handler={SomeHandler} />

My react-router version is: 1.0.3

Body:
for react-router V5 use below syntax for multiple paths

<Route
          exact
          path={[path1, path2]}
          component={component}
        />

for V6

<Route path="/teams" element={<Teams />}>
  <Route index element={<TeamsIndex />} />
  <Route path=":teamId" element={<Team />} />
</Route>


问:
Why does it get same value?? and how to attach currency sign after result?
Why does it get same value?? and how to attach currency sign after result?
also, How to make it more briefly? I want to amend the repeating code.

function changeSign() {
  var currencySelect = document.getElementById("CurrencyID").value;
}

function changeCurrency() {

  var inputVal = parseFloat(document.getElementById("inputMoney").value);
  var currencyVal = parseFloat(document.getElementById("inputMoney"));

  if (document.getElementById("Euro")) {

    if (document.getElementById("Us1")) {

      currencyVal = (inputVal * 1.08);

    } else if (document.getElementById("Uk1")) {

      currencyVal = (inputVal * 0.83);

    } else if (document.getElementById("Ja1")) {

      currencyVal = (inputVal * 118.88);

    } else if (document.getElementById("Ca1")) {

      currencyVal = (inputVal * 1.43);
    }
  }

  document.getElementById("demo").textContent = currencyVal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Choose Convert : </b><br><br>
<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;" onchange="changeSign()">
  <option id="Euro" value="€">Euro (EUR)</option>
  <option id="Us" value="$">US Dollar (USD)</option>
  <option id="Uk" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca" value="$">Canadian Dollor (CAD)</option>
</select>
<br>

<b>Choose Convert : </b><br><br>
<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option id="Euro1" value="€">Euro (EUR)</option>
  <option id="Us1" value="$">US Dollar (USD)</option>
  <option id="Uk1" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja1" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca1" value="$">Canadian Dollor (CAD)</option>
</select>
<br>

<label>
                <br>
                <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all"
                    style="width: 196px; height:22px;" oninput="changeCurrency()"
                    >
            </label><br><br>

</div>
</div>

<p>value: <span id="demo"></span></p></code>```

答:
Firstly; Id properties have to be unique in html files. check your id props and give different names.
Then get values with document.getElementById("CurrencyID1").value and check their values in if conditions.

check the following solution:

function changeSign() {
  var currencySelect = document.getElementById("CurrencyID1").value;
}

function changeCurrency() {
    let firstCurrency = document.getElementById("CurrencyID1").value;
    let secondCurrency = document.getElementById("CurrencyID2").value;

    let inputVal = document.getElementById("inputMoney").value;
    let currencyVal=0;

   if (firstCurrency==="euro") {
      if (secondCurrency==="usd") {
        currencyVal = (inputVal * 1.08)+" $";
      } else if (secondCurrency==="pound") {
        currencyVal = (inputVal * 0.83)+" £";
      } else if (secondCurrency==="yen") {
        currencyVal = (inputVal * 118.88)+" ¥";
      } else if (secondCurrency==="can") {
        currencyVal = (inputVal * 1.43)+ " $";
      }
    }

  document.getElementById("demo").textContent = currencyVal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><b>Choose Convert : </b><br><br>
<select id="CurrencyID1" class="text ui-widget-content ui-corner-all"          style="width: 200px; height:30px;" onchange="changeSign()">
  <option id="Euro" value="euro">Euro (EUR)</option>
  <option id="Us" value="usd">US Dollar (USD)</option>
  <option id="Uk" value="pound">UK Pound Sterling (GBP)</option>
  <option id="Ja" value="yen">Japanese Yen (JPY)</option>
  <option id="Ca" value="can">Canadian Dollor (CAD)</option>
</select>
<br>

<b>Choose Convert : </b><br><br>
<select id="CurrencyID2" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option id="Euro1" value="euro">Euro (EUR)</option>
  <option id="Us1" value="usd">US Dollar (USD)</option>
  <option id="Uk1" value="pound">UK Pound Sterling (GBP)</option>
  <option id="Ja1" value="yen">Japanese Yen (JPY)</option>
  <option id="Ca1" value="can">Canadian Dollor (CAD)</option>
</select>
<br>

<label>
   <br>
  <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all" style="width: 196px; height:22px;" oninput="changeCurrency()">
            </label><br><br>

<p>value: <span id="demo"></span></p></code>```

Body:
Why does it get same value?? and how to attach currency sign after result?
also, How to make it more briefly? I want to amend the repeating code.

function changeSign() {
  var currencySelect = document.getElementById("CurrencyID").value;
}

function changeCurrency() {

  var inputVal = parseFloat(document.getElementById("inputMoney").value);
  var currencyVal = parseFloat(document.getElementById("inputMoney"));

  if (document.getElementById("Euro")) {

    if (document.getElementById("Us1")) {

      currencyVal = (inputVal * 1.08);

    } else if (document.getElementById("Uk1")) {

      currencyVal = (inputVal * 0.83);

    } else if (document.getElementById("Ja1")) {

      currencyVal = (inputVal * 118.88);

    } else if (document.getElementById("Ca1")) {

      currencyVal = (inputVal * 1.43);
    }
  }

  document.getElementById("demo").textContent = currencyVal;
}

Choose Convert :

<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;" onchange="changeSign()">
  <option id="Euro" value="€">Euro (EUR)</option>
  <option id="Us" value="$">US Dollar (USD)</option>
  <option id="Uk" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca" value="$">Canadian Dollor (CAD)</option>
</select>

Choose Convert :

<select name="CurrencyConverter" id="CurrencyID" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option id="Euro1" value="€">Euro (EUR)</option>
  <option id="Us1" value="$">US Dollar (USD)</option>
  <option id="Uk1" value="£">UK Pound Sterling (GBP)</option>
  <option id="Ja1" value="¥">Japanese Yen (JPY)</option>
  <option id="Ca1" value="$">Canadian Dollor (CAD)</option>
</select>

                <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all"
                    style="width: 196px; height:22px;" oninput="changeCurrency()"
                    >

value:

Body:
Firstly; Id properties have to be unique in html files. check your id props and give different names.
Then get values with document.getElementById("CurrencyID1").value and check their values in if conditions.

check the following solution:

function changeSign() {
  var currencySelect = document.getElementById("CurrencyID1").value;
}

function changeCurrency() {
    let firstCurrency = document.getElementById("CurrencyID1").value;
    let secondCurrency = document.getElementById("CurrencyID2").value;

    let inputVal = document.getElementById("inputMoney").value;
    let currencyVal=0;

   if (firstCurrency==="euro") {
      if (secondCurrency==="usd") {
        currencyVal = (inputVal * 1.08)+" $";
      } else if (secondCurrency==="pound") {
        currencyVal = (inputVal * 0.83)+" £";
      } else if (secondCurrency==="yen") {
        currencyVal = (inputVal * 118.88)+" ¥";
      } else if (secondCurrency==="can") {
        currencyVal = (inputVal * 1.43)+ " $";
      }
    }

  document.getElementById("demo").textContent = currencyVal;
}

<b>Choose Convert : </b><br><br>
<select id="CurrencyID1" class="text ui-widget-content ui-corner-all"          style="width: 200px; height:30px;" onchange="changeSign()">
  <option id="Euro" value="euro">Euro (EUR)</option>
  <option id="Us" value="usd">US Dollar (USD)</option>
  <option id="Uk" value="pound">UK Pound Sterling (GBP)</option>
  <option id="Ja" value="yen">Japanese Yen (JPY)</option>
  <option id="Ca" value="can">Canadian Dollor (CAD)</option>
</select>
<br>

<b>Choose Convert : </b><br><br>
<select id="CurrencyID2" class="text ui-widget-content ui-corner-all" style="width: 200px; height:30px;">
  <option id="Euro1" value="euro">Euro (EUR)</option>
  <option id="Us1" value="usd">US Dollar (USD)</option>
  <option id="Uk1" value="pound">UK Pound Sterling (GBP)</option>
  <option id="Ja1" value="yen">Japanese Yen (JPY)</option>
  <option id="Ca1" value="can">Canadian Dollor (CAD)</option>
</select>
<br>

<label>
   <br>
  <input name="inputMoney" id="inputMoney" type="text" class="text ui-widget-content ui-corner-all" style="width: 196px; height:22px;" oninput="changeCurrency()">
            </label><br><br>

<p>value: <span id="demo"></span></p>


问:
Docker loads login screen, but not starting node server.js - MEAN stack
Here's most up-to-date configuration since adding bounty: Configuration

UPDATE: It looks like it's getting a cors error when clicking login, which is most likely causing the issue. I've read in other posts like this one that I need to update nginx.conf. I haven't been able to figure out how to update said file since it's already dockerized assuming this is the solution to my problem. Also could be related to not referencing cosmodb in docker-comopose, but when I add this

```<code>    cosomsdb:
        build: ./backend
        ports:
        - "10255:10255"
</code>```

I get cors error still. 10255 is cosmosdb port

```<code>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/user/login. (Reason: CORS request did not succeed).
2
ERROR
Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/api/user/login", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:3000/api/user/login: 0 Unknown Error", error: error }
core.js:6014:19
</code>```

I'm trying to build a MEAN stack docker image, but every time I run it, it says

```<code>Error: Cannot find module '../backend/middleware/check-auth'

</code>```

I don't think it's copying my files to the container correctly. I've been going through forums, but haven't been able to find a solution. I appreciate any help!

Dockerfile

```<code>FROM node

MAINTAINER Phil

WORKDIR /src

COPY . .

RUN npm install

RUN npm install -g nodemon

EXPOSE 3000

CMD ["npm", "start"]
</code>```

docker-compose.yml

```<code>version: '3'
services:
    web:
        image: nginx
        ports:
            - "80:80"
        volumes:
        - "/Users/Phil/Documents/myapp/myapp-docker/frontend/dist:/usr/share/nginx/html"
    node:
        build: ./backend
        ports:
        - "3000:3000"
</code>```

backend package.json

```<code>{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.612.0",
    "bcrypt": "^3.0.8",
    "body-parser": "^1.19.0",
    "create-hash": "^1.2.0",
    "crypto": "^1.0.1",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.8.11",
    "mongoose-unique-validator": "^2.0.3",
    "multer": "^1.4.2",
    "multer-s3": "^2.9.0"
  }
}
</code>```

server.js file

```<code>const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");

var env = require("dotenv").config();

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);

var server = app.listen(app.get("port"), function() {
  debug("Express server listening on port " + server.address().port);
});

</code>```

答: This looks like your importing '../backend/middleware/check-auth' in app.js? If so, change you import path to './backend/middleware/check-auth'. Your compose file and container seem fine. This looks more like a path issue for your module import.

Body:
Here's most up-to-date configuration since adding bounty: Configuration

UPDATE: It looks like it's getting a cors error when clicking login, which is most likely causing the issue. I've read in other posts like this one that I need to update nginx.conf. I haven't been able to figure out how to update said file since it's already dockerized assuming this is the solution to my problem. Also could be related to not referencing cosmodb in docker-comopose, but when I add this

    cosomsdb:
        build: ./backend
        ports:
        - "10255:10255"

I get cors error still. 10255 is cosmosdb port

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/user/login. (Reason: CORS request did not succeed).
2
ERROR
Object { headers: {…}, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/api/user/login", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:3000/api/user/login: 0 Unknown Error", error: error }
core.js:6014:19

I'm trying to build a MEAN stack docker image, but every time I run it, it says

Error: Cannot find module '../backend/middleware/check-auth'

I don't think it's copying my files to the container correctly. I've been going through forums, but haven't been able to find a solution. I appreciate any help!

Dockerfile

FROM node

MAINTAINER Phil

WORKDIR /src

COPY . .

RUN npm install

RUN npm install -g nodemon

EXPOSE 3000

CMD ["npm", "start"]

docker-compose.yml

version: '3'
services:
    web:
        image: nginx
        ports:
            - "80:80"
        volumes:
        - "/Users/Phil/Documents/myapp/myapp-docker/frontend/dist:/usr/share/nginx/html"
    node:
        build: ./backend
        ports:
        - "3000:3000"

backend package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.612.0",
    "bcrypt": "^3.0.8",
    "body-parser": "^1.19.0",
    "create-hash": "^1.2.0",
    "crypto": "^1.0.1",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.8.11",
    "mongoose-unique-validator": "^2.0.3",
    "multer": "^1.4.2",
    "multer-s3": "^2.9.0"
  }
}

server.js file

const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");

var env = require("dotenv").config();

const normalizePort = val => {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    e;
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
};

const onError = error => {
  if (error.syscall !== "listen") {
    throw error;
  }
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  switch (error.code) {
    case "EACCES":
      console.error(bind + " requires elevated privileges");
      process.exit(1);
      break;
    case "EADDRINUSE":
      console.error(bind + " is already in use");
      process.exit(1);
      break;
    default:
      throw error;
  }
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
  .connect(
    "mongodb://" +
      process.env.COSMOSDB_HOST +
      ":" +
      process.env.COSMOSDB_PORT +
      "/" +
      process.env.COSMOSDB_DBNAME +
      "?ssl=true&replicaSet=globaldb",
    {
      auth: {
        user: process.env.COSMODDB_USER,
        password: process.env.COSMOSDB_PASSWORD
      }
    }
  )
  .then(() => console.log("Connection to CosmosDB successful"))
  .catch(err => console.error(err));

const onListening = () => {
  const addr = server.address();
  const bind = typeof port === "string" ? "pipe " + port : "port " + port;
  debug("Listening on " + bind);
};

const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);

var server = app.listen(app.get("port"), function() {
  debug("Express server listening on port " + server.address().port);
});


问:
pyqt4 widget appear outside the layout

I want the effect in the picture. The qlabel is in the layout, and the font is centered. Below is the code I wrote, which is different from what I want. First, qlabel is outside the layout, and second, the font is not centered.

import sys

from PyQt4.QtCore import Qt
from PyQt4.QtGui import QLabel, QApplication, QWidget, QVBoxLayout, QStyleOption, QPainter, QStyle

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.setGeometry(100, 100, 500, 500)

        vbox = QVBoxLayout()
        self.setLayout(vbox)

        a = QLabel('aaa')
        b = QLabel('bbb')
        vbox.addWidget(a)
        vbox.addWidget(a, alignment=Qt.AlignHCenter | Qt.AlignTop)
        vbox.addWidget(b, alignment=Qt.AlignHCenter | Qt.AlignBottom)

        self.setStyleSheet("""
                Example{
             border-width: 1px;
             border-style: solid;
             border-color: red;
                min-width:500px;
                 max-width:500px;
                 min-height:500px;
                 max-height:500px;
                 padding:1px 1px 1px 1px;
                 margin-bottom:30px;
                }
            QLabel{
                min-width:500px;
                 max-width:500px;
                 min-height:50px;
                 max-height:50px;
                 margin:0px;
                 padding:0px;
                 background-color:#cdcdcd;
                 text-align: center center;
            }
        """)
        self.show()

    def paintEvent(self, event):
        super(Example, self).paintEvent(event)
        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

def main():
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
```

答:
The logic of the layouts is to handle the geometry of the elements but you are also handling the geometry with the stylesheet, causing the problem you observe. On the other hand, the QLabel does not have the text-align property but you have to use qproperty-alignment: AlignCenter;.

To avoid this it is better to avoid managing the geometry with stylesheet but with the methods of the class, considering the solution is:

import sys

from PyQt4.QtCore import Qt
from PyQt4.QtGui import (
    QLabel,
    QApplication,
    QWidget,
    QVBoxLayout,
    QStyleOption,
    QPainter,
    QStyle,
)

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.setGeometry(100, 100, 500, 500)

        self.label_a = QLabel("aaa")
        self.label_b = QLabel("bbb")
        self.label_a.setFixedHeight(50)
        self.label_b.setFixedHeight(50)

        vbox = QVBoxLayout(self)
        vbox.setContentsMargins(1, 1, 1, 1)
        vbox.addWidget(self.label_a)
        vbox.addWidget(QWidget(), stretch=1)
        vbox.addWidget(self.label_b)

        self.setFixedSize(500, 500)

        self.setStyleSheet(
            """
        Example{
            border-width: 1px;
            border-style: solid;
            border-color: red;
            padding:1px 1px 1px 1px;
        }
        QLabel{
            margin:0px;
            padding:0px;
            background-color:#cdcdcd;
            qproperty-alignment: AlignCenter;
        }
        """
        )

    def paintEvent(self, event):
        super(Example, self).paintEvent(event)
        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)

def main():
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
```

Title: pyqt4 widget appear outside the layout


问:
context is disposed when using "two levels" of context
When doing:

```<code>    using (IUnitOfWork uow = UnitOfWork.Current)
    {
        LocationRepository rep = new LocationRepository();
        Location loc = new Location()
        {
            CompanyId = m_User.UserCompany.CompanyId,
            Name = locationName
        };
        rep.Insert(loc);
        uow.Commit();
    }
</code>```

I get the exception:

```<code>The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
</code>```

The reason I get this exception is that m_User.UserCompany is implemented like:

```<code>public _Company UserCompany
{
    get
    {
                using (IUnitOfWork uow = UnitOfWork.Current)
                {
                    CompanyRepository rep = new CompanyRepository();
                    m_Company = rep.Get(companyId.Value);
                }
        return m_Company;
    }
}
</code>```

So actually inside the first using statement I create another using statement which dispose my context when done and I get the exception in the outer using statement.

I am using the entity framework the way described here.

What is the common solution for such case?

答:
I wonder why do you even bother with repositories if your User entity access unit of work directly? Your architecture looks very inconsistent. Create central place where unit of work is instanciated and disposed - in case of web application ideal place to call these methods is beginning and ending request. Access unit of work from repositories (or pass unit of work as parameter to their constructors) and handle all data retrieving and data persisting in repositories. Don't make your entities dependent on unit of work - that makes your repositories redundant and you can fallback to active record pattern.

This all leads to dependency injection with per HTTP request lifetime for unit of work and repositories.

Complains like "it is lot of work" or "I have a lot of places to change" are not excuse. You have a problem and you have to solve it. Solution requires big amount of refactoring because your initial solution was wrong - I sad to say you did it wrong and now you must invest your time to fix it.

Body:
When doing:

    using (IUnitOfWork uow = UnitOfWork.Current)
    {
        LocationRepository rep = new LocationRepository();
        Location loc = new Location()
        {
            CompanyId = m_User.UserCompany.CompanyId,
            Name = locationName
        };
        rep.Insert(loc);
        uow.Commit();
    }

I get the exception:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

The reason I get this exception is that m_User.UserCompany is implemented like:

public _Company UserCompany
{
    get
    {
                using (IUnitOfWork uow = UnitOfWork.Current)
                {
                    CompanyRepository rep = new CompanyRepository();
                    m_Company = rep.Get(companyId.Value);
                }
        return m_Company;
    }
}

So actually inside the first using statement I create another using statement which dispose my context when done and I get the exception in the outer using statement.

I am using the entity framework the way described here.

What is the common solution for such case?


问:
Group by with Inner join doesn't return any result
```<code>SELECT TOP 6 *
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber
</code>```

I have a table vws_entryline associated to the table vws_customer according to the account number of the customers, as you can see. I would want to group the results by another field, VoucherNumber (which is present in vws_entryline only).

For example, I would want to have these results (it's not JSON format, only an example from my mind that doesn't correspond exactly to a group by... but what I want is actually a SQL group by result):

{AccountNumber: "PO200", field_1_vws_customer: "foo",
  GeneralAccountNumber: "PO200", "VoucherNumber": "N45PO",
  field_1_vws_entryline: 150.25},

{AccountNumber: "PO200",
  field_1_vws_customer: "foo",  GeneralAccountNumber: "PO200",
  "VoucherNumber": "N45PO", field_1_vws_entryline: 25.75},

{AccountNumber: "PO200", field_1_vws_customer: "foo",
  GeneralAccountNumber: "PO200", "VoucherNumber": "AZERTY",
  field_1_vws_entryline: 50,50},

{AccountNumber: "SW7",
  field_1_vws_customer: "foo",  GeneralAccountNumber: "SW7",
  "VoucherNumber": "42HaveAGoodDay24", field_1_vws_entryline: 50,50}

As you can see, the results are correctly grouped by the VoucherNumber field.

However, my SQL request doesn't return any result. Why?

Edit

I've tried:

```<code>SELECT el.EntryLineDate, el.VoucherNumber, el.label, el.GeneralAccountNumber,
       el.Debit, el.Credit, el.type, el.amount, el.PaymentTypeid, el.EntryNumber,
       c.ThirdId, c.civility, c.name, c.NaturalPerson, c.ThirdLanguage, c.siren,
       c.nic, c.naf, c.AccountNumber
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber
</code>```

but it doesn't work

答:
You dont have aggregation on voucher Number in the JSON resultset. It appears as a normal JSON document with every row for every voucher number.

As you have not provided schema, below is rough query. You need to use FOR JSON clause to achieve JSON resultset. Read more on FOR JSON

```<code>SELECT v_c.AccountNumber, field_1_vws_customer,GeneralAccountNumber,
VoucherNumber, field_1_vws_entryline
FROM vws_entryline AS v_e
JOIN vws_customer AS v_c
ON v_e.accountNumber = v_c.accountNumber
FOR JSON PATH;
</code>```

Body:
SELECT TOP 6 *
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber

I have a table vws_entryline associated to the table vws_customer according to the account number of the customers, as you can see. I would want to group the results by another field, VoucherNumber (which is present in vws_entryline only).

For example, I would want to have these results (it's not JSON format, only an example from my mind that doesn't correspond exactly to a group by... but what I want is actually a SQL group by result):

{AccountNumber: "PO200", field_1_vws_customer: "foo",
  GeneralAccountNumber: "PO200", "VoucherNumber": "N45PO",
  field_1_vws_entryline: 150.25},

{AccountNumber: "PO200",
  field_1_vws_customer: "foo",  GeneralAccountNumber: "PO200",
  "VoucherNumber": "N45PO", field_1_vws_entryline: 25.75},

{AccountNumber: "PO200", field_1_vws_customer: "foo",
  GeneralAccountNumber: "PO200", "VoucherNumber": "AZERTY",
  field_1_vws_entryline: 50,50},

{AccountNumber: "SW7",
  field_1_vws_customer: "foo",  GeneralAccountNumber: "SW7",
  "VoucherNumber": "42HaveAGoodDay24", field_1_vws_entryline: 50,50}

As you can see, the results are correctly grouped by the VoucherNumber field.

However, my SQL request doesn't return any result. Why?

Edit

I've tried:

SELECT el.EntryLineDate, el.VoucherNumber, el.label, el.GeneralAccountNumber,
       el.Debit, el.Credit, el.type, el.amount, el.PaymentTypeid, el.EntryNumber,
       c.ThirdId, c.civility, c.name, c.NaturalPerson, c.ThirdLanguage, c.siren,
       c.nic, c.naf, c.AccountNumber
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber

but it doesn't work

Body:
You dont have aggregation on voucher Number in the JSON resultset. It appears as a normal JSON document with every row for every voucher number.

As you have not provided schema, below is rough query. You need to use FOR JSON clause to achieve JSON resultset. Read more on FOR JSON

SELECT v_c.AccountNumber, field_1_vws_customer,GeneralAccountNumber,
VoucherNumber, field_1_vws_entryline
FROM vws_entryline AS v_e
JOIN vws_customer AS v_c
ON v_e.accountNumber = v_c.accountNumber
FOR JSON PATH;


问:
Ajax Autocomplete not working properly in Laravel 6
I saw a tutorial on AJAX Autocomplete it looks ok but the problem is it also display all the data not the one I am searching for.

sorry I am new to ajax can you help me fixing this?

from my Controller

```<code>public function search(Request $request){
    // check if ajax request is coming or not
    if($request->ajax()) {
        // select country name from database
        $data = Vendor::where('vendor_id', 'LIKE', '%'.$request->vendor_id.'%')
            ->get();
        // declare an empty array for output
        $output = '';
        // if searched countries count is larager than zero
        if (count($data)>0) {
            // concatenate output to the array
            $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
            // loop through the result array
            foreach ($data as $row){
                // concatenate output to the array
                $output .= '<li class="list-group-item">'.$row->vendor_id. ' ' .$row->vendor_name.'</li>';
            }
            // end of output
            $output .= '</ul>';
        }
        else {
            // if there's no matching results according to the input
            $output .= '<li class="list-group-item">'.'No results'.'</li>';
        }
        // return output result array
        return $output;
    }
}
</code>```

My Blade

```<code>    <div class="row">
        <div class="col-lg-12"></div>
        <div class="col-lg-6">
            <div class="form-group">
                <input type="text" name="vendor_id" id="vendor_id" data-type="vendor_id" placeholder="Enter vendor ID" class="form-control autocomplete_txt">
                {{-- <input class="typeahead form-control" type="text"> --}}
            </div>
            <div id="vendor_list"></div>
        </div>
        <div class="col-lg-6">
            <div class="form-group">
                <input type="text" name="vendor_name" id="vendor_name" placeholder="Vendor Name" class="form-control" readonly="true">
            </div>
        </div>
        <div class="col-lg-12"></div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    <script type="text/javascript">
        // jQuery wait till the page is fullt loaded
        $(document).ready(function () {
            // keyup function looks at the keys typed on the search box
            $('#vendor_id').on('keyup',function() {
                // the text typed in the input field is assigned to a variable
                var query = $(this).val();
                // call to an ajax function
                $.ajax({
                    // assign a controller function to perform search action - route name is search
                    url:"{{ route('admin.search') }}",
                    // since we are getting data methos is assigned as GET
                    type:"GET",
                    // data are sent the server
                    data:{'vendor':query},
                    // if search is succcessfully done, this callback function is called
                    success:function (data) {
                        // print the search results in the div called vendor_list(id)
                        $('#vendor_list').html(data);
                    }
                })
                // end of ajax call
            });

            // initiate a click function on each search result
            $(document).on('click', 'li', function(){
                // declare the value in the input field to a variable
                var value = $(this).text();
                // assign the value to the search box
                $('#vendor_id').val(value);
                // after click is done, search results segment is made empty
                $('#vendor_list').html("");
            });
        });
    </script>
</code>```

Route

```<code>Route::get('search', 'PurchasedOrderController@search')->name('search');
</code>```

Can you help me fix the dropdown list and also display the vendor_name on vendor name input field once the this click code trigger? Thank you so much in advance!!!

答:
For me your problem comes from your controller and you need a post request too or stay in get and do like that.

Controller

```<code>public function search(Request $request, $vendor){
// check if ajax request is coming or not
if($request->ajax()) {
    // select country name from database
    $data = Vendor::where('vendor_id', 'LIKE', '%'.$vendor.'%')
        ->get();
    // declare an empty array for output
    $output = '';
    // if searched countries count is larager than zero
    if (count($data)>0) {
        // concatenate output to the array
        $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
        // loop through the result array
        foreach ($data as $row){
            // concatenate output to the array
            $output .= '<li class="list-group-item">'.$row->vendor_id. ' ' .$row->vendor_name.'</li>';
        }
        // end of output
        $output .= '</ul>';
    }
    else {
        // if there's no matching results according to the input
        $output .= '<li class="list-group-item">'.'No results'.'</li>';
    }
    // return output result array
    return $output;
}}
</code>```

Your route

```<code>Route::get('search/{vendor}', 'PurchasedOrderController@search')->name('search');
</code>```

Your blade

```<code>    $(document).ready(function () {
        // keyup function looks at the keys typed on the search box
        $('#vendor_id').on('keyup',function() {
            // the text typed in the input field is assigned to a variable
            var query = $(this).val();
            // call to an ajax function
            $.ajax({
                url:"yourdomain.com/search/"+query,
                // since we are getting data methos is assigned as GET
                type:"GET",
                // if search is succcessfully done, this callback function is called
                success:function (data) {
                    // print the search results in the div called vendor_list(id)
                    $('#vendor_list').html(data);
                }
            })
            // end of ajax call
        });
</code>```

It should work, also not in post you have to change in your controller your $request->vendor_id it is not good, change to $request->vendorand pass your route laravel and the ajax request in post and it should work

for onclick:

```<code>$('#list-group-item').on('click', function(){

    var item_select = $(this).text();
    $('#vendor_id').val(item_select);
    $('#vendor_list').html("");
 });
</code>```

Body:
I saw a tutorial on AJAX Autocomplete it looks ok but the problem is it also display all the data not the one I am searching for.

sorry I am new to ajax can you help me fixing this?

from my Controller

public function search(Request $request){
    // check if ajax request is coming or not
    if($request->ajax()) {
        // select country name from database
        $data = Vendor::where('vendor_id', 'LIKE', '%'.$request->vendor_id.'%')
            ->get();
        // declare an empty array for output
        $output = '';
        // if searched countries count is larager than zero
        if (count($data)>0) {
            // concatenate output to the array
            $output = '
';
            // loop through the result array
            foreach ($data as $row){
                // concatenate output to the array
                $output .= '
'.$row->vendor_id. ' ' .$row->vendor_name.'
';
            }
            // end of output
            $output .= '
';
        }
        else {
            // if there's no matching results according to the input
            $output .= '
'.'No results'.'
';
        }
        // return output result array
        return $output;
    }
}

My Blade

                <input type="text" name="vendor_id" id="vendor_id" data-type="vendor_id" placeholder="Enter vendor ID" class="form-control autocomplete_txt">
                {{-- <input class="typeahead form-control" type="text"> --}}

                <input type="text" name="vendor_name" id="vendor_name" placeholder="Vendor Name" class="form-control" readonly="true">

Route

Route::get('search', 'PurchasedOrderController@search')->name('search');

Can you help me fix the dropdown list and also display the vendor_name on vendor name input field once the this click code trigger? Thank you so much in advance!!!

Body:
For me your problem comes from your controller and you need a post request too or stay in get and do like that.

Controller

public function search(Request $request, $vendor){
// check if ajax request is coming or not
if($request->ajax()) {
    // select country name from database
    $data = Vendor::where('vendor_id', 'LIKE', '%'.$vendor.'%')
        ->get();
    // declare an empty array for output
    $output = '';
    // if searched countries count is larager than zero
    if (count($data)>0) {
        // concatenate output to the array
        $output = '<ul class="list-group" style="display: block; position: relative; z-index: 1">';
        // loop through the result array
        foreach ($data as $row){
            // concatenate output to the array
            $output .= '<li class="list-group-item">'.$row->vendor_id. ' ' .$row->vendor_name.'</li>';
        }
        // end of output
        $output .= '</ul>';
    }
    else {
        // if there's no matching results according to the input
        $output .= '<li class="list-group-item">'.'No results'.'</li>';
    }
    // return output result array
    return $output;
}}

Your route

Route::get('search/{vendor}', 'PurchasedOrderController@search')->name('search');

Your blade

    $(document).ready(function () {
        // keyup function looks at the keys typed on the search box
        $('#vendor_id').on('keyup',function() {
            // the text typed in the input field is assigned to a variable
            var query = $(this).val();
            // call to an ajax function
            $.ajax({
                url:"yourdomain.com/search/"+query,
                // since we are getting data methos is assigned as GET
                type:"GET",
                // if search is succcessfully done, this callback function is called
                success:function (data) {
                    // print the search results in the div called vendor_list(id)
                    $('#vendor_list').html(data);
                }
            })
            // end of ajax call
        });

It should work, also not in post you have to change in your controller your $request->vendor_id it is not good, change to $request->vendorand pass your route laravel and the ajax request in post and it should work

for onclick:

$('#list-group-item').on('click', function(){

    var item_select = $(this).text();
    $('#vendor_id').val(item_select);
    $('#vendor_list').html("");
 });


问:
How to use params inside navigationOptions with React Navigation 5
Sorry for this question i don't understand the other question's answers because they are not really the same as what i want. I am a beginner with this.

This is my App.js: (new way of App.js)

```<code>const Stack = createStackNavigator()

export default function App() {
  return <NavigationContainer>
    <Stack.Navigator>
<Stack.Screen options={{title: 'Profile'},Profile.navigationOptions} name="Profile" component={Profile}/>
name="AccountOverview" component={AccountOverview}/>
    </Stack.Navigator>
  </NavigationContainer>
}
</code>```

 This is my profile.js navigationOptions

```<code>static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;

    if (params.facebookName) {
      var usernameTitle = params.facebookName || "";
    } else {
      var usernameTitle = params.usernameValue || "";
    }
    return {
      title: "Welcome " + usernameTitle,

      headerRight: () =>
        <TouchableOpacity style={styles.btn} onPress={params.removeItemValue}>
          <Text style={styles.btnText}>Log out</Text>
        </TouchableOpacity>

    };
  };
</code>```

The error i am getting is undefined is not an object (evaluating 'navigation.state.params')

I can't understand the documentation either from React Navigation's website.

So i hope i will get a anwer targeting my exact way of code.

I would really appreciate it and give you and accepted answer for your solution.

Thanks for your time

答:
you can use params in three ways:

when defining a screen inside stack navigator you can send initial params to it :

    <Stack.Screen ... initialParams={{ facebookName: "developer" }} />

when navigating to a screen from other screens in the stack :

    navigation.navigate("Profile", { facebookName: "developer" })

you can also update a screen's param from inside of it :

    navigation.setParams({ title: "new title" })

Body:
Sorry for this question i don't understand the other question's answers because they are not really the same as what i want. I am a beginner with this.

This is my App.js: (new way of App.js)

const Stack = createStackNavigator()

export default function App() {
  return <NavigationContainer>
    <Stack.Navigator>
<Stack.Screen options={{title: 'Profile'},Profile.navigationOptions} name="Profile" component={Profile}/>
name="AccountOverview" component={AccountOverview}/>
    </Stack.Navigator>
  </NavigationContainer>
}

 This is my profile.js navigationOptions

static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;

    if (params.facebookName) {
      var usernameTitle = params.facebookName || "";
    } else {
      var usernameTitle = params.usernameValue || "";
    }
    return {
      title: "Welcome " + usernameTitle,

      headerRight: () =>
        <TouchableOpacity style={styles.btn} onPress={params.removeItemValue}>
          <Text style={styles.btnText}>Log out</Text>
        </TouchableOpacity>

    };
  };

The error i am getting is undefined is not an object (evaluating 'navigation.state.params')

I can't understand the documentation either from React Navigation's website.

So i hope i will get a anwer targeting my exact way of code.

I would really appreciate it and give you and accepted answer for your solution.

Thanks for your time


问:
Function not sending alert in browser HTML, JavaScript
Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

```<code><!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>
  <script>
    'use strict';
    function getNumber(cardNum) {
        if (cardNum.length > 16 || cardNum.length < 13) {
            alert(‘This is not valid.’);
            return false;}
        else {
            alert(‘This is valid.’);
            return true;}
    }
  </script>
</head>

<body onload=“document.cardNum()”>

<h4> Enter Credit Card Number: </h4>
<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>
    <br>
    <input type="submit" value=Submit onclick = “getNumber(cardNum)”/>
</form>

</body>
</html>
</code>```

答:
```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Card Reader</title>
    <link type=’text/css’/>

    <script>
      function myFunction() {
        var x = document.getElementById("cardNum").value;
        if (isNaN(x) || x.length < 13 || x.length > 16) {
          alert("Input not valid");
        } else {
          alert("Input OK");
        }
      }
    </script>
  </head>
  <body>
    <h4>Enter Credit Card Number:</h4>

    <input type="text" id="cardNum" name="cardNum" />

    <button type="button" onclick="myFunction()">Submit</button>
  </body>
</html>
</code>```

This is a simple and direct approach.

Body:
Newbie to HTML and Javascript here.

I am coding up a very basic program that allows a user to enter a card number and the browser should say if it is a valid number (between 13-16 digits) or not.

The website pulls up and shows everything I want it to, but when a number is entered (valid or invalid) the alert is not sent to say if the number was good or not.

Any suggestions on how I can fix this?

<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Card Reader</title>
  <link type=’text/css’/>

 Enter Credit Card Number:

<form>
    <input type='text' id=‘cardNum’ name=‘cardNum’/>

    <input type="submit" value=Submit onclick = “getNumber(cardNum)”/>
</form>

Body:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Card Reader</title>
    <link type=’text/css’/>

    <script>
      function myFunction() {
        var x = document.getElementById("cardNum").value;
        if (isNaN(x) || x.length < 13 || x.length > 16) {
          alert("Input not valid");
        } else {
          alert("Input OK");
        }
      }
    </script>
  </head>
  <body>
    <h4>Enter Credit Card Number:</h4>

    <input type="text" id="cardNum" name="cardNum" />

    <button type="button" onclick="myFunction()">Submit</button>
  </body>
</html>

This is a simple and direct approach.


问:
Inheriting and overriding ostream operator in C++
I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.

I am working with several derived classes. The ostream operator << for each of these should print out some things common to each, and some things specific to each.  Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.

For example:

The Base class .h file

```<code>class Base

{

 int FirstClassNumber;

//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.

public:

friend ostream& operator << (ostream& os, const Base &base)
{
    base << os ;

    return os;
}

virtual void operator << (ostream& os) const = 0;

};
</code>```

The Base.cpp file includes these lines:

```<code>void Base::operator << (ostream& os)
{
  os << FirstClassNumber;
}
</code>```

Then I derive: (FirstDerived.h)

```<code>class FirstDerived : Public Base

{

int SecondClassNumber;

};
</code>```

FirstDerived.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
  os <<

  "The first Number is:

 //This is the line that isn't working - someone else gave me this syntax

  << Base::operator<<

  << "The second number is"

  << SecondClassNumber;
}
</code>```

Then I want to derive:

```<code>class SecondDerived: Public FirstDerived
{

int ThirdClassNumber;

};
</code>```

Second.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
  os <<

 FirstDerived::operator<<

 << "The third number is "

 << ThirdClassNumber;

 }
</code>```

I think the problem is most likely either the declaration in the very start of the program, or the lines like Base::operator<<.

Another possibility is that I'm not redeclaring it in the .h file of every inherited class.  Should I be, and if so what syntax should I use?

It was suggested to me to use the static_cast method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it.  Any suggestions?

答:
FirstDerived.cpp:

```<code>FirstDerived::operator << (ostream& os)
{
     os <<    "The first Number is:"
   //This is the line that isn't working - someone else gave me this syntax
    << Base::operator<<
     << "The second number is"
    << SecondClassNumber;
}
</code>```

You need to call the function by putting parenthesis after it, and provide the argument it expects.  It doesn't have a return value so shouldn't be in the set of things being streamed.  Summarily:

```<code>os << "The first number is: "; // finish streaming statement with ";"
Base::operator<<(os);   // separate statement to call this function...
os << "The second number is " << SecondClassNumber; // start streaming again
</code>```

Body:
I've been trying to find an answer to this, but no one seems to have exactly the same problem as I do.

I am working with several derived classes. The ostream operator << for each of these should print out some things common to each, and some things specific to each.  Later on, I would like to further derive from these derived classes, and again the new derived classes need to print out some things that are in the "generations" above them.

For example:

The Base class .h file

class Base

{

 int FirstClassNumber;

//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.

public:

friend ostream& operator << (ostream& os, const Base &base)
{
    base << os ;

    return os;
}

virtual void operator << (ostream& os) const = 0;

};

The Base.cpp file includes these lines:

void Base::operator << (ostream& os)
{
  os << FirstClassNumber;
}

Then I derive: (FirstDerived.h)

class FirstDerived : Public Base

{

int SecondClassNumber;

};

FirstDerived.cpp:

FirstDerived::operator << (ostream& os)
{
  os <<

  "The first Number is:

 //This is the line that isn't working - someone else gave me this syntax

  << Base::operator<<

  << "The second number is"

  << SecondClassNumber;
}

Then I want to derive:

class SecondDerived: Public FirstDerived
{

int ThirdClassNumber;

};

Second.cpp:

FirstDerived::operator << (ostream& os)
{
  os <<

 FirstDerived::operator<<

 << "The third number is "

 << ThirdClassNumber;

 }

I think the problem is most likely either the declaration in the very start of the program, or the lines like Base::operator<<.

Another possibility is that I'm not redeclaring it in the .h file of every inherited class.  Should I be, and if so what syntax should I use?

It was suggested to me to use the static_cast method, but my professor (the one who wrote the assignment, and therefore won't give us too much help with it) said that there's a better way to do it.  Any suggestions?

Body:
FirstDerived.cpp:

FirstDerived::operator << (ostream& os)
{
     os <<    "The first Number is:"
   //This is the line that isn't working - someone else gave me this syntax
    << Base::operator<<
     << "The second number is"
    << SecondClassNumber;
}

You need to call the function by putting parenthesis after it, and provide the argument it expects.  It doesn't have a return value so shouldn't be in the set of things being streamed.  Summarily:

os << "The first number is: "; // finish streaming statement with ";"
Base::operator<<(os);   // separate statement to call this function...
os << "The second number is " << SecondClassNumber; // start streaming again


问:
Transpose data in SQL with new column
I have a data like:

```<code>id maths phy chem
1   50   60   21
2   60   80   22
3   80   90   23
</code>```

Now I want it to look like:

```<code>sub   1   2   3
math 50  60  80
phy  60  80  90
chem 21  22  23
</code>```

my code:

```<code>select *
  from mrks
    pivot
(
  max(maths)
  for id in ([1], [2], [3])
) piv
</code>```

however I'm facing 2 issues

I am not able to transpose chem and phy values

Not able to group maths, phy and chem under subj

答:
In SQL Server, you can unpivot with cross apply, then pivot using conditional aggregation:

```<code>select
    col,
    max(case when id = 1 then val end) col1,
    max(case when id = 2 then val end) col2,
    max(case when id = 3 then val end) col3
from mytable t
cross apply (values ('maths', maths), ('phy', phy), ('chem', chem)) p(col, val)
group by col
</code>```

Demo on DB Fiddle:

```
col   | col1 | col2 | col3
:---- | ---: | ---: | ---:
chem  |   21 |   22 |   23
maths |   50 |   60 |   80
phy   |   60 |   80 |   90
```

Title: Transpose data in SQL with new column

Body:
I have a data like:

id maths phy chem
1   50   60   21
2   60   80   22
3   80   90   23

Now I want it to look like:

sub   1   2   3
math 50  60  80
phy  60  80  90
chem 21  22  23

my code:

select *
  from mrks
    pivot
(
  max(maths)
  for id in ([1], [2], [3])
) piv

however I'm facing 2 issues

I am not able to transpose chem and phy values

Not able to group maths, phy and chem under subj

Body:
In SQL Server, you can unpivot with cross apply, then pivot using conditional aggregation:

select
    col,
    max(case when id = 1 then val end) col1,
    max(case when id = 2 then val end) col2,
    max(case when id = 3 then val end) col3
from mytable t
cross apply (values ('maths', maths), ('phy', phy), ('chem', chem)) p(col, val)
group by col

Demo on DB Fiddle:

col   | col1 | col2 | col3
:---- | ---: | ---: | ---:
chem  |   21 |   22 |   23
maths |   50 |   60 |   80
phy   |   60 |   80 |   90