问:
Define struct field with circular reference
I have the following code where a struct field depends on a struct field that is not declared yet, because that struct in turn might depend on the struct that I am trying to declare.

How can I design this so that it compiles? Or am I missing an obvious way to get rid of the union struct for keeping several struct definitions together?

```<code>typedef struct expression {
    expression_type type;
    union {
        bool_expression bool;
        identifier_expression ident;
        integer_expression _int;
        prefix_expression prefix;
        infix_expression infix;

        // TODO: Fix this
        if_expression _if;
    };
} expression;

typedef struct statement {
    token token;
    identifier name;
    expression * value;
} statement;

typedef struct block_statement {
    token token;
    statement *statements;
} block_statement;

typedef struct if_expression {
    token token;
    expression condition;
    block_statement *consequence;
    block_statement *alternative;
} if_expression;
</code>```

答:
If you change expression condition; to expression *condition; in if_expression, and forward declare expression — typedef struct expression expression; at the top and then place struct expression { … }; at the bottom, the code should be OK.

```<code>/* Placeholder typedefs for undefined typedef names */
typedef int token;
typedef int identifier;
typedef int bool_expression;
typedef int identifier_expression;
typedef int integer_expression;
typedef int prefix_expression;
typedef int infix_expression;
typedef int expression_type;

/* The fixed code starts here */

typedef struct expression expression;

typedef struct statement
{
    token token;
    identifier name;
    expression * value;
} statement;

typedef struct block_statement
{
    token token;
    statement *statements;
} block_statement;

typedef struct if_expression
{
    token token;
    expression *condition;
    block_statement *consequence;
    block_statement *alternative;
} if_expression;

struct expression
{
    expression_type type;
    union
    {
        bool_expression bool;
        identifier_expression ident;
        integer_expression _int;
        prefix_expression prefix;
        infix_expression infix;
        if_expression _if;
    };
};

expression expr = { 0 };
</code>```

This compiles.

Body:
I have the following code where a struct field depends on a struct field that is not declared yet, because that struct in turn might depend on the struct that I am trying to declare.

How can I design this so that it compiles? Or am I missing an obvious way to get rid of the union struct for keeping several struct definitions together?

typedef struct expression {
    expression_type type;
    union {
        bool_expression bool;
        identifier_expression ident;
        integer_expression _int;
        prefix_expression prefix;
        infix_expression infix;

        // TODO: Fix this
        if_expression _if;
    };
} expression;

typedef struct statement {
    token token;
    identifier name;
    expression * value;
} statement;

typedef struct block_statement {
    token token;
    statement *statements;
} block_statement;

typedef struct if_expression {
    token token;
    expression condition;
    block_statement *consequence;
    block_statement *alternative;
} if_expression;

Body:
If you change expression condition; to expression *condition; in if_expression, and forward declare expression — typedef struct expression expression; at the top and then place struct expression { … }; at the bottom, the code should be OK.

/* Placeholder typedefs for undefined typedef names */
typedef int token;
typedef int identifier;
typedef int bool_expression;
typedef int identifier_expression;
typedef int integer_expression;
typedef int prefix_expression;
typedef int infix_expression;
typedef int expression_type;

/* The fixed code starts here */

typedef struct expression expression;

typedef struct statement
{
    token token;
    identifier name;
    expression * value;
} statement;

typedef struct block_statement
{
    token token;
    statement *statements;
} block_statement;

typedef struct if_expression
{
    token token;
    expression *condition;
    block_statement *consequence;
    block_statement *alternative;
} if_expression;

struct expression
{
    expression_type type;
    union
    {
        bool_expression bool;
        identifier_expression ident;
        integer_expression _int;
        prefix_expression prefix;
        infix_expression infix;
        if_expression _if;
    };
};

expression expr = { 0 };

This compiles.


来源: stackexchange

问:
Trying to scan lines of a file into a ragged array (array of pointers) in C
running UNIX through putty, and using vi and gcc.
I am attempting to read in a line of a file and using a ragged array store the lines.
I won't provide the whole code because it is unnecessary,

```<code>main(){
   char func[51];
   char * functions[201];
   FILE * inf;
   if (( inf = fopen("test.txt", "r")) == NULL){
       printf("can't open so exiting\n");
       exit(EXIT_SUCCESS)

   int i;
   i = 0;
   while( fscanf(inf, "%s", func) != EOF){
        functions[i] = func;
        i++;
   }
   printf("%s\n", *functions); /* this is just for me to check if its working*/

   }
</code>```

incldues stdio.h, stdlib.h and string.h

SO the code works in that it runs through the file and during the while loop it stores the line but I want it so that functions[0] stores a pointer leading to the first line and functions[1] stores a pointer leading to the second line and so on. I'm not sure how to do this, any help would be appreciated thanks :)

答:
Please fix your formating / code blocks now it seems like you are reading test.txt when you have failed to open the file and exited the program.

You have to keep in mind that the variable func points to the data structure func[51] now when you fscanf you overwrite func[51] all the time with a new line. And since your are storing the address pointing to func[51] to in the array functions you don't actually store the contents of the char array (func[51]).

You could solve this by make your functions array an two-dimensional array char functions[201][51] and then use a strcpy to copy the data structure func is pointing to to functions[i] with strcpy(functions[i], func);

this will result in something like:

```<code>main() {
    char func[51];
    char functions[201][51];
    FILE * inf;
    if (( inf = fopen("test.txt", "r")) == NULL) {
        printf("can't open so exiting\n");
        exit(EXIT_SUCCESS)
    } // <-- you are missing this one

    int i = 0;
    while( fscanf(inf, "%s", func) != EOF){
        strcpy(functions[i++], func);
    }
    printf("%s\n", *functions); /* this is just for me to check if its working*/
}
</code>```

This could also be:

```<code>while (fscanf(inf, "%s", functions[i++]) != EOF);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
running UNIX through putty, and using vi and gcc.
I am attempting to read in a line of a file and using a ragged array store the lines.
I won't provide the whole code because it is unnecessary,

main(){
   char func[51];
   char * functions[201];
   FILE * inf;
   if (( inf = fopen("test.txt", "r")) == NULL){
       printf("can't open so exiting\n");
       exit(EXIT_SUCCESS)

   int i;
   i = 0;
   while( fscanf(inf, "%s", func) != EOF){
        functions[i] = func;
        i++;
   }
   printf("%s\n", *functions); /* this is just for me to check if its working*/

   }

incldues stdio.h, stdlib.h and string.h

SO the code works in that it runs through the file and during the while loop it stores the line but I want it so that functions[0] stores a pointer leading to the first line and functions[1] stores a pointer leading to the second line and so on. I'm not sure how to do this, any help would be appreciated thanks :)

Body:
Please fix your formating / code blocks now it seems like you are reading test.txt when you have failed to open the file and exited the program.

You have to keep in mind that the variable func points to the data structure func[51] now when you fscanf you overwrite func[51] all the time with a new line. And since your are storing the address pointing to func[51] to in the array functions you don't actually store the contents of the char array (func[51]).

You could solve this by make your functions array an two-dimensional array char functions[201][51] and then use a strcpy to copy the data structure func is pointing to to functions[i] with strcpy(functions[i], func);

this will result in something like:

main() {
    char func[51];
    char functions[201][51];
    FILE * inf;
    if (( inf = fopen("test.txt", "r")) == NULL) {
        printf("can't open so exiting\n");
        exit(EXIT_SUCCESS)
    } // <-- you are missing this one

    int i = 0;
    while( fscanf(inf, "%s", func) != EOF){
        strcpy(functions[i++], func);
    }
    printf("%s\n", *functions); /* this is just for me to check if its working*/
}

This could also be:

while (fscanf(inf, "%s", functions[i++]) != EOF);


问:
Dynamic Dependent Select Box using Ajax and PHP not working in materialize js
In my application, I am using Dynamic Dependent Select Box using Ajax and PHP. My website template is constructed using materialize js. In my console it successfully receive the values on Doctor Name in my application, but isn't load into the doctor name select box. With removing materialize js and materialize css it working fine.

Here is the code:

```<code>         <form class="form-horizontal" method="POST" id="form_apt">
         <center>   <h2>Request an Appointment</h2>  </center>  <br><br>
                <div class="form-group">
                    <label class="control-label col-sm-3">Doctor Specilization:</label>
                    <div class="col-sm-9">

                    <?php
        function load(){
           include('phpquery/dbconnection.php');
            $output='';
            $sql="SELECT * from doctorspecilization";
            $result=mysqli_query($con,$sql);
            while($row=mysqli_fetch_array($result)){
     $output.='<option value="'.$row["specilization"].'">'.$row["specilization"].'</option>';
          }
              return $output;
             }
        ?>

            <select name="doctorspecilization" id="doctorspecilization">
            <option value="">Select Specilization</option>
             <?php echo load();   ?>

                  </select>
                  <span id="doctorspecilization-info" class="info text-danger"></span><br />

                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-3">Doctor :</label>
                    <div class="col-sm-9" class="select">
                        <select name="doctorname" id="doctorname">
                    <option value="">Select Doctor</option>
                  </select>
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-sm-3">Appointment Date:</label>
                    <div class="col-sm-9">
                        <input type="date" id="date" name="date" class="form-control"
                        placeholder="Enter your education">
                        <span id="date-info" class="info text-danger"></span><br />
                    </div>

                </div>

                <div class="form-group mar-bot-0">
                    <div class="col-sm-offset-3 col-sm-9">
                        <i class="waves-effect waves-light light-btn waves-input-wrapper" style=""><input type="button" value="APPLY NOW" id="apply" name="apply" class="waves-button-input"></i>
                    </div>
                </div><br>
                <center>  <div id="success_mes" class="text text-success">    </div>  </center> <br>

            </form>
</code>```

Here is theAjax:

```<code><script>

        //    start query
 $(document).ready(function () {

 $('#doctorspecilization').change(function () {

var doc_spec_id=$(this).val();

$.ajax({
            url: "phpquery/fetch_doctor_name.php", // Url to which the request is send
            method: "POST",             // Type of request to be send, called as method
            data: {doc_spec_id:doc_spec_id  },
            dataType:"text",

            success: function (data) {
                $("#doctorname").html(data);

            }

        });

    });
</script>
</code>```

I don't know where I went wrong. Any help may highly appreciated.

答:
#1 Materialize select needs initializing

I can't see any initialization in your code.

```<code>document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems);
  });

  // Or with jQuery

  $(document).ready(function(){
    $('select').formSelect();
  });
