问:
How I do a Bluetooth auto pairing?
I'm working on Android Studio, doing an app with 2 activities. In the first one, you can scan near devices and when you touch some device, the app change to the next activity. If the device hasn't been paired before, the connection fail or the app crashed. Im not sure the order of the Broadcast and the createBond

I tried putting createBond() after setPairingConfirmation()

```<code> private BroadcastReceiver mReceiver5 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
            try {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0);
                // the pin in case you need to accept for an specific pin
                int pin = intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",CONTRASEÑA);
                Log.d(TAG, "Start Auto Pairing. PIN = " +intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",CONTRASEÑA));
                byte[] pinBytes;
                // pinBytes = (""+pin).getBytes("UTF-8");
                pinBytes = ("" + pin).getBytes("UTF-8");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    device.setPin(pinBytes);
                    device.setPairingConfirmation(true);
                }

            } catch (Exception e) {
                Log.e(TAG, "Error occurs when trying to auto pair");
                e.printStackTrace();
            }
        }
    }
}

 private AdapterView.OnItemClickListener mDeviceClickListener =
        new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
        // Se detiene discovery porque es muy intenso para la memoria
        mBTAdapter.cancelDiscovery();

        Log.d(TAG, "onItemClick: clickeaste sobre un dispositivo");
        String deviceName = mBTDevices.get(arg2).getName();
        String deviceAddress = mBTDevices.get(arg2).getAddress();

        Log.d(TAG, "onItemClick: deviceName = " + deviceName);
        Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

        // Crea el enlace
        // NOTA: se requiere api 17 o más
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // Entra si la versión del SDK es mayor a versión Lollipop
            Log.d(TAG, "Tratando de emparejar con: " + deviceName);
            mBTDevices.get(arg2).createBond();
        }

        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
        registerReceiver(mReceiver5,intentFilter);

        Intent i = new Intent(DispositivosBT.this, MainActivity.class); //
        i.putExtra(EXTRA_DEVICE_ADDRESS, deviceAddress);

        startActivity(i);
    }
};
</code>```

Now, when I try to connect to an unpair device, sometimes the app stop working, and other timer, the connection fails but the app continue working and if I try again to connect, the connection success.
I need to connect the an unpair device and change to the next activity

答:
The solution that I found was this one:</p>

```<code>   private AdapterView.OnItemClickListener mDeviceClickListener =
                    new AdapterView.OnItemClickListener() {
                        public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
                        cancelarDiscovery(mBTAdapter);

                        Log.d(TAG, "onItemClick: clickeaste sobre un dispositivo");
                        String deviceName = mBTDevices.get(arg2).getName();
                        deviceAddress = mBTDevices.get(arg2).getAddress();

                        Log.d(TAG, "onItemClick: deviceName = " + deviceName);
                        Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            Log.d(TAG, "Trying to pair with: " + deviceName);
                            mBTDevices.get(arg2).createBond();
                        }

                        if(mBTDevices.get(arg2).getBondState() == BluetoothDevice.BOND_BONDED){
                            nextActivity();
                        }
                      }
                };
</code>```

Title: How I do a Bluetooth auto pairing?

Body:
I'm working on Android Studio, doing an app with 2 activities. In the first one, you can scan near devices and when you touch some device, the app change to the next activity. If the device hasn't been paired before, the connection fail or the app crashed. Im not sure the order of the Broadcast and the createBond

I tried putting createBond() after setPairingConfirmation()

 private BroadcastReceiver mReceiver5 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
            try {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0);
                // the pin in case you need to accept for an specific pin
                int pin = intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",CONTRASEÑA);
                Log.d(TAG, "Start Auto Pairing. PIN = " +intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",CONTRASEÑA));
                byte[] pinBytes;
                // pinBytes = (""+pin).getBytes("UTF-8");
                pinBytes = ("" + pin).getBytes("UTF-8");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    device.setPin(pinBytes);
                    device.setPairingConfirmation(true);
                }

            } catch (Exception e) {
                Log.e(TAG, "Error occurs when trying to auto pair");
                e.printStackTrace();
            }
        }
    }
}

 private AdapterView.OnItemClickListener mDeviceClickListener =
        new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
        // Se detiene discovery porque es muy intenso para la memoria
        mBTAdapter.cancelDiscovery();

        Log.d(TAG, "onItemClick: clickeaste sobre un dispositivo");
        String deviceName = mBTDevices.get(arg2).getName();
        String deviceAddress = mBTDevices.get(arg2).getAddress();

        Log.d(TAG, "onItemClick: deviceName = " + deviceName);
        Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

        // Crea el enlace
        // NOTA: se requiere api 17 o más
        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            // Entra si la versión del SDK es mayor a versión Lollipop
            Log.d(TAG, "Tratando de emparejar con: " + deviceName);
            mBTDevices.get(arg2).createBond();
        }

        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
        registerReceiver(mReceiver5,intentFilter);

        Intent i = new Intent(DispositivosBT.this, MainActivity.class); //
        i.putExtra(EXTRA_DEVICE_ADDRESS, deviceAddress);

        startActivity(i);
    }
};

Now, when I try to connect to an unpair device, sometimes the app stop working, and other timer, the connection fails but the app continue working and if I try again to connect, the connection success.
I need to connect the an unpair device and change to the next activity

Body:
The solution that I found was this one:

   private AdapterView.OnItemClickListener mDeviceClickListener =
                    new AdapterView.OnItemClickListener() {
                        public void onItemClick(AdapterView av, View v, int arg2, long arg3) {
                        cancelarDiscovery(mBTAdapter);

                        Log.d(TAG, "onItemClick: clickeaste sobre un dispositivo");
                        String deviceName = mBTDevices.get(arg2).getName();
                        deviceAddress = mBTDevices.get(arg2).getAddress();

                        Log.d(TAG, "onItemClick: deviceName = " + deviceName);
                        Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            Log.d(TAG, "Trying to pair with: " + deviceName);
                            mBTDevices.get(arg2).createBond();
                        }

                        if(mBTDevices.get(arg2).getBondState() == BluetoothDevice.BOND_BONDED){
                            nextActivity();
                        }
                      }
                };


来源: stackexchange

问:
Printing integers in the ascending order recursively
Today, I have taken an exam, and there was a question:

Write a method which prints integer numbers in the ascending order recursively from 1 to n:

```<code>public class PrintIntegersAscendingOrder {

    static int counter = 0;
    public static void PrintIntegersAscendingOrder (int n)
    {
        if (n == 1)
        {

            System.out.printf("%d\n", ++counter);
        }
        else
        {
            System.out.printf("%d ", ++counter);
            PrintIntegersAscendingOrder(n-1);
        }

    }
    public static void main (String args[])
    {
        PrintIntegersAscendingOrder(5);
    }
}
</code>```

Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?

答:
In your code you have defined in your class a method PrintIntegersAscendingOrder having the same name of the class PrintIntegersAscendingOrder containing it. This is an error that can be avoided for example renaming the including class to PrintIntegers. Below the code of class without the error and with the recursive method:

```<code>public class PrintIntegers {
    public static void PrintIntegersAscendingOrder(int n) {
        if (n > 0) {
            PrintIntegersAscendingOrder(n - 1);
            System.out.printf("%d\n", n);
        }
    }
    public static void main (String args[]) {
        PrintIntegersAscendingOrder(5);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Today, I have taken an exam, and there was a question:

Write a method which prints integer numbers in the ascending order recursively from 1 to n:

public class PrintIntegersAscendingOrder {

    static int counter = 0;
    public static void PrintIntegersAscendingOrder (int n)
    {
        if (n == 1)
        {

            System.out.printf("%d\n", ++counter);
        }
        else
        {
            System.out.printf("%d ", ++counter);
            PrintIntegersAscendingOrder(n-1);
        }

    }
    public static void main (String args[])
    {
        PrintIntegersAscendingOrder(5);
    }
}

Although this method worked now, the initial question didn't ask for the class definition, but the method. There, I couldn't be able to fit counter (I have written counter inside the if on the paper, but it gives an error in the program). How can I write the method precisely and correctly without counter variable?

Body:
In your code you have defined in your class a method PrintIntegersAscendingOrder having the same name of the class PrintIntegersAscendingOrder containing it. This is an error that can be avoided for example renaming the including class to PrintIntegers. Below the code of class without the error and with the recursive method:

public class PrintIntegers {
    public static void PrintIntegersAscendingOrder(int n) {
        if (n > 0) {
            PrintIntegersAscendingOrder(n - 1);
            System.out.printf("%d\n", n);
        }
    }
    public static void main (String args[]) {
        PrintIntegersAscendingOrder(5);
    }
}


问:
Recommended approach for Google Maps on different computers

For Google Maps, we need :

1) Maps API key

2) SHA-1 fingerprint to be added to Google Cloud Console.

3) We need to restrict API key to prevent invalid usages(usally in production).

What if I have to run the same project on different computers?

Possible use case I know:

1) Add SHA-1 fingerprint (Both debug and release) of different computers in Google Cloud Console.

Any other approach is welcomed.

答: For an android app I think using the SHA1 fingerprint is the only way per the docs</p>


问:
Unable to convert varchar to date
I am trying to convert a function (varchar) to date, but get the below error message.

Error

Failed to convert date and / or time from string.

Script

```<code>DECLARE @MyDate date

SET @MyDate = CONVERT(date, dbo.GETMINDATE(0123), 103)