</code>```

#2 Select added dynamically will need initializing

```<code>success: function (data) {
                $("#doctorname").html(data);
                $('select').formSelect();

         }
</code>```

https://materializecss.com/select.html#initialization

ContentLicense: CC BY-SA 4.0

Body:
In my application, I am using Dynamic Dependent Select Box using Ajax and PHP. My website template is constructed using materialize js. In my console it successfully receive the values on Doctor Name in my application, but isn't load into the doctor name select box. With removing materialize js and materialize css it working fine.

Here is the code:

         <form class="form-horizontal" method="POST" id="form_apt">

Request an Appointment

                    Doctor Specilization:

                    <?php
        function load(){
           include('phpquery/dbconnection.php');
            $output='';
            $sql="SELECT * from doctorspecilization";
            $result=mysqli_query($con,$sql);
            while($row=mysqli_fetch_array($result)){
     $output.='<option value="'.$row["specilization"].'">'.$row["specilization"].'</option>';
          }
              return $output;
             }
        ?>

            <select name="doctorspecilization" id="doctorspecilization">
            <option value="">Select Specilization</option>
             <?php echo load();   ?>

                  </select>

                    Doctor :

                        <select name="doctorname" id="doctorname">
                    <option value="">Select Doctor</option>
                  </select>

                    Appointment Date:

                        <input type="date" id="date" name="date" class="form-control"
                        placeholder="Enter your education">

                        <input type="button" value="APPLY NOW" id="apply" name="apply" class="waves-button-input">

            </form>

Here is theAjax:

I don't know where I went wrong. Any help may highly appreciated.

Body:
#1 Materialize select needs initializing

I can't see any initialization in your code.

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('select');
    var instances = M.FormSelect.init(elems);
  });

  // Or with jQuery

  $(document).ready(function(){
    $('select').formSelect();
  });

#2 Select added dynamically will need initializing

success: function (data) {
                $("#doctorname").html(data);
                $('select').formSelect();

         }

https://materializecss.com/select.html#initialization


问:
Angular add a random JPG image?
I have created an Angular app that has a button which adds a new item to the list, here is a picture of it:

I searched for sites that provide random images and found "picsum.photos" (Lorem Picsum), which upon refresh indeed gives me a random picture each time.

I've tried implementing this in the code, but I'm getting the same image every time.

TypeScript Code:

```<code>imgUrl = 'https://some_long_path.jpeg';
randomImgUrl = 'https://picsum.photos/536/354';

recipes1: Recipes[] = [
    new Recipes('A Test Recipe',
      'This is simply a test', this.imgUrl)
];

addRecipe() {
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}
</code>```

HTML Code:

```<code><button class="btn btn-success" (click)="addRecipe()" (keyup.d)="removeRecipe()">New Recipe</button>
</code>```

It seems only one random image link gets saved into the variable 'randomImgUrl'...

Does anyone know what is the issue? How can I get a random image each time I call the addRecipe() function?

Thank you!

答:
You can change image by appending a cache-busting query string to the end</p>

```<code>randomImgUrl = 'https://picsum.photos/536/354?a';
</code>```

Title: Angular add a random JPG image?

Body:
I have created an Angular app that has a button which adds a new item to the list, here is a picture of it:

I searched for sites that provide random images and found "picsum.photos" (Lorem Picsum), which upon refresh indeed gives me a random picture each time.

I've tried implementing this in the code, but I'm getting the same image every time.

TypeScript Code:

imgUrl = 'https://some_long_path.jpeg';
randomImgUrl = 'https://picsum.photos/536/354';

recipes1: Recipes[] = [
    new Recipes('A Test Recipe',
      'This is simply a test', this.imgUrl)
];

addRecipe() {
   this.recipes1.push(new Recipes('name', 'description', this.randomImgUrl));
}

HTML Code:

<button class="btn btn-success" (click)="addRecipe()" (keyup.d)="removeRecipe()">New Recipe</button>

It seems only one random image link gets saved into the variable 'randomImgUrl'...

Does anyone know what is the issue? How can I get a random image each time I call the addRecipe() function?

Thank you!

Body:
You can change image by appending a cache-busting query string to the end

randomImgUrl = 'https://picsum.photos/536/354?a';


问:
Mat-table with headers in two rows, using Angular 8
I'm showing information in a table using mat-table. I have something like this:

material table

with this HTML:

```<code>  <div class="container">
   <div class="mat-elevation-z8">
    <table #dataTable mat-table [dataSource]="dataSource">
      <ng-container class="ng-hide" matColumnDef="$key">
        <th class="ng-hide" mat-header-cell *matHeaderCellDef>ID del Paciente</th>
        <td class="ng-hide" mat-cell *matCellDef="let element"> {{element.$key}} </td>
      </ng-container>

      <ng-container matColumnDef="nombre_paciente">
        <th mat-header-cell *matHeaderCellDef> Nombre </th>
        <td mat-cell *matCellDef="let element"> {{element.nombre_paciente}}</td>
      </ng-container>

      <ng-container matColumnDef="apellido_paciente">
        <th mat-header-cell *matHeaderCellDef> Apellido </th>
        <td mat-cell *matCellDef="let element"> {{element.apellido_paciente}} </td>
      </ng-container>

      <ng-container matColumnDef="dni">
        <th mat-header-cell *matHeaderCellDef> DNI </th>
        <td mat-cell *matCellDef="let element"> {{element.dni}} </td>
      </ng-container>

      <ng-container matColumnDef="fecha_nacimiento">
        <th mat-header-cell *matHeaderCellDef> Fecha de Nacimiento </th>
        <td mat-cell *matCellDef="let element"> {{element.fecha_nacimiento | date: "dd/MM/yyyy" }</td>
      </ng-container>

      <ng-container matColumnDef="obra_social">
        <th mat-header-cell *matHeaderCellDef> Obra Social </th>
        <td mat-cell *matCellDef="let element"> {{element.obra_social}} </td>
      </ng-container>

      <ng-container matColumnDef="numero_os">
        <th mat-header-cell *matHeaderCellDef> Número de Obra Social </th>
        <td mat-cell *matCellDef="let element"> {{element.numero_os}} </td>
      </ng-container>

      <ng-container matColumnDef="telefono">
        <th mat-header-cell *matHeaderCellDef> Número de teléfono </th>
        <td mat-cell *matCellDef="let element"> {{element.telefono}} </td>
      </ng-container>

      <ng-container matColumnDef="telefono_contacto">
        <th mat-header-cell *matHeaderCellDef> Teléfono de Contacto </th>
        <td mat-cell *matCellDef="let element"> {{element.telefono_contacto}} </td>
      </ng-container>

      <ng-container matColumnDef="accion">
        <th mat-header-cell *matHeaderCellDef></th>
        <td mat-cell *matCellDef="let element; let i = index;">
          <button mat-raised-button color="primary" class="push-right"
            [routerLink]="['/PacienteEdita/', element.$key]">Editar</button>
          <button mat-raised-button color="warn" (click)="deletePaciente(i, element)">Eliminar</button>
        </td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

    </table>
  </div>
</div>
</code>```

and this TS:

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { Paciente } from './../../shared/paciente';
import { MatTableDataSource, MatTable } from '@angular/material';
import { PacienteService } from './../../shared/paciente.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-pacientes-detalle',
  templateUrl: './pacientes-detalle.component.html',
  styleUrls: ['./pacientes-detalle.component.css']
})
export class PacientesDetalleComponent implements OnInit {
  id: any;
  element: Paciente;
  dataSource: MatTableDataSource<Paciente[]>;
  displayedColumns: any[] = [
    '$key',
    'nombre_paciente',
    'apellido_paciente',
    'dni',
    'fecha_nacimiento',
    'obra_social',
    'numero_os',
    'telefono',
    'telefono_contacto',
    'accion'
  ];
  @ViewChild('dataTable',{ static:false }) dataTable: MatTable<any>;
  constructor(
    private actRoute: ActivatedRoute,
    private pacienteApi: PacienteService
    ) {
  }

  ngOnInit() {
    this.id = this.actRoute.snapshot.paramMap.get('id');
    this.pacienteApi.GetPaciente(this.id).valueChanges().subscribe(data => {
      /* Data table */
      this.element = data;
      this.element.$key = this.id;
      this.dataSource = new MatTableDataSource<Paciente[]>([data]);
    })
  }
}
</code>```

I'm trying to get, using mat-table and angular 8, something like this:

table without material

The problem is i can't make it work with displayedColumns. I've tried to use two different displayed columns, but it didn't work for me.

Any suggestions?

答:
maybe this can help.

```<code><ng-container matColumnDef="nombre_paciente">
    <td mat-cell *matCellDef="let element">
       <div class="inner-col-header">Nombre<div>
       <div class="inner-col-data">{{element.nombre_paciente}}<div>
       <div class="inner-col-header">Obra Social<div>
       <div class="inner-col-data">{{element.obra_social}}<div>
    </td>
</ng-container>
</code>```

You can format your data with both classes inner-col-data and inner-col-header and get rid of not used columns ( Obra Social in this case)

Body:
I'm showing information in a table using mat-table. I have something like this:

material table

with this HTML:

      <ng-container class="ng-hide" matColumnDef="$key">
        ID del Paciente
         {{element.$key}}
      </ng-container>

      <ng-container matColumnDef="nombre_paciente">
         Nombre
         {{element.nombre_paciente}}
      </ng-container>

      <ng-container matColumnDef="apellido_paciente">
         Apellido
         {{element.apellido_paciente}}
      </ng-container>

      <ng-container matColumnDef="dni">
         DNI
         {{element.dni}}
      </ng-container>

      <ng-container matColumnDef="fecha_nacimiento">
         Fecha de Nacimiento
         {{element.fecha_nacimiento | date: "dd/MM/yyyy" }
      </ng-container>

      <ng-container matColumnDef="obra_social">
         Obra Social
         {{element.obra_social}}
      </ng-container>

      <ng-container matColumnDef="numero_os">
         Número de Obra Social
         {{element.numero_os}}
      </ng-container>

      <ng-container matColumnDef="telefono">
         Número de teléfono
         {{element.telefono}}
      </ng-container>

      <ng-container matColumnDef="telefono_contacto">
         Teléfono de Contacto
         {{element.telefono_contacto}}
      </ng-container>

      <ng-container matColumnDef="accion">

          <button mat-raised-button color="primary" class="push-right"
            [routerLink]="['/PacienteEdita/', element.$key]">Editar</button>
          <button mat-raised-button color="warn" (click)="deletePaciente(i, element)">Eliminar</button>

      </ng-container>

and this TS:

import { Component, OnInit, ViewChild } from '@angular/core';
import { Paciente } from './../../shared/paciente';
import { MatTableDataSource, MatTable } from '@angular/material';
import { PacienteService } from './../../shared/paciente.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-pacientes-detalle',
  templateUrl: './pacientes-detalle.component.html',
  styleUrls: ['./pacientes-detalle.component.css']
})
export class PacientesDetalleComponent implements OnInit {
  id: any;
  element: Paciente;
  dataSource: MatTableDataSource<Paciente[]>;
  displayedColumns: any[] = [
    '$key',
    'nombre_paciente',
    'apellido_paciente',
    'dni',
    'fecha_nacimiento',
    'obra_social',
    'numero_os',
    'telefono',
    'telefono_contacto',
    'accion'
  ];
  @ViewChild('dataTable',{ static:false }) dataTable: MatTable<any>;
  constructor(
    private actRoute: ActivatedRoute,
    private pacienteApi: PacienteService
    ) {
  }