SELECT @MyDate
</code>```

The function itself returns a varchar date like so - '01 Apr 2010 08:00:00.000'.

The SQL Server host is in French settings, so perhaps it's a regional setting issue.

答:
So you guessed that it might be a regional or language setting. You guessed correctly. Tibor discusses all facets of the datetime datatype here. Specifically he mentions that the format you use (with the month abbreviation) depends on the language setting in use at runtime. Here is an fiddle to demonstrate.

So how should you fix this? Well, you could force everyone else in the world (every user in your database) to use one of the english language settings. Somehow I don't think that will go over well in the real world. Seems a team meeting might be needed to determine an appropriate path forward. This is a tough lesson to learn about software design.

Title: Unable to convert varchar to date

Body:
I am trying to convert a function (varchar) to date, but get the below error message.

Error

Failed to convert date and / or time from string.

Script

DECLARE @MyDate date

SET @MyDate = CONVERT(date, dbo.GETMINDATE(0123), 103)

SELECT @MyDate

The function itself returns a varchar date like so - '01 Apr 2010 08:00:00.000'.

The SQL Server host is in French settings, so perhaps it's a regional setting issue.


问:
destructor/callback in C for getting shared_ptr behavour
I'm writing a socket listener in C. Whenever it accepts, it creates a new thread (detached) recv the data and process.

But everytime, I need to manually call close(socket_descriptor). Had it been C++, I could have in someway choose to close it inside a destructor.

I was trying to find out something that provides me same behaviour.

Basically, I want to create something like shared_ptr in C.

Is there anyway in C where one can get a signal or a notification when an object is going out of scope?

答:
No, that's not an inherent feature of C ... to enable something like what you're asking for you would have to create some sort of call-back mechanism that would use a look-up table to match an object to its "destrutor", and call that general call-back function at the end of every function you write, or more likely, at the end of every scope where an object was declared.  I'd consider that very messy and complicated, and in the end, that's probably much more hassle than it's worth, i.e., you could simply use a goto and write all your clean-up code at the end of the function (I know in-general using goto's is considered very bad style, but for jumping to clean-up code at the end of a function, they can actually make the code much cleaner than the alternative which is to keep repeating the same clean-up code every time there's an error).

For example, suppose you had a function that allocated some memory and opened a file descriptor at some early point in the function, but then if there were some errors, could not continue ... you can't simply return an error code, you have to-do some clean-up, but it would be a pain to repeat the clean-up code over and over again right in the middle of the code:

```<code>int my_function()
{
    int* array_on_heap = malloc(ARRAYSIZE * sizeof(int));
    int file_descriptor;

    //...some code

    if (some_ptr == NULL)
        goto error_cleanup;

    //...some more code

    if (some_other_pointer != some_ptr)
        goto error_cleanup;

    //...even more code

    //normal return with no error
    return 0;

    error_cleanup:
        //clean-up code in case there was an error
        free(array_on_heap);
        close(fd);
        return -1;
}
</code>```

This deliberate and judicious use of the goto here creates a very concise area of the function where destruction and clean-up can take place, and you don't have to worry about possibly missing clean-up functionality had you decided to sprinkle clean-up code in the actual "mechanics" of the function itself.

ContentLicense: CC BY-SA 3.0

Body:
No, that's not an inherent feature of C ... to enable something like what you're asking for you would have to create some sort of call-back mechanism that would use a look-up table to match an object to its "destrutor", and call that general call-back function at the end of every function you write, or more likely, at the end of every scope where an object was declared.  I'd consider that very messy and complicated, and in the end, that's probably much more hassle than it's worth, i.e., you could simply use a goto and write all your clean-up code at the end of the function (I know in-general using goto's is considered very bad style, but for jumping to clean-up code at the end of a function, they can actually make the code much cleaner than the alternative which is to keep repeating the same clean-up code every time there's an error).

For example, suppose you had a function that allocated some memory and opened a file descriptor at some early point in the function, but then if there were some errors, could not continue ... you can't simply return an error code, you have to-do some clean-up, but it would be a pain to repeat the clean-up code over and over again right in the middle of the code:

int my_function()
{
    int* array_on_heap = malloc(ARRAYSIZE * sizeof(int));
    int file_descriptor;

    //...some code

    if (some_ptr == NULL)
        goto error_cleanup;

    //...some more code

    if (some_other_pointer != some_ptr)
        goto error_cleanup;

    //...even more code

    //normal return with no error
    return 0;

    error_cleanup:
        //clean-up code in case there was an error
        free(array_on_heap);
        close(fd);
        return -1;
}

This deliberate and judicious use of the goto here creates a very concise area of the function where destruction and clean-up can take place, and you don't have to worry about possibly missing clean-up functionality had you decided to sprinkle clean-up code in the actual "mechanics" of the function itself.


问:
State ReactJS and render method
I'm studying chapter State and lifecycle in reactJS with Clock class and I don't understand why I can re-render my variables "myFirstNumber, mySecondNumber, myWord"  which are not states when I use this code in CodePen:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
    };
    this.mySecondNumber = 0;
  }

  componentDidMount() {
    this.myFirstNumber = 0;
    this.myWord = "Start";
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );

  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date(),

    });
        this.myFirstNumber += 1;
       this.mySecondNumber += 1;
    if (this.myFirstNumber ===5) {
      this.myWord = "Finish";
    }
  }

  render() {
    return (

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

myFirstNumber from ComponentDidMount: {this.myFirstNumber}

mySecondNumber from constructor: {this.mySecondNumber}

myWord: {this.myWord}

    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
```

The render method render all DOM each seconde for my variables which are not states ?

答:
In componentDidMount() you schedule interval which triggers tick() function every second. Inside this function you update component's state by invoking setState() and passing current time as a new state value. Moreover, you modify some local variables of the class. When arguments passed to setState() are processed by JS engine, what happens asynchronously, not immediately after setState() is called, the component updates its state.

Then the render() function is called by the framework. The render() function returns output which reflects the current values of all variables requested inside render() function. If you didn't call setState() inside tick() method then you wouldn't see any changes even though you modify myFirstNumber and other variables after each second.

Title: State ReactJS and render method

Body:
I'm studying chapter State and lifecycle in reactJS with Clock class and I don't understand why I can re-render my variables "myFirstNumber, mySecondNumber, myWord"  which are not states when I use this code in CodePen:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
    };
    this.mySecondNumber = 0;
  }

  componentDidMount() {
    this.myFirstNumber = 0;
    this.myWord = "Start";
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );

  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date(),

    });
        this.myFirstNumber += 1;
       this.mySecondNumber += 1;
    if (this.myFirstNumber ===5) {
      this.myWord = "Finish";
    }
  }

  render() {
    return (

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

myFirstNumber from ComponentDidMount: {this.myFirstNumber}

mySecondNumber from constructor: {this.mySecondNumber}

myWord: {this.myWord}

    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

The render method render all DOM each seconde for my variables which are not states ?


问:
Angular Mat-table Paginator breaks while sort works
I'm working on a table which shows a list of data (retrieved from the API).
After quite some headache, I managed to get the sort and filter working, but now my paginator isn't working. I came across some similar questions, but none of them seem to work for me.

I've placed my paginator outside my ngIf-div to make sure that isn't the cause of the problem.
I first thought it had something to do with the async loading, since it also affected by sorting, but now that is fixed and I still struggle with the paginator.

Below I've placed my HTML and TS file.

  <mat-table [dataSource]="dataSource" class="mat-elevation-z4" matSort>

    <ng-container matColumnDef="userid">
      <mat-header-cell *matHeaderCellDef mat-sort-header> No. </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.userid}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="email">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Email </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="role">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Role </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.role}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="company">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Company </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.company}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="sector">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Sector </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.sector}} </mat-cell>
    </ng-container>

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

<mat-paginator [pageSize]="20" [pageSizeOptions]="[5, 10, 20, 50]" showFirstLastButtons></mat-paginator>
```

<pre class="lang-js prettyprint-override"><code>export class UserListComponent implements OnInit {
  hasParticipantsError: boolean;
  isParticipantLoading: boolean;

  participants: Array<UserElement> = [];

  displayedColumns: string[] = [
    'userid',
    'name',
    'email',
    'role',
    'company',
    'sector'
  ];

  dataSource: MatTableDataSource<UserElement> = new MatTableDataSource<UserElement>();

  //Tried using the set method for paginator, aswell as the function method, both didn't work
  @ViewChild(MatSort) set matSort(sort: MatSort) {
    this.dataSource.sort = sort;
  }
  @ViewChild(MatPaginator) MatPaginator(paginator: MatPaginator) {
    this.dataSource.paginator = paginator;
  }

  constructor(
    private aus: AccountService,
    private auth: AuthService,
  ) {}

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  ngOnInit() {
    this.hasParticipantsError = false;
    this.isParticipantLoading = true;
    this.aus.getAccounts(this.auth.token).subscribe(
      (results: Array<Account>) => {
        results.forEach(
          (acc: Account) => {
            this.participants.push(new UserElement(acc));
          }
        );
        this.dataSource = new MatTableDataSource<UserElement>(this.participants);
        this.isParticipantLoading = false;
        //tried asigning the paginator here, no success
      },
          () => {
            this.hasParticipantsError = true;
            this.isParticipantLoading = false;
            this.openSnackBar();
          }
    );
  }
}

</code>```

答:
You are overwriting your dataSource when your Observable emits.

Sort works because you set this.isParticipantLoading = false; after you create new dataSource, so then *ngIf="!isParticipantLoading" complies and set matSort(sort: MatSort) { } fires to set Sort to the newly created dataSource.

However, because paginator is not wrapped with *ngIf="!isParticipantLoading", it was assigned to the previous dataSource which you later overwrite:

dataSource: MatTableDataSource<UserElement> = new MatTableDataSource<UserElement>();

You probably can fix it by replacing:

this.dataSource = new MatTableDataSource<UserElement>(this.participants);

with:

this.dataSource.data = this.participants;

Body:
I'm working on a table which shows a list of data (retrieved from the API).
After quite some headache, I managed to get the sort and filter working, but now my paginator isn't working. I came across some similar questions, but none of them seem to work for me.

I've placed my paginator outside my ngIf-div to make sure that isn't the cause of the problem.
I first thought it had something to do with the async loading, since it also affected by sorting, but now that is fixed and I still struggle with the paginator.

Below I've placed my HTML and TS file.

  <mat-table [dataSource]="dataSource" class="mat-elevation-z4" matSort>

    <ng-container matColumnDef="userid">
      <mat-header-cell *matHeaderCellDef mat-sort-header> No. </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.userid}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="email">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Email </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.email}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="role">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Role </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.role}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="company">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Company </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.company}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="sector">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Sector </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.sector}} </mat-cell>
    </ng-container>

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

<mat-paginator [pageSize]="20" [pageSizeOptions]="[5, 10, 20, 50]" showFirstLastButtons></mat-paginator>

export class UserListComponent implements OnInit {
  hasParticipantsError: boolean;
  isParticipantLoading: boolean;

  participants: Array<UserElement> = [];

  displayedColumns: string[] = [
    'userid',
    'name',
    'email',
    'role',
    'company',
    'sector'
  ];

  dataSource: MatTableDataSource<UserElement> = new MatTableDataSource<UserElement>();

  //Tried using the set method for paginator, aswell as the function method, both didn't work
  @ViewChild(MatSort) set matSort(sort: MatSort) {
    this.dataSource.sort = sort;
  }
  @ViewChild(MatPaginator) MatPaginator(paginator: MatPaginator) {
    this.dataSource.paginator = paginator;
  }

  constructor(
    private aus: AccountService,
    private auth: AuthService,
  ) {}

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }

  ngOnInit() {
    this.hasParticipantsError = false;
    this.isParticipantLoading = true;
    this.aus.getAccounts(this.auth.token).subscribe(
      (results: Array<Account>) => {
        results.forEach(
          (acc: Account) => {
            this.participants.push(new UserElement(acc));
          }
        );
        this.dataSource = new MatTableDataSource<UserElement>(this.participants);
        this.isParticipantLoading = false;
        //tried asigning the paginator here, no success
      },
          () => {
            this.hasParticipantsError = true;
            this.isParticipantLoading = false;
            this.openSnackBar();
          }
    );
  }
}


问:
Count same values on array using each Ruby Rails
I execute the query in the bank by the controller and I receive the data in the var when executing each on top of the var returns me an array, I wanted to count how many times the same parameter is repeated to create a counter could help me follow my code.

Rails 3.2, ruby 2.3

results os my query.. from postgresql

```<code>#<tickets title: "any text any first register ", updated_at: "2018-01-30 18:38:58", company: 89869>

#<tickets title: "any text any second register ", updated_at: "2018-06-25 20:18:20", company: 99991>
</code>```

I want to count how many times the same date is repeated regardless of the time to count the number of times that displays the same date.

答:
My usual approach is to use group_by and transform_values.

```<code>counts_by_date = tickets.group_by do |ticket|
  ticket.updated.at.strftime("%Y/%m/%d") # get Year/Month/Day as string
end.transform_values(&:count)
</code>```

With Ruby 2.7 we get tally which is slightly shorter:

```<code>counts_by_date = tickets.map do |ticket|
  ticket.updated.at.strftime("%Y/%m/%d") # get Year/Month/Day as string
end.tally
</code>```

Body:
I execute the query in the bank by the controller and I receive the data in the var when executing each on top of the var returns me an array, I wanted to count how many times the same parameter is repeated to create a counter could help me follow my code.

Rails 3.2, ruby 2.3

results os my query.. from postgresql

#<tickets title: "any text any first register ", updated_at: "2018-01-30 18:38:58", company: 89869>

#<tickets title: "any text any second register ", updated_at: "2018-06-25 20:18:20", company: 99991>

I want to count how many times the same date is repeated regardless of the time to count the number of times that displays the same date.

Body:
My usual approach is to use group_by and transform_values.

counts_by_date = tickets.group_by do |ticket|
  ticket.updated.at.strftime("%Y/%m/%d") # get Year/Month/Day as string
end.transform_values(&:count)

With Ruby 2.7 we get tally which is slightly shorter:

counts_by_date = tickets.map do |ticket|
  ticket.updated.at.strftime("%Y/%m/%d") # get Year/Month/Day as string
end.tally


问:
Error to search a location by googleMapsAutoComplete.. on react native?
When I search some place it brokes the app, here is the error:

Device: (357:37) this.mapView.animateToLocation is not a function. (In
  'this.mapView.animateToLocation({
          latitude: loc.lat,
          longitude: loc.lng
        })', 'this.mapView.animateToLocation' is undefined)

Here is the Search Input:

```<code><MapInput style = {{flex: 1, position : 'absolute'}} notifyChange={loc => this.getCoordsFromName(loc)} />
</code>```

And here is the animation marker to the chosen location:

```<code> goCoordsFromName(loc) {
    this.setState({
      region: {
        latitude: loc.lat,
        longitude: loc.lng,
      },
    });
  }

  getCoordsFromName(loc) {
    this.goCoordsFromName(loc);
    this.mapView.animateToLocation({
      latitude: loc.lat,
      longitude: loc.lng,
    })
  }

  animateToLocation = location => {
    this.mapView.animateToRegion({
      latitude: location.latitude,
      longitude: location.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
  };
</code>```

Here is the reference of the full code:

https://snack.expo.io/@matheus_cbrl/react-native-maps-autocomplete?session_id=snack-session-zEXHnaZSt&referrer=https%3A%2F%2Fmedium.com%2F%40mohammad.nicoll%2Freact-native-maps-with-autocomplete-e9c71e493974

答:
Here is a possible solution, I did it:

This:

```<code> goCoordsFromName(loc) {
    this.setState({
      region: {
        latitude: loc.lat,
        longitude: loc.lng,
      },
    });
  }

  getCoordsFromName(loc) {
    this.goCoordsFromName(loc);
    this.mapView.animateToLocation({
      latitude: loc.lat,
      longitude: loc.lng,
    })
  }

  animateToLocation = location => {
    this.mapView.animateToRegion({
      latitude: location.latitude,
      longitude: location.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
  };
</code>```

to:

```<code>  getCoordsFromName(loc) {
     this.mapView.animateToRegion({
      ...this.state.region,
      latitude: loc.lat,
      longitude: loc.lng,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
    this.setState(prevState => {
      return {
        region: {
          ...prevState.region,
          latitude: loc.lat,
          longitude: loc.lng,
        },
      };
    });
  }
</code>```

Body:
When I search some place it brokes the app, here is the error:

Device: (357:37) this.mapView.animateToLocation is not a function. (In
  'this.mapView.animateToLocation({
          latitude: loc.lat,
          longitude: loc.lng
        })', 'this.mapView.animateToLocation' is undefined)

Here is the Search Input:

<MapInput style = {{flex: 1, position : 'absolute'}} notifyChange={loc => this.getCoordsFromName(loc)} />