  ngOnInit() {
    this.id = this.actRoute.snapshot.paramMap.get('id');
    this.pacienteApi.GetPaciente(this.id).valueChanges().subscribe(data => {
      /* Data table */
      this.element = data;
      this.element.$key = this.id;
      this.dataSource = new MatTableDataSource<Paciente[]>([data]);
    })
  }
}

I'm trying to get, using mat-table and angular 8, something like this:

table without material

The problem is i can't make it work with displayedColumns. I've tried to use two different displayed columns, but it didn't work for me.

Any suggestions?

Body:
maybe this can help.

<ng-container matColumnDef="nombre_paciente">
    <td mat-cell *matCellDef="let element">
       <div class="inner-col-header">Nombre<div>
       <div class="inner-col-data">{{element.nombre_paciente}}<div>
       <div class="inner-col-header">Obra Social<div>
       <div class="inner-col-data">{{element.obra_social}}<div>
    </td>
</ng-container>

You can format your data with both classes inner-col-data and inner-col-header and get rid of not used columns ( Obra Social in this case)


答:
Could you please try following, written and tested with shown samples. This solution will take care of inserting new lines even if you have more than 1 occurrences present in your single line too.</p>

```<code>awk '
match($0,/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\|0/){
  val=substr($0,RSTART+RLENGTH)
  if(val){
    num=gsub(/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\|0/,"&")
    while(++count<num){
      sub(/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\|0/,"&\n")
    }
  }
  val=count=num=""
}
1
'  Input_file
</code>```

Title: Bash command/script to split line on a certain character

Body:
I would like to split the below data to the expected output:

Raw Data:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Expected Output:

931096|376601|1|ART|AT-2151780724|2151780724|2|102809198|I|CGM44I|MIL3VF03|52576377.3600|PENDING|MO|PEND-INFO|Pend ACS4R|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|52576377.3600|1317720|system|2020-02-13 02:00:42|0
931097|375789|1|AYT|AT-2151509210|2151509210|7|102614605|A|CTHGMI|OZF19|444006.6400|APPROVED|NULL|APPROVED|Approved|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|kg17718|NULL|NULL|0.0000|1317722|system|2020-02-13 02:00:43|0
931098|375979|1|AHT|AT-2151780726|2151780726|2|102809199|I|CGMI|MILaesLF11|26312.0000|PENDING|MO|PEND-INFO|Pend ACRES|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|26312.0000|1317721|system|2020-02-13 02:00:43|0
931099|376572|1|AT|AT-2151399812|2151399812|5|102673999|I|CG2rMI|WEL44LF15|60991.6956|PENDING|MO|PEND-INFO|Pend ACERS|N|N|N|N|N|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|NULL|N|NULL|NULL|N|system|NULL|NULL|0.0000|1317723|system|2020-02-13 02:00:45|0

Basically the \n character is getting lost sometimes in the data and the lines are getting merged. Sometimes more than 1 line gets merged as well (even the opposite happens but we can get to that later).

The data always has 43 columns | separated. The last but one column(42nd) always is a timestamp and the last column is usually 0 or 1.

Trying for the below approach:
If cols > 43
Split 44th column to add \n and print the remaining.
Repeat process until cols=43

echo "${curr}" | awk -F\| ' { if(NF > 43) {for(i=43;i<NF;i++) "sed '${NR}s/\(^0\)/\1\n/p' $i" }}' filename

Body:
Could you please try following, written and tested with shown samples. This solution will take care of inserting new lines even if you have more than 1 occurrences present in your single line too.

awk '
match($0,/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\|0/){
  val=substr($0,RSTART+RLENGTH)
  if(val){
    num=gsub(/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\|0/,"&")
    while(++count<num){
      sub(/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}\|0/,"&\n")
    }
  }
  val=count=num=""
}
1
'  Input_file


问:
c# winforms communication between user controls
I'm new to the whole winforms programming. In the beginning, it seemed like all the code was ending up I'm the main form class. So i searched up how you're meant to organize code in winforms apps.

One solution I am trying right now is separate parts of the interface into user controls.

The problem is I'm not sure of the best way to communicate between controls and the main form. For example. Lets say I have a shape drawing type editing app. There's the main form and a user control which draws the objects. The main form holds the objects. And the user is able to select objects to edit and the selected object needs to be highlighted. So every time the selection changes, the main form has to tell the display control which object is now selected. Imagine if I had several user controls that needed to know information about the state in the main form. Every time something changed I'd have to call functions in all the controls to let them update. So in addition to the main form having to store a reference to the selected object all the controls are storing it as well. And i have to make sure they are all updated.

Another issue I have is that, I have a user control that lets you set properties of objects such as size or color. In order for the main form to know that a property changed, I need a custom event for each changeable setting, and then raise those events whenever a text box or checkbox changes and pass the value back. This seems like a lot of extra work. If everything was on the main form it would be so much easier. But then the main form class would be a million lines.

Am I going about all this the wrong way?

答:
You can make your controls bind to an event on the main form. You can then raise that event from the main form and all your controls will be notified.

If you want to make the main form aware of changing properties in objects, you could implement the INotifyPropertyChanged interface on your objects. See here.


问:
Why hasn't this list changed?
In the following code, the function modify_list want to modify b, but it failed, the print result is [1,2,3]. why hasn't the list a changed?</p>

```<code>def modify_list(b):
    b = [1,2]
a = [1,2,3]
modify_list(a)
print(a)
</code>```

答:
you are declaring other local variable b, if you want to mutate you can do:

```<code>b[:] = [1, 2]
</code>```

or even better you can return your desired value for list a

if you want to change your list a value you can assign the desired value:

```<code>a = [1, 2]
</code>```

Title: Why hasn't this list changed?

Body:
In the following code, the function modify_list want to modify b, but it failed, the print result is [1,2,3]. why hasn't the list a changed?

def modify_list(b):
    b = [1,2]
a = [1,2,3]
modify_list(a)
print(a)

Body:
you are declaring other local variable b, if you want to mutate you can do:

b[:] = [1, 2]

or even better you can return your desired value for list a

if you want to change your list a value you can assign the desired value:

a = [1, 2]


问:
StoreDevTools crash on an older setup
I am trying to instrument StoreDevTools with an oldish version of Angular (4.1.x) and @ngrx/store (5.2.0).

The zone.js version installed is 0.8.29

If I do the recommended way (ie. after StoreModule and EffectsModule) (app.module.ts):

```<code>    StoreModule.forRoot({}),
    EffectsModule.forRoot([]),

    StoreDevtoolsModule.instrument({
        name: 'myApp',
        maxAge: 50,
    }),
</code>```

then the StoreDevTools crash with

```<code>Error:
zone.js?6788:682 Unhandled Promise rejection: Object(...) is not a function ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Object(...) is not a function
    at new StoreDevtools (store-devtools.js?51ff:764)
</code>```

the js line referred says:

```<code>var liftedAction$ = merge(merge(actions$.asObservable().pipe(skip(1)), extension.actions$).pipe(map(liftAction)), dispatcher, extension.liftedActions$).pipe(observeOn(queueScheduler));
</code>```

When I do the other way around, the StoreDevTols don't crash, but the inspector cannot see the store in there.

Both modules are receiving empty data because I am just putting the store in place and I start with a feature module.

```<code>    StoreModule.forFeature('Feature1', feature1Reducer),
    EffectsModule.forFeature([
        Feature1Effects,
    ]),
</code>```

There is no data stored at the root level, like app or auth just yet.

Is the error caused by dependencies (like zone.js for example) or by how I set up my store?

Redux DevTools 2.17.0

答:
Old question, but if it helps anyone - I had a the same error after upgrading an old app to use @ngrx/store to 4.1.1

I had to match @ngrx/store-devtools to the same version number as the other @ngrx deps.

npm had initially installed it at latest which was 8.x at time of writing.  As soon as the deps were matched the app and store loaded fine

```<code>"@angular/core": "5.2.11",
...
"@ngrx/effects": "4.1.1",
"@ngrx/store": "4.1.1",
"@ngrx/store-devtools": "4.1.1",
....
"zone.js": "0.8.12"
</code>```

Title: StoreDevTools crash on an older setup

Body:
I am trying to instrument StoreDevTools with an oldish version of Angular (4.1.x) and @ngrx/store (5.2.0).

The zone.js version installed is 0.8.29

If I do the recommended way (ie. after StoreModule and EffectsModule) (app.module.ts):

    StoreModule.forRoot({}),
    EffectsModule.forRoot([]),

    StoreDevtoolsModule.instrument({
        name: 'myApp',
        maxAge: 50,
    }),

then the StoreDevTools crash with

Error:
zone.js?6788:682 Unhandled Promise rejection: Object(...) is not a function ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Object(...) is not a function
    at new StoreDevtools (store-devtools.js?51ff:764)

the js line referred says:

var liftedAction$ = merge(merge(actions$.asObservable().pipe(skip(1)), extension.actions$).pipe(map(liftAction)), dispatcher, extension.liftedActions$).pipe(observeOn(queueScheduler));

When I do the other way around, the StoreDevTols don't crash, but the inspector cannot see the store in there.

Both modules are receiving empty data because I am just putting the store in place and I start with a feature module.

    StoreModule.forFeature('Feature1', feature1Reducer),
    EffectsModule.forFeature([
        Feature1Effects,
    ]),

There is no data stored at the root level, like app or auth just yet.

Is the error caused by dependencies (like zone.js for example) or by how I set up my store?

Redux DevTools 2.17.0

Body:
Old question, but if it helps anyone - I had a the same error after upgrading an old app to use @ngrx/store to 4.1.1