And here is the animation marker to the chosen location:

 goCoordsFromName(loc) {
    this.setState({
      region: {
        latitude: loc.lat,
        longitude: loc.lng,
      },
    });
  }

  getCoordsFromName(loc) {
    this.goCoordsFromName(loc);
    this.mapView.animateToLocation({
      latitude: loc.lat,
      longitude: loc.lng,
    })
  }

  animateToLocation = location => {
    this.mapView.animateToRegion({
      latitude: location.latitude,
      longitude: location.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
  };

Here is the reference of the full code:

https://snack.expo.io/@matheus_cbrl/react-native-maps-autocomplete?session_id=snack-session-zEXHnaZSt&referrer=https%3A%2F%2Fmedium.com%2F%40mohammad.nicoll%2Freact-native-maps-with-autocomplete-e9c71e493974

Body:
Here is a possible solution, I did it:

This:

 goCoordsFromName(loc) {
    this.setState({
      region: {
        latitude: loc.lat,
        longitude: loc.lng,
      },
    });
  }

  getCoordsFromName(loc) {
    this.goCoordsFromName(loc);
    this.mapView.animateToLocation({
      latitude: loc.lat,
      longitude: loc.lng,
    })
  }

  animateToLocation = location => {
    this.mapView.animateToRegion({
      latitude: location.latitude,
      longitude: location.longitude,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
  };

to:

  getCoordsFromName(loc) {
     this.mapView.animateToRegion({
      ...this.state.region,
      latitude: loc.lat,
      longitude: loc.lng,
      latitudeDelta: LATITUDE_DELTA,
      longitudeDelta: LONGITUDE_DELTA,
    });
    this.setState(prevState => {
      return {
        region: {
          ...prevState.region,
          latitude: loc.lat,
          longitude: loc.lng,
        },
      };
    });
  }


问:
Terraform and Azure Data Explorer
I am looking for recipes on how to standup a complete Azure Data Explorer stack using Terraform. So far I have found that Terraform has support to create clusters, apply access control and create databases.

I am yet to find guidance/recipes on creation of tables and table mappings.

How are others provisioning complete Azure Data Explorer stacks? What are some of the best practices to integrate create tables/table-mappings sql calls with Terraform scripts?

Thanks in advance.

答:
We found much the same. Supposedly, support for Tables and Ingestion Mappings via ARM (or perhaps APIs accessible to Terraform) will be supported at some time.

However, the ADX team within Azure refers to tables and ingestion mappings as being part of the "data plane" -- not the "control plane." So their preferred approach is to use the management commands from a Kusto client to create tables and ingestion mappings.

We wound up creating a mini-migration tool in house to handle this work for us. It basically just reads through a list of files in a directory and applies any new migrations to the database that haven't previously been run (recording successful migrations to avoid re-running them). I would love to open source this tool, but we'd need sign-off from legal. Unlike other database technology you may be familiar with, I don't believe that ADX supports transactional updates to table structure, so we didn't even bother making rollback functionality for our tool.

There are some tools you can use that don't require writing up a whole migration tool of your own: https://learn.microsoft.com/en-us/azure/kusto/tools/#source-control-integration-tools

Title: Terraform and Azure Data Explorer


问:
Can't load libOpenSLES.so when I run a android ndk application on emulator
I am trying to compile and run vlc android app on emulator on ubuntu 11.04.

I get it compiles and linked. But when I run the app on emulator, I get the following 'usr/lib/libOpenSLES.so not found' error.

I have checked that I do have libOpenSLES.so in the right path on my ubuntu environment. So why it said it can't find it?

E/LibVLC  (  443): Can't load vlcjni library: java.lang.UnsatisfiedLinkError: Cannot load library: link_image[1962]:    33 could not load needed library '/home/michael/Programs/android-ndk/platforms/android-9/arch-arm/usr/lib/libOpenSLES.so' for 'libvlcjni.so' (load_library[1104]: Library '/home/michael/Programs/android-ndk/platforms/android-9/arch-arm/usr/lib/libOpenSLES.so' not found)

答:
I looks like the app has been linked with a full path to libOpenSLES on your development machine. When you run on the emulator you want it to resolve the OpenSLES lib to the correct place on the emulator, not your dev machine.

The toolchain should already be set up to resolve the correct library paths, you should be able to link with just "-lOpenSLES" which will resolve to your NDK dir at build time and the correct location on the emulator / device at runtime.


问:
Subprocesses not running with pytest Error Processing Test
I am currently converting my unittest setup over to pytest, everything is working however on certain tests I run a command line process in order to load code into the hardware I have attached via USB. this process works fine with unittest however when using pytest or nose2 I get the response

```<code>------------------------------------------------ Captured stderr call -------------------------------------------------
Error processing Test
</code>```

this happens just when my process begins to run? I get no error message am an unsure why one is not output? The command is fine as it runs on cmd and unittest is there something I am missing in order to make it work with pytest?

For reference my class I am running

```<code>class LoadCode():

def __init__(self, comport):
    ''' Constructor
    '''

    self.filename = None
    self.code_comport = comport
    self.code_loaded = False
    self.logger = logging.getLogger(__name__)

def set_code_filename(self, new_file_name):
    ''' Sets the filename parameter for loading the code
    '''
    if (self.filename != new_file_name):
        self.filename = new_file_name
        self.logger.info("Setting code File to " + self.filename)
        self.code_loaded = False
    else:
        self.logger.info("Code File Name Is Already Set !")

def write_code(self):
    REBOOT_TIME = 50 #approximatly 50 seconds if enough for a reboot after loading boot and main   and enough time for
    SUCCESSFUL_RETURNCODE = 0   # 0 is a successful return code for subprocess

    if(self.filename != None and self.code_comport != None):
        #set up command line to run
        command = <<COMMAND>>
        self.logger.info("Running: " + command)
        #run command line as subprocess (thread will wait for command line to finish)
        load_code = subprocess.run(command)
        #successful returncode = 0 anything else means an error has occured during subprocess
        subprocess.CompletedProcess(args=[command], returncode = SUCCESSFUL_RETURNCODE)
        if (load_code.returncode == SUCCESSFUL_RETURNCODE ):
            self.code_loaded = True
            self.logger.info(self.filename)
            time.sleep(REBOOT_TIME)  #Allow reboot
    else:
        raise AssertionError("ERROR: No code File Set/No Comport Set")
    self.is_code_loaded()

def is_code_loaded(self):
    '''check the bool of code to ensure it has successfully ran
    '''
    if self.code_loaded == False:
        Print("Failed")
        raise AssertionError("Code Was Not Loaded ..")
    else:
        print("WORKED")
</code>```

答:
```<code>subprocess.CompletedProcess(args=[command], returncode = SUCCESSFUL_RETURNCODE)
</code>```

this line of code is not needed as it returns from subproccess.run(). thanks @Masklinn for pointing that out.
details: https://python.readthedocs.io/en/latest/library/subprocess.html?highlight=CompletedProcess

The path that was generated contained spaces in the middle and did not have one at the start which is why the command did not run and the error was returned! now my subprocess work perfectly fine with pytest and nose2 ! :)

Body:
I am currently converting my unittest setup over to pytest, everything is working however on certain tests I run a command line process in order to load code into the hardware I have attached via USB. this process works fine with unittest however when using pytest or nose2 I get the response

------------------------------------------------ Captured stderr call -------------------------------------------------
Error processing Test

this happens just when my process begins to run? I get no error message am an unsure why one is not output? The command is fine as it runs on cmd and unittest is there something I am missing in order to make it work with pytest?

For reference my class I am running

class LoadCode():

def __init__(self, comport):
    ''' Constructor
    '''

    self.filename = None
    self.code_comport = comport
    self.code_loaded = False
    self.logger = logging.getLogger(__name__)

def set_code_filename(self, new_file_name):
    ''' Sets the filename parameter for loading the code
    '''
    if (self.filename != new_file_name):
        self.filename = new_file_name
        self.logger.info("Setting code File to " + self.filename)
        self.code_loaded = False
    else:
        self.logger.info("Code File Name Is Already Set !")

def write_code(self):
    REBOOT_TIME = 50 #approximatly 50 seconds if enough for a reboot after loading boot and main   and enough time for
    SUCCESSFUL_RETURNCODE = 0   # 0 is a successful return code for subprocess

    if(self.filename != None and self.code_comport != None):
        #set up command line to run
        command = <<COMMAND>>
        self.logger.info("Running: " + command)
        #run command line as subprocess (thread will wait for command line to finish)
        load_code = subprocess.run(command)
        #successful returncode = 0 anything else means an error has occured during subprocess
        subprocess.CompletedProcess(args=[command], returncode = SUCCESSFUL_RETURNCODE)
        if (load_code.returncode == SUCCESSFUL_RETURNCODE ):
            self.code_loaded = True
            self.logger.info(self.filename)
            time.sleep(REBOOT_TIME)  #Allow reboot
    else:
        raise AssertionError("ERROR: No code File Set/No Comport Set")
    self.is_code_loaded()

def is_code_loaded(self):
    '''check the bool of code to ensure it has successfully ran
    '''
    if self.code_loaded == False:
        Print("Failed")
        raise AssertionError("Code Was Not Loaded ..")
    else:
        print("WORKED")

Body:
subprocess.CompletedProcess(args=[command], returncode = SUCCESSFUL_RETURNCODE)

this line of code is not needed as it returns from subproccess.run(). thanks @Masklinn for pointing that out.
details: https://python.readthedocs.io/en/latest/library/subprocess.html?highlight=CompletedProcess

The path that was generated contained spaces in the middle and did not have one at the start which is why the command did not run and the error was returned! now my subprocess work perfectly fine with pytest and nose2 ! :)


问:
Java Bouncy Castle OCSP Url
I am using bouncy castle 1.48 to verify certificate validation with OCSP. It works good.
But I'm using Ocsp Url as static variable and I want to read it from certificate. Url is written in certificate as Authority Info Access

```<code>[1]Authority Info Access
 Access Method=On-line Certificate Status Protocol (1.3.6.1.5.5.7.48.1)
 Alternative Name:
      URL=http://ocsp.mydomain
</code>```

I got org.bouncycastle.asn1.x509.AuthorityInformationAccess object from certificate

```<code>byte[] octetBytes = certificate.getExtensionValue(X509Extension.authorityInfoAccess.getId());
ASN1InputStream octetStream = new ASN1InputStream(octetBytes);
byte[] encoded = X509ExtensionUtil.fromExtensionValue(octetBytes).getEncoded();
ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(encoded));
AuthorityInformationAccess access = AuthorityInformationAccess.getInstance(seq);
</code>```

which writes AuthorityInformationAccess: Oid(1.3.6.1.5.5.7.48.1) but cant get Url from there

答:
With BouncyCastle 1.9 is:

Dependences

```<code>    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.59</version>
    </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcpkix-jdk15on</artifactId>
        <version>1.59</version>
    </dependency>
</code>```

Method for get url OCSP

```<code>private ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
    byte[] bytes = certificate.getExtensionValue(oid);
    if (bytes == null) {
        return null;
    }
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    return aIn.readObject();
}

public String getOcspUrl() throws Exception {
    ASN1Primitive obj;
    try {
        obj = getExtensionValue(getFirstCertificate(), Extension.authorityInfoAccess.getId());
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }

    if (obj == null) {
        return null;
    }

    AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.getInstance(obj);

    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {
        boolean correctAccessMethod = accessDescription.getAccessMethod().equals(X509ObjectIdentifiers.ocspAccessMethod);
        if (!correctAccessMethod) {
            continue;
        }

        GeneralName name = accessDescription.getAccessLocation();
        if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
            continue;
        }

        DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
        return derStr.getString();
    }

    return null;
}
</code>```

Function to verif revocation

```<code>public CertificateStatus verifRevocationWithOCSP(X509Certificate certificate,X509Certificate issuerCertificate) throws Exception{
    OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle();
    String urlOCSP = getOcspUrl();
    BasicOCSPResp basicOCSPResp = ocspClient.getBasicOCSPResp(certificate, issuerCertificate, urlOCSP);

    if (basicOCSPResp == null)
        throw new IOException("Error en la consulta ar servidor OCSP ["+urlOCSP+"]");

    BasicOCSPResp basicResponse = basicOCSPResp;
    SingleResp[] responses = basicResponse.getResponses();
    if (responses.length == 1) {
        SingleResp resp = responses[0];
        Object status = resp.getCertStatus();
        System.out.println("OBJECT: "+status);
        if (status == CertificateStatus.GOOD) {
            return CertificateStatus.GOOD;
        } else if (status instanceof RevokedStatus) {
            RevokedStatus revokedStatus = (RevokedStatus)status;
            return revokedStatus;
        } else if(status instanceof UnknownStatus){
            UnknownStatus unknownStatus = (UnknownStatus)status;
            return unknownStatus;
        }
        throw new IOException("Tipo de respuesta de OCSP ["+status+"] desconocido");
    }
    else
        throw new IOException("No se recibio ni una respuesta al consultar el OCSP para la URL ["+urlOCSP+"]");
}
</code>```

Title: Java Bouncy Castle OCSP Url

Body:
I am using bouncy castle 1.48 to verify certificate validation with OCSP. It works good.
But I'm using Ocsp Url as static variable and I want to read it from certificate. Url is written in certificate as Authority Info Access

[1]Authority Info Access
 Access Method=On-line Certificate Status Protocol (1.3.6.1.5.5.7.48.1)
 Alternative Name:
      URL=http://ocsp.mydomain

I got org.bouncycastle.asn1.x509.AuthorityInformationAccess object from certificate

byte[] octetBytes = certificate.getExtensionValue(X509Extension.authorityInfoAccess.getId());
ASN1InputStream octetStream = new ASN1InputStream(octetBytes);
byte[] encoded = X509ExtensionUtil.fromExtensionValue(octetBytes).getEncoded();
ASN1Sequence seq = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(encoded));
AuthorityInformationAccess access = AuthorityInformationAccess.getInstance(seq);

which writes AuthorityInformationAccess: Oid(1.3.6.1.5.5.7.48.1) but cant get Url from there

Body:
With BouncyCastle 1.9 is:

Dependences

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk15on</artifactId>
        <version>1.59</version>
    </dependency>
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcpkix-jdk15on</artifactId>
        <version>1.59</version>
    </dependency>

Method for get url OCSP

private ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
    byte[] bytes = certificate.getExtensionValue(oid);
    if (bytes == null) {
        return null;
    }
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    return aIn.readObject();
}

public String getOcspUrl() throws Exception {
    ASN1Primitive obj;
    try {
        obj = getExtensionValue(getFirstCertificate(), Extension.authorityInfoAccess.getId());
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }

    if (obj == null) {
        return null;
    }

    AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.getInstance(obj);

    AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
    for (AccessDescription accessDescription : accessDescriptions) {
        boolean correctAccessMethod = accessDescription.getAccessMethod().equals(X509ObjectIdentifiers.ocspAccessMethod);
        if (!correctAccessMethod) {
            continue;
        }

        GeneralName name = accessDescription.getAccessLocation();
        if (name.getTagNo() != GeneralName.uniformResourceIdentifier) {
            continue;
        }

        DERIA5String derStr = DERIA5String.getInstance((ASN1TaggedObject) name.toASN1Primitive(), false);
        return derStr.getString();
    }

    return null;
}

Function to verif revocation

public CertificateStatus verifRevocationWithOCSP(X509Certificate certificate,X509Certificate issuerCertificate) throws Exception{
    OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle();
    String urlOCSP = getOcspUrl();
    BasicOCSPResp basicOCSPResp = ocspClient.getBasicOCSPResp(certificate, issuerCertificate, urlOCSP);

    if (basicOCSPResp == null)
        throw new IOException("Error en la consulta ar servidor OCSP ["+urlOCSP+"]");

    BasicOCSPResp basicResponse = basicOCSPResp;
    SingleResp[] responses = basicResponse.getResponses();
    if (responses.length == 1) {
        SingleResp resp = responses[0];
        Object status = resp.getCertStatus();
        System.out.println("OBJECT: "+status);
        if (status == CertificateStatus.GOOD) {
            return CertificateStatus.GOOD;
        } else if (status instanceof RevokedStatus) {
            RevokedStatus revokedStatus = (RevokedStatus)status;
            return revokedStatus;
        } else if(status instanceof UnknownStatus){
            UnknownStatus unknownStatus = (UnknownStatus)status;
            return unknownStatus;
        }
        throw new IOException("Tipo de respuesta de OCSP ["+status+"] desconocido");
    }
    else
        throw new IOException("No se recibio ni una respuesta al consultar el OCSP para la URL ["+urlOCSP+"]");
}


问:
What does adding a second parameter in a for loop with nested enumerate() do?
I'm trying myself on Python again and I want to create a text-based Ticktacktoe.

Currently, I am working on the layout with 0 representing the empty spaces in the games and numbers up top and on the left for coordinates.This is what I have so far:

```<code>game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for row in enumerate(game):
    print(row)
</code>```

which outputs this :

```<code>     0  1  2
(0, [0, 0, 0])
(1, [0, 0, 0])
(2, [0, 0, 0])
</code>```

The problem is that I want it to look like this:

```<code>   0  1  2
0 [0, 0, 0]
1 [0, 0, 0]
2 [0, 0, 0]
</code>```

Now I found a way by adding 'count' into the for loop. But I don't understand why at all.
Looking up the Python documentation did not help.
Why is this happening? Why does that get rid of the brackets and commas?

```<code>game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for count, row in enumerate(game):
    print(count, row)
</code>```

Edit: I think I understand now.Since enumarate() returns the Index and the value all that's basically happening is that I assigned count to the Index and row to basically the value? And that is why there are now brackets since print prints more than 1 variable using a space? Could you confirm this?

答:
for row in enumerate(game):

This will print row, which is a tuple. Tuples are printed in the format
    (item1, item2, ...)

Example:

```<code>>>> row = (5, [0,0,0])
>>> print(row)
(5, [0,0,0])
</code>```

for count, row in enumerate(game):
Here, the result is unpacked. What was a tuple is now split into count and row. print can take a variable number of arguments, and by default it separates them with a space.

Example:

```<code>>>> count = 5
>>> row = [0,0,0]
>>> print(count, row)
5 [0,0,0]
</code>```

Nested Lists

A nested list is a list that contains other lists. A simple example is

```<code>nested = [[0,1,2], [3,4,5]]
</code>```

You can unpack a nested list (or any list at all)

```<code>list012, list345 = nested
</code>```

That's what for count, row in enumerate(game): is doing.

enumerate(game) returns a tuple: a counter and the normal object. We can compare it like this:

my_list = [10,20,30]
for i in my_list:
    print i    # prints 10 20 30
for i in enumerate(my_list):
    print i    # prints (0,10) (1,20) (2,30)
```

Body:
I'm trying myself on Python again and I want to create a text-based Ticktacktoe.

Currently, I am working on the layout with 0 representing the empty spaces in the games and numbers up top and on the left for coordinates.This is what I have so far:

game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for row in enumerate(game):
    print(row)

which outputs this :

     0  1  2
(0, [0, 0, 0])
(1, [0, 0, 0])
(2, [0, 0, 0])

The problem is that I want it to look like this:

   0  1  2
0 [0, 0, 0]
1 [0, 0, 0]
2 [0, 0, 0]

Now I found a way by adding 'count' into the for loop. But I don't understand why at all.
Looking up the Python documentation did not help.
Why is this happening? Why does that get rid of the brackets and commas?

game = [[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],]

print('   0  1  2')

for count, row in enumerate(game):
    print(count, row)

Edit: I think I understand now.Since enumarate() returns the Index and the value all that's basically happening is that I assigned count to the Index and row to basically the value? And that is why there are now brackets since print prints more than 1 variable using a space? Could you confirm this?

Body:
for row in enumerate(game):

This will print row, which is a tuple. Tuples are printed in the format
    (item1, item2, ...)

Example:

>>> row = (5, [0,0,0])
>>> print(row)
(5, [0,0,0])

for count, row in enumerate(game):
Here, the result is unpacked. What was a tuple is now split into count and row. print can take a variable number of arguments, and by default it separates them with a space.

Example:

>>> count = 5
>>> row = [0,0,0]
>>> print(count, row)
5 [0,0,0]

Nested Lists

A nested list is a list that contains other lists. A simple example is

nested = [[0,1,2], [3,4,5]]

You can unpack a nested list (or any list at all)

list012, list345 = nested

That's what for count, row in enumerate(game): is doing.

enumerate(game) returns a tuple: a counter and the normal object. We can compare it like this:

my_list = [10,20,30]
for i in my_list:
    print i    # prints 10 20 30
for i in enumerate(my_list):
    print i    # prints (0,10) (1,20) (2,30)


问:
Poor performance of WPF application reading from Excel on separate thread
I have some code in my project that reads from and writes into Excel 2003 using Excel COM API. Now this piece of code is called from two places:

1. From within the Excel add-in itself, on the same thread.

2. From a WPF application, where the WPF window was invoked on a separate thread.

The issue is, when the WPF application invokes the code, the normal operation of reading from Excel that should take 10 seconds is taking 2 minutes. I think it is because of the invocation from a new thread, but I'm not 100% sure.

Any ideas?

答:
You have a number of things to consider:

The COM API likely launches the Excel process.  It takes time to start the process and wait for it to be ready.

There is likely a process boundary being crossed, this is slower than in-proc stuff.

You may have fallen into the trap of thread-affinity of the COM objects you create in code.  They might have affinity with the thread they were created on, meaning even though you use a COM object on another thread, the actual running of that code is marshalled back to the owning thread of the object.  This should be obvious, however, as your UI will stutter if the code is intensive enough.

Sorry this isn't a direct answer, but it gives some points to explore.


问:
Partial functions keeping their signature
We can use purrr::partial to create partial functions:

f <- function(x, y) {
  print(x)
  print(y)
  return(invisible())
}

ff <- purrr::partial(f, y = 1)

ff(2)
#> [1] 2
#> [1] 1
```