I had to match @ngrx/store-devtools to the same version number as the other @ngrx deps.

npm had initially installed it at latest which was 8.x at time of writing.  As soon as the deps were matched the app and store loaded fine

"@angular/core": "5.2.11",
...
"@ngrx/effects": "4.1.1",
"@ngrx/store": "4.1.1",
"@ngrx/store-devtools": "4.1.1",
....
"zone.js": "0.8.12"


问:
SQL Server 2016 Management Studio doesn't keep line numbers
I can't get SQL Server 2016 Management Studio to remember that I want line numbers. Every time I open an instance, I have to turn line numbers on, but when I open a new instance, they've been turned off again.

Does anyone know how to make them stay on permanently or whether this is a bug within SSMS?

答:
Even though the answer to this question was already given, i was looking for how to put line numbers on the editor and the answer was not given, so here it is!

Step1: Go to Tools > Options.

Step2: In the Options dialog box navigate to Text Editor >
  Transact-SQL > General.

Step 3: Check “Line Numbers” and click on “OK” Now, when a query
  window is opened Line Numbers will be displayed


问:
CA2000 Dispose warning when reference held in a ConcurrentDictionary
I have a parent class that has a collection of child classes. Both classes are IDisposable. I am receiving warning CA2000 ("Call Dispose on object ... before all references to it are out of scope."), but I don't want to Dispose() it in the same method call it's created, as the child has a long lifetime. I'm keeping a reference to it in the parent class. If that reference is in a Dictionary or a ConcurrentBag, all is well. If the reference is in a ConcurrentDictionary, CA2000 is listed.

As far as I can tell I'm implementing IDisposable correctly. Perhaps the way I'm iterating a concurrent collection and calling Dispose() could be improved, although I suspect that's not the source of the warning.

Is this a bug in the compiler/warnings, or can I achieve compliance through code? My stab at a theory is that it's being of the function syntax used to add the reference, but I'm not sure.

The following example reproduces the warning, with child1 and child3 being fine, but child2 producing the warning, when the only difference is the container type:

```<code>using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

public class ParentDisposable : IDisposable
{
    private readonly Dictionary<string, ChildDisposable> dictionary = new Dictionary<string, ChildDisposable>();
    private readonly ConcurrentDictionary<string, ChildDisposable> concurrentDictionary = new ConcurrentDictionary<string, ChildDisposable>();
    private readonly ConcurrentBag<ChildDisposable> concurrentBag = new ConcurrentBag<ChildDisposable>();

    public void CreateChild()
    {
        // I want to create these disposable children, use them beyond the lifetime of this method call, and dispose of them when this parent class is disposed of
        var child1 = new ChildDisposable(); // No warning
        var child2 = new ChildDisposable(); // Warning CA2000  Call System.IDisposable.Dispose on object created by 'new ChildDisposable()' before all references to it are out of scope.
        var child3 = new ChildDisposable(); // No Warning
        this.dictionary.Add("key", child1);
        this.concurrentDictionary.AddOrUpdate("key", child2, (k, v) => child2);
        this.concurrentBag.Add(child3);
    }

    #region IDisposable Pattern
    private bool disposedValue = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposedValue)
        {
            if (disposing)
            {
                foreach (var key in this.dictionary.Keys)
                {
                    this.dictionary[key].Dispose();
                }

                foreach (var key in this.concurrentDictionary.Keys)
                {
                    this.concurrentDictionary[key].Dispose();
                }

                foreach (var child in this.concurrentBag)
                {
                    child.Dispose();
                }
            }

            this.disposedValue = true;
        }
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion IDisposable Pattern
}

public class ChildDisposable : IDisposable
{
    private EventWaitHandle waitObject = new EventWaitHandle(false, EventResetMode.AutoReset);

    #region IDisposable Pattern
    private bool disposedValue = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposedValue)
        {
            this.waitObject.Dispose();
            this.disposedValue = true;
        }
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion IDisposable Pattern
}

</code>```

答:
This is not a problem in your code, it's an oversight in the version of FxCop you are using.

This has been fixed in the latest version. See https://github.com/dotnet/roslyn-analyzers/issues/3082

Body:
I have a parent class that has a collection of child classes. Both classes are IDisposable. I am receiving warning CA2000 ("Call Dispose on object ... before all references to it are out of scope."), but I don't want to Dispose() it in the same method call it's created, as the child has a long lifetime. I'm keeping a reference to it in the parent class. If that reference is in a Dictionary or a ConcurrentBag, all is well. If the reference is in a ConcurrentDictionary, CA2000 is listed.

As far as I can tell I'm implementing IDisposable correctly. Perhaps the way I'm iterating a concurrent collection and calling Dispose() could be improved, although I suspect that's not the source of the warning.

Is this a bug in the compiler/warnings, or can I achieve compliance through code? My stab at a theory is that it's being of the function syntax used to add the reference, but I'm not sure.

The following example reproduces the warning, with child1 and child3 being fine, but child2 producing the warning, when the only difference is the container type:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

public class ParentDisposable : IDisposable
{
    private readonly Dictionary<string, ChildDisposable> dictionary = new Dictionary<string, ChildDisposable>();
    private readonly ConcurrentDictionary<string, ChildDisposable> concurrentDictionary = new ConcurrentDictionary<string, ChildDisposable>();
    private readonly ConcurrentBag<ChildDisposable> concurrentBag = new ConcurrentBag<ChildDisposable>();

    public void CreateChild()
    {
        // I want to create these disposable children, use them beyond the lifetime of this method call, and dispose of them when this parent class is disposed of
        var child1 = new ChildDisposable(); // No warning
        var child2 = new ChildDisposable(); // Warning CA2000  Call System.IDisposable.Dispose on object created by 'new ChildDisposable()' before all references to it are out of scope.
        var child3 = new ChildDisposable(); // No Warning
        this.dictionary.Add("key", child1);
        this.concurrentDictionary.AddOrUpdate("key", child2, (k, v) => child2);
        this.concurrentBag.Add(child3);
    }

    #region IDisposable Pattern
    private bool disposedValue = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposedValue)
        {
            if (disposing)
            {
                foreach (var key in this.dictionary.Keys)
                {
                    this.dictionary[key].Dispose();
                }

                foreach (var key in this.concurrentDictionary.Keys)
                {
                    this.concurrentDictionary[key].Dispose();
                }

                foreach (var child in this.concurrentBag)
                {
                    child.Dispose();
                }
            }

            this.disposedValue = true;
        }
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion IDisposable Pattern
}

public class ChildDisposable : IDisposable
{
    private EventWaitHandle waitObject = new EventWaitHandle(false, EventResetMode.AutoReset);

    #region IDisposable Pattern
    private bool disposedValue = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposedValue)
        {
            this.waitObject.Dispose();
            this.disposedValue = true;
        }
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion IDisposable Pattern
}


答:
The standard approach here is to use np.take_along_axis() in conjunction with np.expand_dims() (the core idea is presented also in the np.argmax() documentation):

```<code>np.take_along_axis(A, np.expand_dims(C, axis=0), axis=0).squeeze()
</code>```

Comparing the proposed approach with the explicit loops and the np.ogrid()-based approaches one would get:

```<code>import numpy as np

def take_by_axis_loop_fix(arr, pos):
    result = np.zeros(pos.shape, dtype=int)
    for i in range(pos.shape[0]):
        for j in range(pos.shape[1]):
            result[i, j] = arr[pos[i, j], i, j]
    return result

def take_by_axis_ogrid_fix(arr, pos):
    i, j = np.ogrid[:pos.shape[0], :pos.shape[1]]
    return arr[pos[i, j], i, j]

def take_by_axis_np(arr, pos, axis=0):
    return np.take_along_axis(arr, np.expand_dims(pos, axis=axis), axis=axis).squeeze()

def take_by_axis_ogrid(arr, pos, axis=0):
    ij = tuple(np.ogrid[tuple(slice(None, d, None) for d in pos.shape)])
    ij = ij[:axis] + (pos[ij],) + ij[axis:]
    return arr[ij]
</code>```

```<code>A_ = np.random.randint(0, 255, size=(300, 400, 500))
B_ = np.random.randint(0, 255, size=(300, 400, 500))
C_ = np.argmax(B_, axis=0)

funcs = take_by_axis_loop_fix, take_by_axis_ogrid_fix, take_by_axis_ogrid, take_by_axis_np
for func in funcs:
    print(func.__name__, np.all(func(A_, C_) == take_by_axis_loop_fix(A_, C_)))
    %timeit func(A_, C_)
    print()

# take_by_axis_loop_fix True
# 10 loops, best of 3: 114 ms per loop

# take_by_axis_ogrid_fix True
# 100 loops, best of 3: 5.94 ms per loop

# take_by_axis_ogrid True
# 100 loops, best of 3: 5.54 ms per loop

# take_by_axis_np True
# 100 loops, best of 3: 3.34 ms per loop
</code>```

indicating this to be the most efficient approach proposed so far.
Note also that the np.take_along_axis()-based and the take_by_axis_ogrid() approaches would work essentially unchanged for inputs with higher dimensionality, contrarily to the _fix approaches.

Particularly, take_by_axis_ogrid() is the axis-agnostic version of take_by_axis_ogrid_fix() which is, essentially, nth's answer.

Title: How to slice a 3D array from a 2D array without nested loops?

Body:
I have four matrices, partially created from each other:

A is a 3D matrix that represents a stack of grayscale images and is of shape (n, h, w)

B is a 3D matrix that also represents a stack of images, where each slice is individually calculated from the corresponding slice in A and is also of shape (n, h, w)

C is a 2D matrix, containing the index with the maximum value of B in z direction and is of shape (h, w)

D is a 2D matrix, where a value from A is copied from a certain slice, which is indicated by the value in C at position (x, y).

A minimum example implemented with loops would look as follows:

import numpy as np

A = np.random.randint(0, 255, size=(3, 4, 5))
B = np.random.randint(0, 255, size=(3, 4, 5))
C = np.argmax(B, axis=0)

D = np.zeros(C.shape, dtype=int)
for y in range(C.shape[0]):
    for x in range(C.shape[1]):
        D[y, x] = A[C[y, x], y, x]

> A
array([[[ 24,  84, 155,   8, 147],
        [ 25,   4,  49, 195,  57],
        [ 93,  76, 233,  83, 177],
        [ 70, 211, 201, 132, 239]],

       [[177, 144, 247, 251, 207],
        [242, 148,  28,  40, 105],
        [181,  28, 132,  94, 196],
        [166, 121,  72,  14,  14]],

       [[ 55, 254, 140, 142,  14],
        [112,  28,  85, 112, 145],
        [ 16,  72,  16, 248, 179],
        [160, 235, 225,  14, 211]]])

> B
array([[[246,  14,  55, 163, 161],
        [  3, 152, 128, 104, 203],
        [ 43, 145,  59, 169, 242],
        [106, 169,  31, 222, 240]],

       [[ 41,  26, 239,  25,  65],
        [ 47, 252, 205, 210, 138],
        [194,  64, 135, 127, 101],
        [ 63, 208, 179, 137,  59]],

       [[112, 156, 183,  23, 253],
        [ 35,   6, 233,  42, 100],
        [ 66, 119, 102, 217,  64],
        [ 82,  67, 135,   6,   8]]])

> C
array([[0, 2, 1, 0, 2],
       [1, 1, 2, 1, 0],
       [1, 0, 1, 2, 0],
       [0, 1, 1, 0, 0]])

> D
array([[ 24, 254, 247,   8,  14],
       [242, 148,  85,  40,  57],
       [181,  76, 132, 248, 177],
       [ 70, 121,  72, 132, 239]])

My question is: How to slice A with C efficiently eliminating the nested for-loops? My initial idea was to expand C to a 3D boolean mask, where only the positions [c, y, x] are set to True and then to simply multiply it elementwise with A and take the sum over z-axis. But I can't think of an pythonesque implementation without loops (and I probably wouldn't need to create a boolean mask anymore, if I'd knew how to write that).

The closest already implemented function I found is np.choose(), but it only takes 32 elements for C.

Body:
The standard approach here is to use np.take_along_axis() in conjunction with np.expand_dims() (the core idea is presented also in the np.argmax() documentation):

np.take_along_axis(A, np.expand_dims(C, axis=0), axis=0).squeeze()

Comparing the proposed approach with the explicit loops and the np.ogrid()-based approaches one would get:

import numpy as np

def take_by_axis_loop_fix(arr, pos):
    result = np.zeros(pos.shape, dtype=int)
    for i in range(pos.shape[0]):
        for j in range(pos.shape[1]):
            result[i, j] = arr[pos[i, j], i, j]
    return result

def take_by_axis_ogrid_fix(arr, pos):
    i, j = np.ogrid[:pos.shape[0], :pos.shape[1]]
    return arr[pos[i, j], i, j]

def take_by_axis_np(arr, pos, axis=0):
    return np.take_along_axis(arr, np.expand_dims(pos, axis=axis), axis=axis).squeeze()

def take_by_axis_ogrid(arr, pos, axis=0):
    ij = tuple(np.ogrid[tuple(slice(None, d, None) for d in pos.shape)])
    ij = ij[:axis] + (pos[ij],) + ij[axis:]
    return arr[ij]

A_ = np.random.randint(0, 255, size=(300, 400, 500))
B_ = np.random.randint(0, 255, size=(300, 400, 500))
C_ = np.argmax(B_, axis=0)

funcs = take_by_axis_loop_fix, take_by_axis_ogrid_fix, take_by_axis_ogrid, take_by_axis_np
for func in funcs:
    print(func.__name__, np.all(func(A_, C_) == take_by_axis_loop_fix(A_, C_)))
    %timeit func(A_, C_)
    print()

# take_by_axis_loop_fix True
# 10 loops, best of 3: 114 ms per loop

# take_by_axis_ogrid_fix True
# 100 loops, best of 3: 5.94 ms per loop

# take_by_axis_ogrid True
# 100 loops, best of 3: 5.54 ms per loop

# take_by_axis_np True
# 100 loops, best of 3: 3.34 ms per loop

indicating this to be the most efficient approach proposed so far.
Note also that the np.take_along_axis()-based and the take_by_axis_ogrid() approaches would work essentially unchanged for inputs with higher dimensionality, contrarily to the _fix approaches.

Particularly, take_by_axis_ogrid() is the axis-agnostic version of take_by_axis_ogrid_fix() which is, essentially, nth's answer.


问:
AtomicReferenceFieldUpdater doubt
I was creating a concurrnetHashtable that is suitable for me and little different from concurrentHashMap, and i am using AtomicReferenceFieldUpdater to make CASNext operation ( usually CAS is supported but by this we can perform CASNext also ), so am i going on right path ? Though usually i get good performance in this concurrentHashTable than locking hashtable, but sometimes things doesn't work out.

So i came to following conclusion :

if number of available processor are greater than number of bucket available in the hashtable then there are higher probability of getting lock contention, so in this case concurrentHashTable is going to work better than locking approach, and ofcourse if reading are much ( journals says 85-90% reading operation) , then it's good for use ..
so please suggest me, am i going on the right path, and assuming things correctly ?

if you get time then see code on this page code
In this hash table i am doing insertions if element is not present already...
so tell me whether this is a correct lock-free approach ?

答:
in a concurrent hash map there are 3 major operations to worry about: adding a element, removing an element and rehash

in removing and adding it's easy enough with CaS only

however a rehash will introduce races left and right which can result in data being dropped, elements not being visible for some ops, infinite loops and this is very hard to get right and using r/w locks on the whole table is much easier

Title: AtomicReferenceFieldUpdater doubt


答:
```<code>getRandomImgUrl() {
  return this.randomImgUrl + '?cache=' + new Date().getTime()
}

addRecipe() {
  this.recipes1.push(new Recipes('name', 'description', this.getRandomImgUrl()));
}
</code>```

Title: Angular add a random JPG image?


问:
How to verify the body before sending the request in angular unittest
I having some trouble in making a unit test, I read a lot of articles, but none of them helped me, seems hard to make a simple test.

I need to test this function, it returns an Observable, I actually only need to verify if myBody was build correctly, I don't want to make an actual HttpRequest.

public myCoolFunction(params) {
    const myBody= new buildMyBodyModel();
    this.buildMyBody(params, myBody); // private function, will set the values for me
    return this.sendService.send(myBody); // make a htppPostRequest and returns to me a Observeble
}
```

<pre class="lang-js prettyprint-override"><code>private buildMyBody(params, myBody){
    myBody.name = params.name;
    myBody.color = params.customColor;
    myBody.count = params.number + 1;
}
</code>```

Expected myBody:

{
    name = 'Jack';
    color = 'Orange';
    count = 4;
}
```

答:
Hope this is what you're looking for:-

```<code>it('send method should be called with expected param', () => {
    const sendService = TestBed.get(SendService);
    const params = { name: 'Jack', customColor: 'Orange', number: 3 };
    spyOn(sendService, 'send');
    component.myCoolFunction(params);
    expect(sendService.send).toHaveBeenCalledWith({ name: 'Jack', color: 'Orange', count: 4 });
});
</code>```

If you only need to test if your myBody is built correctly, try this:-

```<code>it('buildMyBody should change myBody according to params', () => {
    const myBody= new buildMyBodyModel();
    const params = { name: 'Jack', customColor: 'Orange', number: 3 };
    (component as any).buildMyBody(params, myBody);
    expect(myBody).toEqual({ name: 'Jack', color: 'Orange', count: 4 });
});
</code>```

Body:
I having some trouble in making a unit test, I read a lot of articles, but none of them helped me, seems hard to make a simple test.

I need to test this function, it returns an Observable, I actually only need to verify if myBody was build correctly, I don't want to make an actual HttpRequest.

public myCoolFunction(params) {
    const myBody= new buildMyBodyModel();
    this.buildMyBody(params, myBody); // private function, will set the values for me
    return this.sendService.send(myBody); // make a htppPostRequest and returns to me a Observeble
}

private buildMyBody(params, myBody){
    myBody.name = params.name;
    myBody.color = params.customColor;
    myBody.count = params.number + 1;
}

Expected myBody:

{
    name = 'Jack';
    color = 'Orange';
    count = 4;
}

Body:
Hope this is what you're looking for:-

it('send method should be called with expected param', () => {
    const sendService = TestBed.get(SendService);
    const params = { name: 'Jack', customColor: 'Orange', number: 3 };
    spyOn(sendService, 'send');
    component.myCoolFunction(params);
    expect(sendService.send).toHaveBeenCalledWith({ name: 'Jack', color: 'Orange', count: 4 });
});

If you only need to test if your myBody is built correctly, try this:-

it('buildMyBody should change myBody according to params', () => {
    const myBody= new buildMyBodyModel();
    const params = { name: 'Jack', customColor: 'Orange', number: 3 };
    (component as any).buildMyBody(params, myBody);
    expect(myBody).toEqual({ name: 'Jack', color: 'Orange', count: 4 });
});


问:
Unselect an option using jQuery on a Bootstrap selectpicker
I am using Bootstrap for some UI elements: SelectPicker which allows a user to select multiple options and have it rendered to the screen in paragraph tags.  They should also be able to remove a selected option.

This is my code to render the selected options onto the screen, so that each option appears with an 'X' next to it, when it's clicked the selected item is removed from the screen:

```<code>//Render selected item to the screen

$('#dataCombo').change(function(){
$('#dataOutput').html('');
var values = $('#dataCombo').val();
for(var i = 0; i < values.length; i += 1) {
$('#dataOutput').append("<p class='removeable'>" + values[i] + " x </p>")
}});

//When the 'X' is clicked, remove that item

$("#dataOutput").on('click','.removeable',function(){
$(this).remove(); //this removes the item from the screen
//Next i need to unselect it from dataCombo selectpicker
var foo = $(this);
$('#dataCombo').find('[value=foo]').remove();
console.log(foo);
$('dataCombo').selectpicker('refresh');
});
</code>```

So the problem is the second half of the 'remove' code, while the item does get removed from the output display, it is still selected in the select picker, so when another item is selected - the 'removed' item is re-rendered.  Any ideas how i can do this?

The HTML is pretty simple:

```<code><h6>ComboBox</h6>
<select id="dataCombo"  class="selectpicker" multiple>
</select>
</code>```

答:
No need to use JQuery. Assumption that user is using bootstrap-select ... https://developer.snapappointments.com/bootstrap-select/

Make the select into a 'multiple' select list and set 'data-max-options' to 1. For example:

```<code>               <select class="selectpicker" title="Select..." multiple data-max-options="1">
                                <option>Hello Title 1</option>
                                <option>Hello Title 2</option>
                                <option>Hello Title 3</option>
               </select>