<p><sup>Created on 2020-02-19 by the reprex package (v0.3.0)</sup></p>

<p>This can often be quite useful, but has the unfortunate side-effect that the partialized function loses it's signature, which is replaced with an elipsis:</p>

<pre class="lang-r prettyprint-override"><code>ff
#> <partialised>
#> function (...)
#> f(y = 1, ...)
</code>```

While programatically irrelevant, this leads to worse code legibility during development, where RStudio's "intellisense" can no longer aid us in remembering the names and/or order of arguments. So is there some other means of partializing which keeps the original signature (minus the partialized-away arguments), as below?

ff
#> <partialised>
#> function (x)
#> f(y = 1, x)
```

<p>Now, obviously this can be done manually, by defining a new function <code>ff</code> which is simply a wrapper around <code>f</code> with the desired arguments.</p>

<pre class="lang-r prettyprint-override"><code>ff <- function(x) f(x, y = 1)
</code>```

But this means any modifications to the signature of f need to be replicated to ff. So is there a "cleaner" way of partializing while keeping the signature?

答:
One option is to use rlang::fn_fmls() (or base::formals() equivalent) to explicitly give default values to the function arguments:

```<code># If desired, create a copy of the function first: ff <- f
rlang::fn_fmls(f) <- purrr::list_modify( rlang::fn_fmls(f), y=1 )

args(f)
# function (x, y = 1)

f(2)
# [1] 2
# [1] 1
</code>```

Body:
We can use purrr::partial to create partial functions:

f <- function(x, y) {
  print(x)
  print(y)
  return(invisible())
}

ff <- purrr::partial(f, y = 1)

ff(2)
#> [1] 2
#> [1] 1

Created on 2020-02-19 by the reprex package (v0.3.0)

This can often be quite useful, but has the unfortunate side-effect that the partialized function loses it's signature, which is replaced with an elipsis:

ff
#> <partialised>
#> function (...)
#> f(y = 1, ...)

While programatically irrelevant, this leads to worse code legibility during development, where RStudio's "intellisense" can no longer aid us in remembering the names and/or order of arguments. So is there some other means of partializing which keeps the original signature (minus the partialized-away arguments), as below?

ff
#> <partialised>
#> function (x)
#> f(y = 1, x)

Now, obviously this can be done manually, by defining a new function ff which is simply a wrapper around f with the desired arguments.

ff <- function(x) f(x, y = 1)

But this means any modifications to the signature of f need to be replicated to ff. So is there a "cleaner" way of partializing while keeping the signature?

Body:
One option is to use rlang::fn_fmls() (or base::formals() equivalent) to explicitly give default values to the function arguments:

# If desired, create a copy of the function first: ff <- f
rlang::fn_fmls(f) <- purrr::list_modify( rlang::fn_fmls(f), y=1 )

args(f)
# function (x, y = 1)

f(2)
# [1] 2
# [1] 1


问:
Why does javac allow "new CLS().new InnerCLS()" compile?
Consider the following snippet:

(I came across this syntax when inspecting some decompiled class files and this is a minimal representation)

```<code>public class Main {
    public static void main(String[] args) {
        Main.Inner o = new Main().new Inner() {};

        System.out.println("Bye from " + o.getClass());
    }

    class Inner {}
}
</code>```

This compiles and runs fine (I tested a bunch of JDKs).

Can someone please explain how come this compiles and what does this code represent?

This code creates 3 classes:

```<code>1. Main - This creates the following code (I removed the irrelevant parts):
    new Main$1
    dup
    new Main
    dup
    invokespecial Method Main <init> ()V
    dup
    invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
    pop
    invokespecial Method Main$1 <init> (LMain;)V

Why is it calling getClass (the result is popped anyway)?

2. Main$Inner - This class looks like as would expect an inner class to look

3. Main$1 - This creates the following class (I removed the irrelevant parts):
    final class Main$1 extends Main$Inner
    method <init> : (LMain;)V
    aload_0
    aload_1
    dup
    invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
    pop
    invokespecial Method Main$Inner <init> (LMain;)V
    return

Again, why is it calling getClass (the result is popped anyway)?
</code>```

BTW, it can be nested even further like this:

```<code>public class Main {
    public static void main(String[] args) {
        Object o = new Main().new Inner1().new Inner2().new Inner3() {};

        System.out.println("Bye from " + o.getClass());
    }

    class Inner1 {
        class Inner2 {
            class Inner3 {
            }
        }
    }
}
</code>```

答:
This is how instance (non-static) inner classes work. You need an instance of the outer class to instantiate instance of the inner class. This is another example:

```<code>var outer = new Outer();
var inner = outer.new Outer.Inner();
</code>```

See:

The Java™ Tutorials: Nested Classes

Body:
Consider the following snippet:

(I came across this syntax when inspecting some decompiled class files and this is a minimal representation)

public class Main {
    public static void main(String[] args) {
        Main.Inner o = new Main().new Inner() {};

        System.out.println("Bye from " + o.getClass());
    }

    class Inner {}
}

This compiles and runs fine (I tested a bunch of JDKs).

Can someone please explain how come this compiles and what does this code represent?

This code creates 3 classes:

1. Main - This creates the following code (I removed the irrelevant parts):
    new Main$1
    dup
    new Main
    dup
    invokespecial Method Main <init> ()V
    dup
    invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
    pop
    invokespecial Method Main$1 <init> (LMain;)V

Why is it calling getClass (the result is popped anyway)?

2. Main$Inner - This class looks like as would expect an inner class to look

3. Main$1 - This creates the following class (I removed the irrelevant parts):
    final class Main$1 extends Main$Inner
    method <init> : (LMain;)V
    aload_0
    aload_1
    dup
    invokevirtual Method java/lang/Object getClass ()Ljava/lang/Class;
    pop
    invokespecial Method Main$Inner <init> (LMain;)V
    return

Again, why is it calling getClass (the result is popped anyway)?

BTW, it can be nested even further like this:

public class Main {
    public static void main(String[] args) {
        Object o = new Main().new Inner1().new Inner2().new Inner3() {};

        System.out.println("Bye from " + o.getClass());
    }

    class Inner1 {
        class Inner2 {
            class Inner3 {
            }
        }
    }
}

Body:
This is how instance (non-static) inner classes work. You need an instance of the outer class to instantiate instance of the inner class. This is another example:

var outer = new Outer();
var inner = outer.new Outer.Inner();

See:

The Java™ Tutorials: Nested Classes


问:
Non-overloaded C++ Function That Can Print a vector and a vector of vectors?
Consider the following overloaded function that can print a 1d vector and a vector of vector of several types like strings, ints, doubles etc.

```<code>template<typename T>
void p(const vector<vector<T>>& vec) {
    int count = 0;
    for (vector<T> innerVec: vec) {
        cout << count++ << ": ";
        for (T e :innerVec) {
            cout << e << ' ';
        }
        cout << '\n';
    }
    cout << '\n';
}

template<typename T>
void p(const vector<T>& vec) {
    for (T e: vec) {
        cout << e << ' ';
    }
    cout << '\n';
}
</code>```

Is there anyway I can merge these two functions into 1? I tried using SFINAE and tag dispatching but all the solutions I could come up with need a macro or multiple functions and I don't want this.

I know the question might seem odd since my solution works, but I prefer having just one function in my code. This is because I want to implement a function that can detect if I am passing in a map, vector, vector of vectors, unordered_set, multimap, etc and just print that STL data structure and having one overloaded function for each specialization is a bit annoying as it gets large quick.

答:
Yes, but you need an extra parameter to distinguish the inner from the outer case

```<code>#include <vector>
#include <iostream>

struct counting_prefix {
    void call() { std::cout << count++ << ": "; }
    int count = 0;
};

struct no_prefix {
    void call() { }
};

template<typename T, typename Prefix = no_prefix>
void p(const T& e, Prefix prefix = {}) {
    prefix.call();
    std::cout << e << ' ';
}

template<typename T, typename Prefix = no_prefix>
void p(const std::vector<T>& vec, Prefix prefix = {}) {
    for (const T& e: vec) {
        prefix.call();
        p(e);
    }
    std::cout << '\n';
}