</code>```

Body:
I am using Bootstrap for some UI elements: SelectPicker which allows a user to select multiple options and have it rendered to the screen in paragraph tags.  They should also be able to remove a selected option.

This is my code to render the selected options onto the screen, so that each option appears with an 'X' next to it, when it's clicked the selected item is removed from the screen:

//Render selected item to the screen

$('#dataCombo').change(function(){
$('#dataOutput').html('');
var values = $('#dataCombo').val();
for(var i = 0; i < values.length; i += 1) {
$('#dataOutput').append("
" + values[i] + " x
")
}});

//When the 'X' is clicked, remove that item

$("#dataOutput").on('click','.removeable',function(){
$(this).remove(); //this removes the item from the screen
//Next i need to unselect it from dataCombo selectpicker
var foo = $(this);
$('#dataCombo').find('[value=foo]').remove();
console.log(foo);
$('dataCombo').selectpicker('refresh');
});

So the problem is the second half of the 'remove' code, while the item does get removed from the output display, it is still selected in the select picker, so when another item is selected - the 'removed' item is re-rendered.  Any ideas how i can do this?

The HTML is pretty simple:

ComboBox

<select id="dataCombo"  class="selectpicker" multiple>
</select>

Body:
No need to use JQuery. Assumption that user is using bootstrap-select ... https://developer.snapappointments.com/bootstrap-select/

Make the select into a 'multiple' select list and set 'data-max-options' to 1. For example:

               <select class="selectpicker" title="Select..." multiple data-max-options="1">
                                <option>Hello Title 1</option>
                                <option>Hello Title 2</option>
                                <option>Hello Title 3</option>
               </select>


问:
Why does one hot encoding improve machine learning performance?
I have noticed that when One Hot encoding is used on a particular data set (a matrix) and used as training data for learning algorithms, it gives significantly better results with respect to prediction accuracy, compared to using the original matrix itself as training data. How does this performance increase happen? </p>

答:
When you want to predict categories, you want to predict items of a set. Not using one-hot encoding is akin to letting the categories have neighbour categories (e.g.: if you did a regression with the integers of the categories instead) organized in a certain way and in a certain order.

Now, what happens if you assign category 0 to 0, category 1 to 1, and category 2 to 2 without one-hot encoding, and that your algorithm's prediction isn't sure if it should choose 0 or 2: should he predict 1 despite he thinks it's either 0 or 2?

You see where it goes. The same goes for your data inputs: if they shouldn't be supposed to be neighbours, then don't show them to your algorithm as neighbours.


问:
EF code first attach and create proxy
Let's say I have an entity Foo.

```<code>public class Foo
{
  public int Id {get;set;}
  public virtual ICollection<Bar> Bars {get;set;}
}
</code>```

When I get this entity from the db then I actually get a proxy and everything works as it should be.

But, can I attach Foo to DbContext and create the proxy manually so Bars would not return null after attaching it, but an actual collection of bars?

Meaning

```<code>var foo = new Foo { Id = 1 };
Context.Set<Foo>().Attach(foo);
foo = CreateProxyOf(foo);
var countOfBars = foo.Bars.Count();
</code>```

Is there something like CreateProxyOf?

答:
Yes there is a way but instead of Foo's constructor you must use:</p>

```<code>var set = Context.Set<Foo>();
var foo = set.Create();
foo.Id = 1;
set.Attach(foo);
var countOfBars = foo.Bars.Count();
</code>```

Title: EF code first attach and create proxy

Body:
Let's say I have an entity Foo.

public class Foo
{
  public int Id {get;set;}
  public virtual ICollection<Bar> Bars {get;set;}
}

When I get this entity from the db then I actually get a proxy and everything works as it should be.

But, can I attach Foo to DbContext and create the proxy manually so Bars would not return null after attaching it, but an actual collection of bars?

Meaning

var foo = new Foo { Id = 1 };
Context.Set<Foo>().Attach(foo);
foo = CreateProxyOf(foo);
var countOfBars = foo.Bars.Count();

Is there something like CreateProxyOf?

Body:
Yes there is a way but instead of Foo's constructor you must use:

var set = Context.Set<Foo>();
var foo = set.Create();
foo.Id = 1;
set.Attach(foo);
var countOfBars = foo.Bars.Count();


问:
Linking static ".a" libraries to an Android Studio project using Gradle and CMake
I need to link a, prebuilt ".a" static library to an Android Studio project, using CMakeLists.txt.

The .a library was properly built to armeabi, armeabiv-7a, mips and x86 (it can even be "objdumped" for "content checking") and the ".h" files are just right as well.

The goal isn't to recompile the library sources along with my Android Studio project native sources.

Also, please do not refer to solutions using NDK + Andoid.mk (CMakeLists.txt only).

Since there is no working example on this matter on the web (including the Google NDK documentation and SO), please provide every change needed to the project files and/or project structure.

I keep the ".a" file and its "include" directory on a local folder, so as a meta reference to the this location, please consider /lib.a and /include.

Thank you.

答:
After a long research on this subject, this is a working solution, with a couple of minor issues.

Issue #1:

This should work by placing the libxyz.a lib file and its include directory at {AndroidStudioProjects folder}/{The Project's name}/app/libs but for some (still unknown) reason, on my system it never worked like that.

I managed to make it work by placing both (lib file and include dir) at: {AndroidStudioProjects folder}/{The Project's name}/app/src/main/cpp/libs (which had to be created).

Issue #2:

I have faced some 32bit x 64bit linking issues so, at this point, I have given up on "fat APKs" and kept it 32bit only.

What did I do

On CMakeLists.txt add:

```<code>add_library(xyz STATIC IMPORTED)
set_target_properties(xyz PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libxyz.a)
</code>```

And on target_link_libraries (to your shared native lib), you must add the "xyz" reference:

```<code>target_link_libraries(
    #the target shared lib:
    native-lib
    #other libs to link go here
    xyz)
</code>```

Extra:

If you want to be able to include the headers to libxyz.a on your C++ code by using the default include dir, like this:

```<code>#inlcude <xyz.h>
</code>```

You must add it to CMakeLists.txt:

```<code>include_directories( ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/include )
</code>```

Making the output 32bit only

On build.gradle (Module:app) go to the "android defaultConfig" block, right before "externalNativeBuild" and add the ndk abiFilters:

```<code>android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.your.project"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters 'armeabi-v7a', 'x86'
        }
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
</code>```

Please feel free to improve this.

Body:
After a long research on this subject, this is a working solution, with a couple of minor issues.

Issue #1:

This should work by placing the libxyz.a lib file and its include directory at {AndroidStudioProjects folder}/{The Project's name}/app/libs but for some (still unknown) reason, on my system it never worked like that.

I managed to make it work by placing both (lib file and include dir) at: {AndroidStudioProjects folder}/{The Project's name}/app/src/main/cpp/libs (which had to be created).

Issue #2:

I have faced some 32bit x 64bit linking issues so, at this point, I have given up on "fat APKs" and kept it 32bit only.

What did I do

On CMakeLists.txt add:

add_library(xyz STATIC IMPORTED)
set_target_properties(xyz PROPERTIES IMPORTED_LOCATION ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/libxyz.a)

And on target_link_libraries (to your shared native lib), you must add the "xyz" reference:

target_link_libraries(
    #the target shared lib:
    native-lib
    #other libs to link go here
    xyz)

Extra:

If you want to be able to include the headers to libxyz.a on your C++ code by using the default include dir, like this:

#inlcude <xyz.h>

You must add it to CMakeLists.txt:

include_directories( ${CMAKE_SOURCE_DIR}/libs/${ANDROID_ABI}/include )

Making the output 32bit only

On build.gradle (Module:app) go to the "android defaultConfig" block, right before "externalNativeBuild" and add the ndk abiFilters:

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.your.project"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            abiFilters 'armeabi-v7a', 'x86'
        }
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }

Please feel free to improve this.


答:
If you want something like this to work you can do:

```<code>def modify_list(b):
    return [1,2]
a = [1,2,3]
a = modify_list(a)
print(a)
</code>```

Or

```<code>def modify_list(b):
    b[:] = [1,2]
a = [1,2,3]
modify_list(a)
print(a)
</code>```

Title: Why hasn't this list changed?

Body:
If you want something like this to work you can do:

def modify_list(b):
    return [1,2]
a = [1,2,3]
a = modify_list(a)
print(a)

Or

def modify_list(b):
    b[:] = [1,2]
a = [1,2,3]
modify_list(a)
print(a)


问:
Using filter with pipe, getting error on length of result
I want to select the "clarity" of each diamond, where the cut == "Premium"

I have the following code:

```<code>> (dia <- select(diamonds, clarity, cut) %>%
          filter(dia, cut == "Premium"))
</code>```

I am getting these errors:

```<code>Error: Result must have length 53940, not 107880
In addition: Warning messages:
1: In Ops.ordered(left, right) : '&' is not meaningful for ordered factors
2: In Ops.ordered(left, right) : '&' is not meaningful for ordered factors
</code>```

Thanks for any guidence

答:
We don't need to pass the data object when using pipes:

```<code>dia <- select(ggplot2::diamonds, clarity, cut) %>%
         filter(cut == "Premium")
</code>```

Or even clearer:

```<code>library(ggplot2)
library(dplyr)
dia <- diamonds %>%
       select(clarity, cut) %>%
       filter(cut == "Premium")
</code>```

Body:
I want to select the "clarity" of each diamond, where the cut == "Premium"

I have the following code:

> (dia <- select(diamonds, clarity, cut) %>%
          filter(dia, cut == "Premium"))

I am getting these errors:

Error: Result must have length 53940, not 107880
In addition: Warning messages:
1: In Ops.ordered(left, right) : '&' is not meaningful for ordered factors
2: In Ops.ordered(left, right) : '&' is not meaningful for ordered factors

Thanks for any guidence

Body:
We don't need to pass the data object when using pipes:

dia <- select(ggplot2::diamonds, clarity, cut) %>%
         filter(cut == "Premium")

Or even clearer:

library(ggplot2)
library(dplyr)
dia <- diamonds %>%
       select(clarity, cut) %>%
       filter(cut == "Premium")


问:
Identical Oracle db setups: exception on just one of them
edit: Look to the end of this question for what caused the error and how I found out.

I have a very strange exception thrown on me from Hibernate when I run an app that does batch inserts of data into an oracle database. The error comes from the Oracle database, ORA-00001, which

" means that an attempt has been made to
  insert a record with a duplicate
  (unique) key. This error will also be
  generated if an existing record is
  updated to generate a duplicate
  (unique) key."

The error is weird because I have created the same table (exactly same definition) on another machine where I do NOT get the same error if I use that through my app. AND all the data get inserted into the database, so nothing is really rejected.

There has to be something different between the two setups, but the only thing I can see that is different is the banner output that I get when issuing

```<code>select * from v$version where banner like 'Oracle%';
</code>```

The database that gives me trouble:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod

The one that works:
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production

Table definitions, input, and the app I wrote is the same for both. The table involved is basically a four column table with a composite id (serviceid, date, value1, value2) - nothing fancy.

Any ideas on what can be wrong? I have started out clean several times, dropping both tables to start on equal grounds, but I still get the error from the database.

Some more of the output:

```<code>Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint (STATISTICS.PRIMARY_KEY_CONSTRAINT) violated

    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:367)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:8728)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