int main() {
    std::vector<std::vector<double>> stuff = { { 1., 2. }, { 3., 4. } };
    p(stuff, counting_prefix{});
}
</code>```

See it live

Body:
Consider the following overloaded function that can print a 1d vector and a vector of vector of several types like strings, ints, doubles etc.

template<typename T>
void p(const vector<vector<T>>& vec) {
    int count = 0;
    for (vector<T> innerVec: vec) {
        cout << count++ << ": ";
        for (T e :innerVec) {
            cout << e << ' ';
        }
        cout << '\n';
    }
    cout << '\n';
}

template<typename T>
void p(const vector<T>& vec) {
    for (T e: vec) {
        cout << e << ' ';
    }
    cout << '\n';
}

Is there anyway I can merge these two functions into 1? I tried using SFINAE and tag dispatching but all the solutions I could come up with need a macro or multiple functions and I don't want this.

I know the question might seem odd since my solution works, but I prefer having just one function in my code. This is because I want to implement a function that can detect if I am passing in a map, vector, vector of vectors, unordered_set, multimap, etc and just print that STL data structure and having one overloaded function for each specialization is a bit annoying as it gets large quick.

Body:
Yes, but you need an extra parameter to distinguish the inner from the outer case

#include <vector>
#include <iostream>

struct counting_prefix {
    void call() { std::cout << count++ << ": "; }
    int count = 0;
};

struct no_prefix {
    void call() { }
};

template<typename T, typename Prefix = no_prefix>
void p(const T& e, Prefix prefix = {}) {
    prefix.call();
    std::cout << e << ' ';
}

template<typename T, typename Prefix = no_prefix>
void p(const std::vector<T>& vec, Prefix prefix = {}) {
    for (const T& e: vec) {
        prefix.call();
        p(e);
    }
    std::cout << '\n';
}

int main() {
    std::vector<std::vector<double>> stuff = { { 1., 2. }, { 3., 4. } };
    p(stuff, counting_prefix{});
}

See it live


问:
Can't get input value with Twig
Hello I was trying to pass some arguments but I don't know how to get value of input using twig here is my code :
okey first of all im displaying the blog details using this detailsaction which also rendering a form to add comments to the blog ;

```<code>public function detailsAction(Request $request,Blog $blog){

        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();

        $comments = $em->getRepository(CommentaireBlog::class)->findByBlog($blog);
        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)

            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

                return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
            'comments'=>$comments,
        ));

    }

</code>```

twig page:

```<code>   {{ form_start(form) }}
                                <div class="row form-group">

                                    <div class="col col-md-3"><label class=" form-control-label">Votre Commentaire  </label></div>
                                    <div class="col-12 col-md-9"> {{ form_widget(form.contenu, { 'attr': {'class': 'form-control'} }) }}<small class="form-text text-muted"></small></div>
                                    <button type="submit" class="btn btn-default">Envoyer</button>
                                    <div class="col-12 col-md-9">
                                    </div>
                                </div>
                                    {{ form_end(form) }}

</code>```

now what i want to do is that after someone add a comment and its(racist/verbual abuse..) an other user can report the comment and a mail will be sent so i used reportAction which take three arguments the reason the message and comment id

```<code>public function reportAction($msg,$type,$id)
    {

    }
</code>```

i still didnt write inside it cause first of all i need to the value of inputs so i went to the twig page and i made this little form to get inputs but idk how to get the value
here is the form :

```<code><div class="modal-body">
  <form id="lala" method="GET">
    <label for="cars">Reason:</label>
            <select id="reportreason">
                <option value="Inappropriate Content">Inappropriate Content</option>
                 <option value="Spam">Spam</option>
                <option value="Racism">Racism</option>
                <option value="Nudity">Nudity</option>
                 <option value="Other">Other</option>
      </select>
    <div class="form-group">
        <label for="message-text" class="col-form-label">Message:</label>
        <textarea id="reportmessage" class="form-control" id="message-text"></textarea>
    </div>
  </form>
</div>
 <div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <a id="reportlink" href="{{ path('comment_report', { 'msg': form.vars.data.reportmessage ,'type': form.vars.data.reportreason, 'id': comment.id  }) }}" type="button" class="btn btn-primary">Send message</a>
</div>
</code>```

this is yml file :

```<code>blog_details:
    path:      /{id}/details
    defaults: { _controller: "BlogBundle:Blog:details" }
    methods:  [GET, POST]
comment_report:
    path:     /{msg}/{type}/{id}/report
    defaults: { _controller: "BlogBundle:Blog:report" }
    methods:  [GET, POST]
</code>```

but im getting this error now :
Neither the property "reportmessage" nor one of the methods "reportmessage()", "getreportmessage()"/"isreportmessage()" or "__call()" exist and have public access in class "BlogBundle\Entity\CommentaireBlog".

so how can i get get the value of the inputs using twig ?

答:
Twig Object Syntax https://twigfiddle.com/01iobj

Effectively the twig error message is saying that in your path() arguments, you are passing an object without an associated key as {value} The correct syntax would be {key: value} or [value], resembling a JSON syntax.

```<code>{
   "key1": { "key1a": "value1a" },
   "key2": ["value2"],
   "key3": "value3"
}
</code>```

Result

```<code>$_GET = array(
    'key1' => array('key1a' => 'value1a'),
    'key2' => array('value2'),
    'key3' => 'value3'
);
</code>```

A different approach

Looking at what you want to do, you need to refactor your approach.

First change your controller pathing for ONLY the comment.

```<code>blog_details:
    path:      /{id}/details
    defaults: { _controller: "BlogBundle:Blog:details" }
    methods:  [GET, POST]
comment_report:
    path:     /{comment}/report
    defaults: { _controller: "BlogBundle:Blog:report" }
    methods:  [POST]
</code>```

Next create a form instance for your modal, this will allow you use the FormInstance for rendering and validating the submitted form elsewhere. Ensuring that all of the validation occurs and you're not having to update different scripts for the same form.

/* /src/Form/CommentReportForm.php */

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class CommentReportForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
         $builder
             ->add('reason', Form\ChoiceType::class [
                'choices' => [
                     'Inappropriate Content' => 'Inappropriate Content',
                     'Spam' => 'Spam',
                     'Racism' => 'Racism',
                     'Nudity' => 'Nudity',
                     'Other' => 'Other'
                ]
            ])
             ->add('message', Form\TextType::class, [
                'constraints' => [
                    new Assert\Length(['min' => 10]),
                    new Assert\NotBlank(),
                ],
            ]);
    }

    public function getBlockPrefix()
    {
       return 'report_comment_form';
    }
}
```

<p>Next, update your Controller actions accordingly.</p>

<pre class="lang-php prettyprint-override"><code>public function detailsAction(Request $request, Blog $blog)
{
    if (!$user = $this->getUser()) {
        //this should be handled in your firewall configuration!!!!
        return $this->redirectToRoute('fos_user_security_login');
    }
    $em = $this->getDoctrine()->getManager();

    $add_comment = new CommentaireBlog();
    $add_comment->setBlog($blog);
    $add_comment->setUser($user);
    $add_comment->setDate(new \DateTime());

    $form = $this->createFormBuilder($add_comment)
        ->add('contenu', TextareaType::class)
        ->getForm();
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        //Symfony form sets values for the model by_reference
        $em->persist($add_comment);
        $em->flush();

        return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
    }

    /*
    * create the report form
    */
    $reportForm = $this->createForm(\App\Form\CommentReportForm::class);
    $reportForm->handleRequest($request);

    return $this->render('blog/details.html.twig', array(
        'form' => $form->createView(),
        'comment' => $add_comment,
        'blog' => $blog,
        'comments'=> $em->getRepository(CommentaireBlog::class)->findByBlog($blog),
        /*
         * give the report form a different name in twig
         */
        'report_form' => $reportForm->createView(),
    ));

}
</code>```

public function reportAction(Request $request, CommentaireBlog $comment)
{
    $reportForm = $this->createForm(\App\Form\CommentReportForm::class);
    $reportForm->handleRequest($request);
    /** @var array|string[message, reason] */
    $reportData = $reportForm->getData();
    /*
      array( 'reason' => 'value', 'message' => 'value' )
     */
    dump($reportData);
    if ($reportForm->isSubmitted() && $reportForm->isValid()) {
        //send email

        //redirect to success message
    }
    //display an error message
}
```

<p>Lastly update your view to support the new form in your modal.</p>

```

  {{ form_start(report_form, { action: path('comment_report', { comment: comment.id }) })
  {{ form_label(report_form.reason) }}
  {{ form_widget(report_form.reason) }}

      {{ form_label(report_form.message) }}
      {{ form_widget(report_form.message) }}

  {{ form_end(report_form) }}

    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Send message</button>

```

As a recommendation, I strongly urge you to record the report submissions in the database, to function as a case log and status of the reports. My approach will get you most of the way there, you would just need to create your App\Entity\CommentReport entity, with an optional association to the CommentaireBlog entity. Which would be passed to the form and adding the data_class to the form options resolver, mimicking what you have done in your other database forms.

Title: Can't get input value with Twig

Body:
Hello I was trying to pass some arguments but I don't know how to get value of input using twig here is my code :
okey first of all im displaying the blog details using this detailsaction which also rendering a form to add comments to the blog ;

public function detailsAction(Request $request,Blog $blog){

        $user=$this->getUser();
        if($user==null)
            return $this->redirectToRoute('fos_user_security_login');
        $add_comment = new CommentaireBlog();
        $em = $this->getDoctrine()->getManager();

        $comments = $em->getRepository(CommentaireBlog::class)->findByBlog($blog);
        $add_comment->setBlog($blog);
        $add_comment->setUser($user);
        $add_comment->setDate( new \DateTime());

        $form = $this->createFormBuilder($add_comment)

            ->add('contenu', TextareaType::class)

            ->getForm();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $add_comment = $form->getData();
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($add_comment);
                $em->flush();

                return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
            }
        }

        return $this->render('blog/details.html.twig', array(
            'form' => $form->createView(),
            'comment' => $add_comment,
            'blog' => $blog,
            'comments'=>$comments,
        ));

    }

twig page:

   {{ form_start(form) }}

Votre Commentaire

 {{ form_widget(form.contenu, { 'attr': {'class': 'form-control'} }) }}

                                    <button type="submit" class="btn btn-default">Envoyer</button>

                                    {{ form_end(form) }}

now what i want to do is that after someone add a comment and its(racist/verbual abuse..) an other user can report the comment and a mail will be sent so i used reportAction which take three arguments the reason the message and comment id

public function reportAction($msg,$type,$id)
    {

    }

i still didnt write inside it cause first of all i need to the value of inputs so i went to the twig page and i made this little form to get inputs but idk how to get the value
here is the form :

  <form id="lala" method="GET">
    Reason:
            <select id="reportreason">
                <option value="Inappropriate Content">Inappropriate Content</option>
                 <option value="Spam">Spam</option>
                <option value="Racism">Racism</option>
                <option value="Nudity">Nudity</option>
                 <option value="Other">Other</option>
      </select>

        Message:
        <textarea id="reportmessage" class="form-control" id="message-text"></textarea>

  </form>

    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    Send message

this is yml file :

blog_details:
    path:      /{id}/details
    defaults: { _controller: "BlogBundle:Blog:details" }
    methods:  [GET, POST]
comment_report:
    path:     /{msg}/{type}/{id}/report
    defaults: { _controller: "BlogBundle:Blog:report" }
    methods:  [GET, POST]

but im getting this error now :
Neither the property "reportmessage" nor one of the methods "reportmessage()", "getreportmessage()"/"isreportmessage()" or "__call()" exist and have public access in class "BlogBundle\Entity\CommentaireBlog".

so how can i get get the value of the inputs using twig ?

Body:
Twig Object Syntax https://twigfiddle.com/01iobj

Effectively the twig error message is saying that in your path() arguments, you are passing an object without an associated key as {value} The correct syntax would be {key: value} or [value], resembling a JSON syntax.

{
   "key1": { "key1a": "value1a" },
   "key2": ["value2"],
   "key3": "value3"
}

Result

$_GET = array(
    'key1' => array('key1a' => 'value1a'),
    'key2' => array('value2'),
    'key3' => 'value3'
);

A different approach

Looking at what you want to do, you need to refactor your approach.

First change your controller pathing for ONLY the comment.

blog_details:
    path:      /{id}/details
    defaults: { _controller: "BlogBundle:Blog:details" }
    methods:  [GET, POST]
comment_report:
    path:     /{comment}/report
    defaults: { _controller: "BlogBundle:Blog:report" }
    methods:  [POST]

Next create a form instance for your modal, this will allow you use the FormInstance for rendering and validating the submitted form elsewhere. Ensuring that all of the validation occurs and you're not having to update different scripts for the same form.

/* /src/Form/CommentReportForm.php */

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class CommentReportForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
         $builder
             ->add('reason', Form\ChoiceType::class [
                'choices' => [
                     'Inappropriate Content' => 'Inappropriate Content',
                     'Spam' => 'Spam',
                     'Racism' => 'Racism',
                     'Nudity' => 'Nudity',
                     'Other' => 'Other'
                ]
            ])
             ->add('message', Form\TextType::class, [
                'constraints' => [
                    new Assert\Length(['min' => 10]),
                    new Assert\NotBlank(),
                ],
            ]);
    }

    public function getBlockPrefix()
    {
       return 'report_comment_form';
    }
}

Next, update your Controller actions accordingly.

public function detailsAction(Request $request, Blog $blog)
{
    if (!$user = $this->getUser()) {
        //this should be handled in your firewall configuration!!!!
        return $this->redirectToRoute('fos_user_security_login');
    }
    $em = $this->getDoctrine()->getManager();

    $add_comment = new CommentaireBlog();
    $add_comment->setBlog($blog);
    $add_comment->setUser($user);
    $add_comment->setDate(new \DateTime());

    $form = $this->createFormBuilder($add_comment)
        ->add('contenu', TextareaType::class)
        ->getForm();
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        //Symfony form sets values for the model by_reference
        $em->persist($add_comment);
        $em->flush();

        return $this->redirectToRoute('blog_details', array('id' => $blog->getId()));
    }

    /*
    * create the report form
    */
    $reportForm = $this->createForm(\App\Form\CommentReportForm::class);
    $reportForm->handleRequest($request);

    return $this->render('blog/details.html.twig', array(
        'form' => $form->createView(),
        'comment' => $add_comment,
        'blog' => $blog,
        'comments'=> $em->getRepository(CommentaireBlog::class)->findByBlog($blog),
        /*
         * give the report form a different name in twig
         */
        'report_form' => $reportForm->createView(),
    ));

}

public function reportAction(Request $request, CommentaireBlog $comment)
{
    $reportForm = $this->createForm(\App\Form\CommentReportForm::class);
    $reportForm->handleRequest($request);
    /** @var array|string[message, reason] */
    $reportData = $reportForm->getData();
    /*
      array( 'reason' => 'value', 'message' => 'value' )
     */
    dump($reportData);
    if ($reportForm->isSubmitted() && $reportForm->isValid()) {
        //send email

        //redirect to success message
    }
    //display an error message
}

Lastly update your view to support the new form in your modal.

<div class="modal-body">
  {{ form_start(report_form, { action: path('comment_report', { comment: comment.id }) })
  {{ form_label(report_form.reason) }}
  {{ form_widget(report_form.reason) }}
  <div class="form-group">
      {{ form_label(report_form.message) }}
      {{ form_widget(report_form.message) }}
  </div>
  {{ form_end(report_form) }}
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Send message</button>
</div>

As a recommendation, I strongly urge you to record the report submissions in the database, to function as a case log and status of the reports. My approach will get you most of the way there, you would just need to create your App\Entity\CommentReport entity, with an optional association to the CommentaireBlog entity. Which would be passed to the form and adding the data_class to the form options resolver, mimicking what you have done in your other database forms.


问:
Spring serves static content as application/json no matter what
I have a simple Spring Boot app with a static content. I would like the browsers to cache not all but just some of the types, like css. So I added following configuration:

```<code>@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/")
                .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
}
</code>```

But now all the CSS files are server as Content-Type: application/json. Without this code they are served as text/css. I cannot figure out what am I doing wrong. Is there anything I should check or add?

Thanks in advance.

答:
you have to mention extension of the file name like *.css want to cache </p>

```<code>@Configuration
public class BaseMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/css/*.css").addResourceLocations("classpath:/static/").setCachePeriod(24 * 3600 * 365);
registry.addResourceHandler("/static/js/*.js").addResourceLocations("classpath:/static/").setCachePeriod(0);

}
}
</code>```

Body:
I have a simple Spring Boot app with a static content. I would like the browsers to cache not all but just some of the types, like css. So I added following configuration:

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/css/**").addResourceLocations("/css/")
                .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS));
}

But now all the CSS files are server as Content-Type: application/json. Without this code they are served as text/css. I cannot figure out what am I doing wrong. Is there anything I should check or add?

Thanks in advance.

Body:
you have to mention extension of the file name like *.css want to cache

@Configuration
public class BaseMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/css/*.css").addResourceLocations("classpath:/static/").setCachePeriod(24 * 3600 * 365);
registry.addResourceHandler("/static/js/*.js").addResourceLocations("classpath:/static/").setCachePeriod(0);

}
}


答: When you call this.setState function, the DOM gets rerendered. Here the DOM is getting updated every second when this.state.date gets changed through this.setState, showing new values. However, if you keep date outside of state, you can see that the DOM no longer rerenders, same result if you want to change "myWord" or "firstNumber" without changing anything in state.</p>

Title: State ReactJS and render method

Body:
I'm studying chapter State and lifecycle in reactJS with Clock class and I don't understand why I can re-render my variables "myFirstNumber, mySecondNumber, myWord"  which are not states when I use this code in CodePen:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: new Date(),
    };
    this.mySecondNumber = 0;
  }

  componentDidMount() {
    this.myFirstNumber = 0;
    this.myWord = "Start";
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );

  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date(),

    });
        this.myFirstNumber += 1;
       this.mySecondNumber += 1;
    if (this.myFirstNumber ===5) {
      this.myWord = "Finish";
    }
  }

  render() {
    return (

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

myFirstNumber from ComponentDidMount: {this.myFirstNumber}

mySecondNumber from constructor: {this.mySecondNumber}

myWord: {this.myWord}

    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

The render method render all DOM each seconde for my variables which are not states ?


问:
Kotlin multiplatform project is using old complied code
I am experimenting with kotlin multiplatform code I got some sample code running but have made changes to that code now. Every time i compile my project the old kotlin code is run instead of the new code with my changes. How do i make a clean build with the new kotlin code? i have tried invalidating the caches and restarting android, uninstalling the application, running gradle build androidJar, androidMainClasses,clean all haven't worked. Any ideas?  When i try to change the name of the method i get Caused by: java.lang.NoSuchMethodError: No static method aboutMe it can't find the new method

答: I had to delete my whole build folder and have it rebuild everything </p>