</code>```

How I found out what caused the problem

Thanks to APC and ik_zelf I was able to pinpoint the root cause of this error. It turns out the Quartz scheduler was wrongly configured for the production database (where the error turned up).
For the job running against the non-failing oracle server I had <cronTriggerExpression>0/5 * * * * ?</cronTriggerExpression> which ran the batch job every five seconds. I figured that once a minute was sufficent for the other oracle server, and set the quartz scheduler up with * */1 * * * ?. This turns out to be wrong, and instead of running every minute, this ran every second!

Each job took approximately 1.5-2 seconds, and thus two or more jobs were running concurrently, thus causing simultaneous inserts on the server. So instead of inserting 529 elements, I was getting anywhere from 1000 to 2000 inserts. Changing the crontrigger expression to the same as the other one, running every five seconds, fixed the problem.

To find out what was wrong I had to set true in hibernate.cfg.xml and disable the primary key constraint on the table.

```<code>-- To catch exceptions
-- to find the offending rows run the following query
-- SELECT * FROM uptime_statistics, EXCEPTIONS WHERE MY_TABLE.rowid = EXCEPTIONS.row_id;
create table exceptions(row_id rowid,
                        owner varchar2(30),
                        table_name varchar2(30),
                        constraint varchar2(30));

-- This table was set up
CREATE TABLE MY_TABLE
  (
    LOGDATE DATE NOT NULL,
    SERVICEID           VARCHAR2(255 CHAR) NOT NULL,
    PROP_A   NUMBER(10,0),
    PROP_B NUMBER(10,0),
    CONSTRAINT PK_CONSTRAINT PRIMARY KEY (LOGDATE, SERVICEID)
  );

-- Removed the constraint to see what was inserted twice or more
alter table my_table
  disable constraint PK_CONSTRAINT;

-- Enable this later on to find rows that offend the constraints
alter table my_table
  enable constraint PK_CONSTRAINT
    exceptions into exceptions;
</code>```

答:
You have a unique compound constraint.  ORA-00001 means that you have two or more rows which have duplicate values in  ServiceID, Date, Value1 and/or Value2.  You say the input is the same for both databases.  So either:

you are imagining that your program is hurling ORA-00001

you are mistaken that the input is the same in both runs.

The more likely explanation is the second one: one or more of your key columns is populated by an external source or default value (e.g. code table for ServiceId or SYSDATE for the date column).  In your failing database this automatic population is failing to provide a unique value.  There can be any number of reasons why this might be so, depending on what mechanism(s) you're using.  Remember that in a unique compound key NULL entries count.  That is, you can have any number of records (NULL,NULL.NULL,NULL) but only one for (42,NULL,NULL,NULL).

It is hard for us to guess what the actual problem might be, and almost as hard for you (although you do have the advantage of being the code's author, which ought to grant you some insight).  What you need is some trace statements.  My preferred solution would be to use Bulk DML Exception Handling but then I am a PL/SQL fan.  Hibernate allows you to hook in some logging to your programs: I suggest you switch it on.  Code is a heck of a lot easier to debug when it has decent instrumentation.

As a last resort, disable the constraint before running the batch insert.  Afterwards re-enable it like this:

```<code>alter table t42
    enable constraint t42_uk
        exceptions into my_exceptions
/
</code>```

This will fail if you have duplicate rows but crucially the MY_EXCEPTIONS table will list all the rows which clash.  That at least will give you some clue as to the source of the duplication.  If you don't already have an exceptions table you will have to run a script: $ORACLE_HOME/rdbms/admin/utlexcptn.sql ( you may need a DBA to gain access to this directory).

tl;dr

insight requires information: instrument your code.

Body:
edit: Look to the end of this question for what caused the error and how I found out.

I have a very strange exception thrown on me from Hibernate when I run an app that does batch inserts of data into an oracle database. The error comes from the Oracle database, ORA-00001, which

" means that an attempt has been made to
  insert a record with a duplicate
  (unique) key. This error will also be
  generated if an existing record is
  updated to generate a duplicate
  (unique) key."

The error is weird because I have created the same table (exactly same definition) on another machine where I do NOT get the same error if I use that through my app. AND all the data get inserted into the database, so nothing is really rejected.

There has to be something different between the two setups, but the only thing I can see that is different is the banner output that I get when issuing

select * from v$version where banner like 'Oracle%';

The database that gives me trouble:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod

The one that works:
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production

Table definitions, input, and the app I wrote is the same for both. The table involved is basically a four column table with a composite id (serviceid, date, value1, value2) - nothing fancy.

Any ideas on what can be wrong? I have started out clean several times, dropping both tables to start on equal grounds, but I still get the error from the database.

Some more of the output:

Caused by: java.sql.BatchUpdateException: ORA-00001: unique constraint (STATISTICS.PRIMARY_KEY_CONSTRAINT) violated

    at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:367)
    at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:8728)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)

How I found out what caused the problem

Thanks to APC and ik_zelf I was able to pinpoint the root cause of this error. It turns out the Quartz scheduler was wrongly configured for the production database (where the error turned up).
For the job running against the non-failing oracle server I had <cronTriggerExpression>0/5 * * * * ?</cronTriggerExpression> which ran the batch job every five seconds. I figured that once a minute was sufficent for the other oracle server, and set the quartz scheduler up with * */1 * * * ?. This turns out to be wrong, and instead of running every minute, this ran every second!

Each job took approximately 1.5-2 seconds, and thus two or more jobs were running concurrently, thus causing simultaneous inserts on the server. So instead of inserting 529 elements, I was getting anywhere from 1000 to 2000 inserts. Changing the crontrigger expression to the same as the other one, running every five seconds, fixed the problem.

To find out what was wrong I had to set true in hibernate.cfg.xml and disable the primary key constraint on the table.

-- To catch exceptions
-- to find the offending rows run the following query
-- SELECT * FROM uptime_statistics, EXCEPTIONS WHERE MY_TABLE.rowid = EXCEPTIONS.row_id;
create table exceptions(row_id rowid,
                        owner varchar2(30),
                        table_name varchar2(30),
                        constraint varchar2(30));

-- This table was set up
CREATE TABLE MY_TABLE
  (
    LOGDATE DATE NOT NULL,
    SERVICEID           VARCHAR2(255 CHAR) NOT NULL,
    PROP_A   NUMBER(10,0),
    PROP_B NUMBER(10,0),
    CONSTRAINT PK_CONSTRAINT PRIMARY KEY (LOGDATE, SERVICEID)
  );

-- Removed the constraint to see what was inserted twice or more
alter table my_table
  disable constraint PK_CONSTRAINT;

-- Enable this later on to find rows that offend the constraints
alter table my_table
  enable constraint PK_CONSTRAINT
    exceptions into exceptions;

Body:
You have a unique compound constraint.  ORA-00001 means that you have two or more rows which have duplicate values in  ServiceID, Date, Value1 and/or Value2.  You say the input is the same for both databases.  So either:

you are imagining that your program is hurling ORA-00001

you are mistaken that the input is the same in both runs.

The more likely explanation is the second one: one or more of your key columns is populated by an external source or default value (e.g. code table for ServiceId or SYSDATE for the date column).  In your failing database this automatic population is failing to provide a unique value.  There can be any number of reasons why this might be so, depending on what mechanism(s) you're using.  Remember that in a unique compound key NULL entries count.  That is, you can have any number of records (NULL,NULL.NULL,NULL) but only one for (42,NULL,NULL,NULL).

It is hard for us to guess what the actual problem might be, and almost as hard for you (although you do have the advantage of being the code's author, which ought to grant you some insight).  What you need is some trace statements.  My preferred solution would be to use Bulk DML Exception Handling but then I am a PL/SQL fan.  Hibernate allows you to hook in some logging to your programs: I suggest you switch it on.  Code is a heck of a lot easier to debug when it has decent instrumentation.

As a last resort, disable the constraint before running the batch insert.  Afterwards re-enable it like this:

alter table t42
    enable constraint t42_uk
        exceptions into my_exceptions
/

This will fail if you have duplicate rows but crucially the MY_EXCEPTIONS table will list all the rows which clash.  That at least will give you some clue as to the source of the duplication.  If you don't already have an exceptions table you will have to run a script: $ORACLE_HOME/rdbms/admin/utlexcptn.sql ( you may need a DBA to gain access to this directory).

tl;dr

insight requires information: instrument your code.


问:
How to check if a character is a letter or a number in javascript?
I am new to javascript I'm trying to check user entered the alphabet or a number.
if the user enters "A" it shows Alphabet it's ok but if the user enters "1" I want to show Number but its show alphabet.
where i done wrong.
Thanks Advance

```<code>function CHECKCHARATCTER(Letter) {
    if (Letter.length <= 1) {
      if ((64 < Letter.charCodeAt(0) < 91) || (96 < Letter.charCodeAt(0) < 123)) {
        return "Alphabhate";
      }
      else if (47 < Letter.charCodeAt(0) < 58) {
        return "NUMBER";
      }
      else { return "Its NOt a NUMBER or Alphabets"; }
    }
    else { return ("Please enter the single character"); }
}
a = prompt("enter the number or Alphabhate");
alert(typeof (a));
b = CHECKCHARATCTER(a);
alert(b);
</code>```

答:
I modified you conditions as it's shown in the following code. Also you can check it out here</p>

```<code>function CHECKCHARATCTER(Letter){
    if (Letter.length <= 1)
    {
        if (Letter.toUpperCase() != Letter.toLowerCase()) {
            return "Alphabet";
        }
        else if (!isNaN( Letter)) {
            return "Number";
        } else{
            return "Its Not a Number or Alphabet";
        }
    }
    else {
        return("Please enter the single character");
    }
}
input = prompt("enter the Number or Alphabet");
output = CHECKCHARATCTER(input);
alert(output);
</code>```

Body:
I am new to javascript I'm trying to check user entered the alphabet or a number.
if the user enters "A" it shows Alphabet it's ok but if the user enters "1" I want to show Number but its show alphabet.
where i done wrong.
Thanks Advance

function CHECKCHARATCTER(Letter) {
    if (Letter.length <= 1) {
      if ((64 < Letter.charCodeAt(0) < 91) || (96 < Letter.charCodeAt(0) < 123)) {
        return "Alphabhate";
      }
      else if (47 < Letter.charCodeAt(0) < 58) {
        return "NUMBER";
      }
      else { return "Its NOt a NUMBER or Alphabets"; }
    }
    else { return ("Please enter the single character"); }
}
a = prompt("enter the number or Alphabhate");
alert(typeof (a));
b = CHECKCHARATCTER(a);
alert(b);

Body:
I modified you conditions as it's shown in the following code. Also you can check it out here

function CHECKCHARATCTER(Letter){
    if (Letter.length <= 1)
    {
        if (Letter.toUpperCase() != Letter.toLowerCase()) {
            return "Alphabet";
        }
        else if (!isNaN( Letter)) {
            return "Number";
        } else{
            return "Its Not a Number or Alphabet";
        }
    }
    else {
        return("Please enter the single character");
    }
}
input = prompt("enter the Number or Alphabet");
output = CHECKCHARATCTER(input);
alert(output);


问:
Adding NewRelic PHP agent via Ansible
I've been trying to install NewRelic agent for PHP on Amazon Linux 2 the "ansible way", but I cannot get it to work with either rpm_key or yum_repository. I've also tried just copying the repo file to /etc/yum.repos.d/newrelic.repo, but it's supposed to use a GPG key and the only one I found is 548C16BF.gpg and at that point I felt this was getting to hacky.

My current setup is:

- name: add the new relic repository
  # noqa 303
  command: rpm -Uvh http://yum.newrelic.com/pub/newrelic/el5/x86_64/newrelic-repo-5-3.noarch.rpm
```

but that doesn't sit well with ansible-lint (hence the rule exception).

Am I missing something here or maybe my preconception of what the "ansible-way" would be is incorrect. Asking for a friend (with a lot of Ansible experience).

答:
To add the GPG key:

```<code>- name: Adding RPM key
  rpm_key:
   state: present
   key: https://download.newrelic.com/548C16BF.gpg
</code>```

and Add the repository:

```<code>- name: Add repository
  yum_repository:
    name: rewrelic
    description: Newrelic YUM repo
    baseurl: http://yum.newrelic.com/pub/newrelic/el5/x86_64/newrelic-repo-5-3.noarch.rpm
</code>```

Finally install the yum:

```<code>- name: install Rewrelic
  yum:
    name: rewrelic
    state: present
</code>```

Title: Adding NewRelic PHP agent via Ansible

Body:
I've been trying to install NewRelic agent for PHP on Amazon Linux 2 the "ansible way", but I cannot get it to work with either rpm_key or yum_repository. I've also tried just copying the repo file to /etc/yum.repos.d/newrelic.repo, but it's supposed to use a GPG key and the only one I found is 548C16BF.gpg and at that point I felt this was getting to hacky.

My current setup is:

- name: add the new relic repository
  # noqa 303
  command: rpm -Uvh http://yum.newrelic.com/pub/newrelic/el5/x86_64/newrelic-repo-5-3.noarch.rpm

but that doesn't sit well with ansible-lint (hence the rule exception).

Am I missing something here or maybe my preconception of what the "ansible-way" would be is incorrect. Asking for a friend (with a lot of Ansible experience).

Body:
To add the GPG key:

- name: Adding RPM key
  rpm_key:
   state: present
   key: https://download.newrelic.com/548C16BF.gpg

and Add the repository:

- name: Add repository
  yum_repository:
    name: rewrelic
    description: Newrelic YUM repo
    baseurl: http://yum.newrelic.com/pub/newrelic/el5/x86_64/newrelic-repo-5-3.noarch.rpm

Finally install the yum:

- name: install Rewrelic
  yum:
    name: rewrelic
    state: present


问:
Flutter: How can I make a drawer opened at the start?
I want to make the drawer opened when a user navigate to the screen. How can I do it?</p>

```<code>  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Header(),
      drawer: Theme(
        child: Drawer(
          elevation: 0,
        ),
      ),
    );
  }
</code>```

答:
You need to create a GlobalKey and use it as the Scaffold's key.

Then you need to use the key to call openDrawer on state initialization.

This is the corresponding code :

```<code>GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    openDrawer();
  }

  openDrawer() async {
    await Future.delayed(Duration.zero);
    _scaffoldKey.currentState.openDrawer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      drawer: Drawer(

      ),
      body: Center()
    );
  }
</code>```

Body:
I want to make the drawer opened when a user navigate to the screen. How can I do it?

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Header(),
      drawer: Theme(
        child: Drawer(
          elevation: 0,
        ),
      ),
    );
  }

Body:
You need to create a GlobalKey and use it as the Scaffold's key.

Then you need to use the key to call openDrawer on state initialization.

This is the corresponding code :

GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    openDrawer();
  }

  openDrawer() async {
    await Future.delayed(Duration.zero);
    _scaffoldKey.currentState.openDrawer();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      drawer: Drawer(

      ),
      body: Center()
    );
  }


问:
Cypress chrome not pausing at debugger statement
I have the following code in the test:

```<code>it('shows correct language', () => {
  cy.visit('/product/my product');
  cy.changeLanguage('English');
  cy.get('[data-test=attribute-name]').should(
    (elements) => {
      console.log('this shows in console', elements);
      alert('But it wont break!!!!!!!!!!');//this alert shows
      debugger;//never breaks here
    },
  );
});
</code>```

Started cypress with ./node_modules/.bin/cypress open then I run the test in the cypress window, that opens chrome and I open the dev tools manually (don't know how tell cypress to open chrome with devtools open).

It shows the message in the console and shows the alert but never actually breaks. In the sources tab the "Deactivate breakpoints" is not set so breakpoints are active.

Manually set the breakpoint and then click the "Run all test" button after the first run will pause on the manually set breakpoint but ignores the debugger statement.

答:
I think I've managed to solve the issue you're having

Rather than using debugger, you can use cy.debug(). But for it to work, you NEED to have your debugger/console open when running the test.

Check out this page for more info: https://docs.cypress.io/api/commands/debug.html

Body:
I have the following code in the test:

it('shows correct language', () => {
  cy.visit('/product/my product');
  cy.changeLanguage('English');
  cy.get('[data-test=attribute-name]').should(
    (elements) => {
      console.log('this shows in console', elements);
      alert('But it wont break!!!!!!!!!!');//this alert shows
      debugger;//never breaks here
    },
  );
});

Started cypress with ./node_modules/.bin/cypress open then I run the test in the cypress window, that opens chrome and I open the dev tools manually (don't know how tell cypress to open chrome with devtools open).

It shows the message in the console and shows the alert but never actually breaks. In the sources tab the "Deactivate breakpoints" is not set so breakpoints are active.

Manually set the breakpoint and then click the "Run all test" button after the first run will pause on the manually set breakpoint but ignores the debugger statement.


问:
Setting Cookies using Http4s Client
I am using Http4s library to make HTTP calls to a REST web service. the rest web service requires me to set an authentication cookie.

I have written the following code to set this cookie.

```<code>val client = PooledHttp1Client()
val uri = Uri.uri("http://localhost/restService")
val req = Request(GET, uri)
req.headers.put(`Content-Type`(MediaType.`application/json`))
val cookie = org.http4s.Cookie("foo_session", getLoginSessionId, domain = Some("localhost"), path=Some("/"))
req.headers.put(org.http4s.headers.Cookie(cookie))
val task = client.expect[Response](req)
val list = task.run
list.response.foreach(println)
client.shutdownNow()
</code>```

When I run this code I get a 401 error, meaning that the web service does not recognize that the cookie was set.

Now If I write the same code using apache http client. then everything works fine. The code below is doing exactly the same thing as above.

```<code>  val get = new HttpGet(s"http://localhost/restService")
  get.setHeader("Content-type", "application/json")
  val client = new DefaultHttpClient()
  val respHandler = new BasicResponseHandler
  val cookieStore = new BasicCookieStore()
  val cookie1 = new BasicClientCookie("foo_session", getLoginSessionId)
  cookie1.setDomain("localhost")
  cookie1.setPath("/")
  cookieStore.addCookie(cookie1)
  val localContext = new BasicHttpContext()
  localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore)
  localContext
  val responseString = client.execute(get, respHandler, cookieContext)
  val list = parse(responseString).extract[Response]
  list.response.foreach(println)
  list.response
</code>```

答:
It seems that your cookie is not used into response.
Did you try to use the following approach : </p>

```<code>val cookie = org.http4s.ResponseCookie("token", su.token.getOrElse("No token"), httpOnly = true, secure = true)
Ok("resp").map(_.addCookie(cookie))
</code>```

Title: Setting Cookies using Http4s Client

Body:
I am using Http4s library to make HTTP calls to a REST web service. the rest web service requires me to set an authentication cookie.

I have written the following code to set this cookie.

val client = PooledHttp1Client()
val uri = Uri.uri("http://localhost/restService")
val req = Request(GET, uri)
req.headers.put(`Content-Type`(MediaType.`application/json`))
val cookie = org.http4s.Cookie("foo_session", getLoginSessionId, domain = Some("localhost"), path=Some("/"))
req.headers.put(org.http4s.headers.Cookie(cookie))
val task = client.expect[Response](req)
val list = task.run
list.response.foreach(println)
client.shutdownNow()

When I run this code I get a 401 error, meaning that the web service does not recognize that the cookie was set.

Now If I write the same code using apache http client. then everything works fine. The code below is doing exactly the same thing as above.

  val get = new HttpGet(s"http://localhost/restService")
  get.setHeader("Content-type", "application/json")
  val client = new DefaultHttpClient()
  val respHandler = new BasicResponseHandler
  val cookieStore = new BasicCookieStore()
  val cookie1 = new BasicClientCookie("foo_session", getLoginSessionId)
  cookie1.setDomain("localhost")
  cookie1.setPath("/")
  cookieStore.addCookie(cookie1)
  val localContext = new BasicHttpContext()
  localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore)
  localContext
  val responseString = client.execute(get, respHandler, cookieContext)
  val list = parse(responseString).extract[Response]
  list.response.foreach(println)
  list.response

Body:
It seems that your cookie is not used into response.
Did you try to use the following approach :

val cookie = org.http4s.ResponseCookie("token", su.token.getOrElse("No token"), httpOnly = true, secure = true)
Ok("resp").map(_.addCookie(cookie))