问:
How to fetch sequelize js records for today
I have a table which looks similar to the below table. I am trying to find the sum of all prices for TODAY.

```<code>| id| price |       created        |
|---|-------|----------------------|
| 0 |  500  | 2018-04-02 11:40:48  |
| 1 | 2000  | 2018-04-02 11:40:48  |
| 2 | 4000  | 2018-07-02 11:40:48  |
</code>```

The below code is what i came up with but it doesn't seem to work.

```<code>const TODAY = new Date();
const SUM = await OrdersModel.sum('price', {
    where: {
      created: TODAY,
    },
});
console.log(SUM);
</code>```

Value of SUM is 0 even though there are entries for today. I also tried the following but it too didn't work.

```<code>const TODAY = new Date();
const SUM = await OrdersModel.sum('price', {
    where: {
      created: Sequelize.DATE(TODAY),
    },
});
console.log(SUM);
</code>```

The SQL statement queried on the terminal is as follows.

Executing (default): SELECT sum(`price`) AS `sum` FROM `orders` AS `orders` WHERE `orders`.`created` = '2019-05-27 18:30:00';

答:
The problem here is that you are comparing timestamps like '2019-05-27 11:40:48' and '2019-05-27 18:30:00'. So, if we compare them it will never give us a true result because even if it were the same day (27th of May) the time is different.

Here is a possible solution.

const Op = Sequelize.Op;
const TODAY_START = new Date().setHours(0, 0, 0, 0);
const NOW = new Date();

const SUM = await OrdersModel.sum('price', {
    where: {
      created: {
        [Op.gt]: TODAY_START,
        [Op.lt]: NOW
      },
    },
 });
 console.log(SUM);
```
<p>You need to create a query like this: <code>created < [NOW] AND created > [TODAY_START]</code> <strong>Why?</strong> because you will get the sum of all the prices registered after <code>NOW</code>. This code will help you also to get the total of a range of dates.</p>
<h3>Alternative for PostgreSQL</h3>
<p>Notice that PostgreSQL allows you to truncate to specific intervals. So, you can call the <code>sequelize.fn()</code> method to use create a query that calls 'date_trunc' you can read more in this link. Like this:</p>
<pre class="lang-js prettyprint-override"><code>const SUM = await OrdersModel.sum('price', {
    where: {
      sequelize.fn('CURRENT_DATE'): {
        [Op.eq]:  sequelize.fn('date_trunc', 'day', sequelize.col('created'))
      }
    },
});
console.log(SUM);
</code>```

Also remember to update to the latest version:

npm i sequelize@5.8.6 --s
```

Body:
I have a table which looks similar to the below table. I am trying to find the sum of all prices for TODAY.

| id| price |       created        |
|---|-------|----------------------|
| 0 |  500  | 2018-04-02 11:40:48  |
| 1 | 2000  | 2018-04-02 11:40:48  |
| 2 | 4000  | 2018-07-02 11:40:48  |

The below code is what i came up with but it doesn't seem to work.

const TODAY = new Date();
const SUM = await OrdersModel.sum('price', {
    where: {
      created: TODAY,
    },
});
console.log(SUM);

Value of SUM is 0 even though there are entries for today. I also tried the following but it too didn't work.

const TODAY = new Date();
const SUM = await OrdersModel.sum('price', {
    where: {
      created: Sequelize.DATE(TODAY),
    },
});
console.log(SUM);

The SQL statement queried on the terminal is as follows.

Executing (default): SELECT sum(`price`) AS `sum` FROM `orders` AS `orders` WHERE `orders`.`created` = '2019-05-27 18:30:00';

Body:
The problem here is that you are comparing timestamps like '2019-05-27 11:40:48' and '2019-05-27 18:30:00'. So, if we compare them it will never give us a true result because even if it were the same day (27th of May) the time is different.

Here is a possible solution.

const Op = Sequelize.Op;
const TODAY_START = new Date().setHours(0, 0, 0, 0);
const NOW = new Date();

const SUM = await OrdersModel.sum('price', {
    where: {
      created: {
        [Op.gt]: TODAY_START,
        [Op.lt]: NOW
      },
    },
 });
 console.log(SUM);

You need to create a query like this: created < [NOW] AND created > [TODAY_START] Why? because you will get the sum of all the prices registered after NOW. This code will help you also to get the total of a range of dates.

Alternative for PostgreSQL

Notice that PostgreSQL allows you to truncate to specific intervals. So, you can call the sequelize.fn() method to use create a query that calls 'date_trunc' you can read more in this link. Like this:

const SUM = await OrdersModel.sum('price', {
    where: {
      sequelize.fn('CURRENT_DATE'): {
        [Op.eq]:  sequelize.fn('date_trunc', 'day', sequelize.col('created'))
      }
    },
});
console.log(SUM);

Also remember to update to the latest version:

npm i sequelize@5.8.6 --s


来源: stackexchange

问:
SQL Combining two different tables
(P.S. I am still learning SQL and you can consider me a newbie)

I have 2 sample tables as follows:

Table 1

```<code>|Profile_ID|  |Img_Path|
</code>```

Table 2

```<code>|Profile_ID|  |UName|   |Default_Title|
</code>```

My scenario is, from the 2nd table, i need to fetch all the records that contain a certain word, for which i have the following query :

```<code>Select Profile_Id,UName from
Table2 Where
Contains(Default_Title, 'Test')

ORDER BY Profile_Id
OFFSET 5 ROWS
FETCH NEXT 20 ROWS ONLY
</code>```

(Note that i am setting the OFFSET due to requirements.)

Now, the scenario is, as soon as i retrieve 1 record from the 2nd table, i need to fetch the record from the 1st table based on the Profile_Id.

So, i need to return the following 2 results in one single statement :

```<code>|Profile_Id|   |Img_Path|

|Profile_Id|   |UName|
</code>```

And i need to return the results in side-by-side columns, like :

```<code>|Profile_Id|   |Img_Path|   |UName|
</code>```

(Note i had to merge 2 Profile_Id columns into one as they both contain same data)

I am still learning SQL and i am learning about Union, Join etc. but i am a bit confused as to which way to go.

答:
You can use join:

```<code>select t1.*, t2.UName
from table1 t1 join
     (select Profile_Id, UName
      from Table2
      where Contains(Default_Title, 'Test')
      order by Profile_Id
      offset 5 rows fetch next 20 rows only
     ) t2
     on t2.profile_id = t1.profile_id
</code>```

ContentLicense: CC BY-SA 4.0

Title: SQL Combining two different tables

Body:
(P.S. I am still learning SQL and you can consider me a newbie)

I have 2 sample tables as follows:

Table 1

|Profile_ID|  |Img_Path|

Table 2

|Profile_ID|  |UName|   |Default_Title|

My scenario is, from the 2nd table, i need to fetch all the records that contain a certain word, for which i have the following query :

Select Profile_Id,UName from
Table2 Where
Contains(Default_Title, 'Test')

ORDER BY Profile_Id
OFFSET 5 ROWS
FETCH NEXT 20 ROWS ONLY

(Note that i am setting the OFFSET due to requirements.)

Now, the scenario is, as soon as i retrieve 1 record from the 2nd table, i need to fetch the record from the 1st table based on the Profile_Id.

So, i need to return the following 2 results in one single statement :

|Profile_Id|   |Img_Path|

|Profile_Id|   |UName|

And i need to return the results in side-by-side columns, like :

|Profile_Id|   |Img_Path|   |UName|

(Note i had to merge 2 Profile_Id columns into one as they both contain same data)

I am still learning SQL and i am learning about Union, Join etc. but i am a bit confused as to which way to go.

Body:
You can use join:

select t1.*, t2.UName
from table1 t1 join
     (select Profile_Id, UName
      from Table2
      where Contains(Default_Title, 'Test')
      order by Profile_Id
      offset 5 rows fetch next 20 rows only
     ) t2
     on t2.profile_id = t1.profile_id


问:
extjs how to parametrize a component
I'm trying to pass two parameters oneOfAll and twoOfAll into a container. From the initComponent function I do:

```<code>initComponent: function () {
       this.callParent(arguments);
       console.log('Results', this.oneOfAll, this.twoOfAll);
}
</code>```

and the browser's console prints the correct data, but when:

```<code>items: [
          {
              xtype: 'button',
              text: 'Other click',
              id: 'buttonClick',
              handler: function(item) {
                  Ext.Msg.alert('Other Click', '!!!' + this.oneOfAll);
              }
          },
          {
              xtype: 'button',
              text: 'CLICK',
              id: 'buttonClick_2',
              handler: function(item) {
                 Ext.Msg.alert('Other Click', '!!!' + this.twoOfAll);
              }
           }
      ]
</code>```

these values are not seen by the container config, both times undefined is returned.

I have this fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2sk3

How can I pass these parameters into the container and be seen by it?

答:
Your handler has a different scope and configs which you set are in different.

In order to fetch the values, get the reference of that component first and then try to access.

```<code>handler: function(item) {
   Ext.Msg.alert('Other Click', '!!!' + item.up().oneOfAll);
   Ext.Msg.alert('Other Click', '!!!' + item.up().twoOfAll);
}
</code>```

Title: extjs how to parametrize a component

Body:
I'm trying to pass two parameters oneOfAll and twoOfAll into a container. From the initComponent function I do:

initComponent: function () {
       this.callParent(arguments);
       console.log('Results', this.oneOfAll, this.twoOfAll);
}

and the browser's console prints the correct data, but when:

items: [
          {
              xtype: 'button',
              text: 'Other click',
              id: 'buttonClick',
              handler: function(item) {
                  Ext.Msg.alert('Other Click', '!!!' + this.oneOfAll);
              }
          },
          {
              xtype: 'button',
              text: 'CLICK',
              id: 'buttonClick_2',
              handler: function(item) {
                 Ext.Msg.alert('Other Click', '!!!' + this.twoOfAll);
              }
           }
      ]

these values are not seen by the container config, both times undefined is returned.

I have this fiddle: https://fiddle.sencha.com/#view/editor&fiddle/2sk3

How can I pass these parameters into the container and be seen by it?

Body:
Your handler has a different scope and configs which you set are in different.

In order to fetch the values, get the reference of that component first and then try to access.

handler: function(item) {
   Ext.Msg.alert('Other Click', '!!!' + item.up().oneOfAll);
   Ext.Msg.alert('Other Click', '!!!' + item.up().twoOfAll);
}


问:
how to use ngIf to show data if the value exist?
I need to show an error messege  to show on page if the data searched is not existing on database.
should I use ngIf or there is a better method to apply this?
right now once I click with the wrong data searched nothing is happening
products.component.html

```<code><fa (click)="backToHome()" class="arrow" name="chevron-left"></fa>
<h1>جستجو</h1>
<br /><br /><br /><br />
  <div class="search">
    <input class="input" [(ngModel)]="item" required placeholder="جستجو میان محصولات و برندها" />
    <fa class="icon" name="search" (click)="fetchProducts()"></fa>
  </div>
<p>تاریخچه جستجو</p>
<span>{{name}}</span>
<br />
<br />
  <ul>
    <li *ngFor="let product of resultSearch">
        <a href="#">{{product.name}}</a>

    </li>
  </ul>
 <ul *ngIf="products.lenght">
      <li>{{products.name}}</li>
  </ul>

<router-outlet></router-outlet>
</code>```

product.component.ts

```<code>import { ProductsService } from './../products.service';
import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-search-page',
  templateUrl:'./search-page.component.html',
  styleUrls: ['./search-page.component.scss']
})
export class SearchPageComponent implements OnInit {
  public products=[];
  resultSearch;
  item='';
constructor(
  private ProductsService:ProductsService,
  private _router:Router,
    ) {
      this.ProductsService.getProducts().
      subscribe(data=> {
        this.products=data
      // this.fetchProducts();
      }
        );
   }

 ngOnInit() {
  }
  fetchProducts()
  {
    this.resultSearch=this.products.filter(product => product.name.includes(this.item));
  }
  backToHome()
  {
    this._router.navigate(['/home']);
  }
  getProduct()
  {
    return this.products.filter(product => product.name.includes(this.item));
  }
  condition(){
    let condition = " not found!";
    if(!this.products.length){
      return condition;
    }
  }
}
</code>```

答:
No matching results

Try this in end of your code. Hope this help

Body:
I need to show an error messege  to show on page if the data searched is not existing on database.
should I use ngIf or there is a better method to apply this?
right now once I click with the wrong data searched nothing is happening
products.component.html

<fa (click)="backToHome()" class="arrow" name="chevron-left"></fa>

جستجو

    <input class="input" [(ngModel)]="item" required placeholder="جستجو میان محصولات و برندها" />
    <fa class="icon" name="search" (click)="fetchProducts()"></fa>

تاریخچه جستجو

{{name}}

        {{product.name}}

{{products.name}}

<router-outlet></router-outlet>

product.component.ts

import { ProductsService } from './../products.service';
import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-search-page',
  templateUrl:'./search-page.component.html',
  styleUrls: ['./search-page.component.scss']
})
export class SearchPageComponent implements OnInit {
  public products=[];
  resultSearch;
  item='';
constructor(
  private ProductsService:ProductsService,
  private _router:Router,
    ) {
      this.ProductsService.getProducts().
      subscribe(data=> {
        this.products=data
      // this.fetchProducts();
      }
        );
   }

 ngOnInit() {
  }
  fetchProducts()
  {
    this.resultSearch=this.products.filter(product => product.name.includes(this.item));
  }
  backToHome()
  {
    this._router.navigate(['/home']);
  }
  getProduct()
  {
    return this.products.filter(product => product.name.includes(this.item));
  }
  condition(){
    let condition = " not found!";
    if(!this.products.length){
      return condition;
    }
  }
}

Body:
<li *ngIf="resultSearch.length === 0">No matching results</li>
Try this in end of your code. Hope this help


问:
LDAP: fetch custom values during an authentication event
I have Springboot successfully authenticating against LDAP and adding to the view a CustomUserDetails model.

During the authentication event I would like to also bring back additional details like email, telephone and city.

According to this SO answer it is possible and I think this also addresses it.

Despite reading both these answers I am still unsure how to proceed to do this - particularly about how steps 2 and 3 from the second answer relate, and where the details like email, city and telephone are mapped?

My security class:

Security

```<code>@SpringBootApplication
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .and()
            .formLogin()
                .defaultSuccessUrl("/newExhibit");
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .and()
            .ldapAuthentication()
            .userDnPatterns("uid={0},ou=people")
            .groupSearchBase("ou=groups")
            .contextSource()
            .url("ldap://localhost:8389/dc=springframework,dc=org")
            .and()
            .passwordCompare()
            .passwordEncoder(passwordEncoder())
            .passwordAttribute("userPassword");
}
</code>```

My user object from test-server.ldif

```<code>dn: uid=abc123,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Tom Smith
sn: Smith
uid: abc123
userPassword: pass
mail: tom@contoso.com
mobile: +212 307 12345
st: CA
</code>```

Following this answer do I need to add to auth

 (a) contextsource and

 (b) userDetailsContextMapper?

Ultimately these details from ldap I would like to map to my java user class.

UPDATE

An updated AuthenticationManagerBuilder

```<code>@SpringBootApplication
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .userDetailsService(userDetailsService)
        .and()
        .ldapAuthentication()
        .userDnPatterns("uid={0},ou=people")
        .groupSearchBase("ou=groups")
        .contextSource()
        .userDetailsContextMapper(???) // what object in here and how initalised
        .url("ldap://localhost:8389/dc=springframework,dc=org")
        .and()
        .passwordCompare()
        .passwordEncoder(passwordEncoder())
        .passwordAttribute("userPassword");
}
</code>```

答:
Looking at your LDIF file I looks like you are trying to get the properties which are defined as part of the inetOrgPerson. Spring Security has an out-of-the-box mapper for this the InetOrgPersonContextMapper. This will map the defined properties to an InetOrgPerson, which will act as the UserDetails needed.

To configure you just need to create a new instance and wire it to your configuration.

```<code>@SpringBootApplication
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
      .ldapAuthentication()
        .userDnPatterns("uid={0},ou=people")
        .groupSearchBase("ou=groups")
        .contextSource()
        .url("ldap://localhost:8389/dc=springframework,dc=org")
        .and()
        .userDetailsContextMapper(new InetOrgPersonContextMapper())
        .passwordCompare()
        .passwordEncoder(passwordEncoder())
        .passwordAttribute("userPassword");
}
</code>```

This will map the properties accordingly. As you are using LDAP you don't need the UserDetailsService injected as it will automatically configure an LdapUserDetailsService underneath.

Body:
I have Springboot successfully authenticating against LDAP and adding to the view a CustomUserDetails model.

During the authentication event I would like to also bring back additional details like email, telephone and city.

According to this SO answer it is possible and I think this also addresses it.

Despite reading both these answers I am still unsure how to proceed to do this - particularly about how steps 2 and 3 from the second answer relate, and where the details like email, city and telephone are mapped?

My security class:

Security

@SpringBootApplication
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .anyRequest().fullyAuthenticated()
                .and()
            .formLogin()
                .defaultSuccessUrl("/newExhibit");
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .and()
            .ldapAuthentication()
            .userDnPatterns("uid={0},ou=people")
            .groupSearchBase("ou=groups")
            .contextSource()
            .url("ldap://localhost:8389/dc=springframework,dc=org")
            .and()
            .passwordCompare()
            .passwordEncoder(passwordEncoder())
            .passwordAttribute("userPassword");
}

My user object from test-server.ldif

dn: uid=abc123,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Tom Smith
sn: Smith
uid: abc123
userPassword: pass
mail: tom@contoso.com
mobile: +212 307 12345
st: CA

Following this answer do I need to add to auth

 (a) contextsource and

 (b) userDetailsContextMapper?

Ultimately these details from ldap I would like to map to my java user class.

UPDATE

An updated AuthenticationManagerBuilder

@SpringBootApplication
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .userDetailsService(userDetailsService)
        .and()
        .ldapAuthentication()
        .userDnPatterns("uid={0},ou=people")
        .groupSearchBase("ou=groups")
        .contextSource()
        .userDetailsContextMapper(???) // what object in here and how initalised
        .url("ldap://localhost:8389/dc=springframework,dc=org")
        .and()
        .passwordCompare()
        .passwordEncoder(passwordEncoder())
        .passwordAttribute("userPassword");
}

Body:
Looking at your LDIF file I looks like you are trying to get the properties which are defined as part of the inetOrgPerson. Spring Security has an out-of-the-box mapper for this the InetOrgPersonContextMapper. This will map the defined properties to an InetOrgPerson, which will act as the UserDetails needed.

To configure you just need to create a new instance and wire it to your configuration.

@SpringBootApplication
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
      .ldapAuthentication()
        .userDnPatterns("uid={0},ou=people")
        .groupSearchBase("ou=groups")
        .contextSource()
        .url("ldap://localhost:8389/dc=springframework,dc=org")
        .and()
        .userDetailsContextMapper(new InetOrgPersonContextMapper())
        .passwordCompare()
        .passwordEncoder(passwordEncoder())
        .passwordAttribute("userPassword");
}

This will map the properties accordingly. As you are using LDAP you don't need the UserDetailsService injected as it will automatically configure an LdapUserDetailsService underneath.


问:
How to upgrade from 2.x to 3.x in maatwebsite/excel?
I migrated my application to laravel 5.7.When installing the packages in the composer.json i upgraded from "maatwebsite/excel:~2.1.0" to "maatwebsite/excel": "^3.1".So now my export function does not work anymore.I tried to follow the upgrade in https://docs.laravel-excel.com/3.1 but didn't work for me.this is the old code that used to work in the old version:</p>

```<code>$claim = Claim::all();
$count = Claim::count();
$name = 'Liste réclamations '.date('d-m-Y H-i');
    Excel::create($name, function($excel) use($claim, $count) {

        $excel->sheet('Sheetname', function($sheet) use($claim, $count) {

            $i = 2;
            $rows = $count;
            $rows++;

            $sheet->setHeight(1, 25);
            $sheet->setAutoSize(true);
            $sheet->setBorder('A1:AH'.$rows, 'thin');

            $sheet->row(1, array(

                'Utilisateur',
                'Référence',
                'Infraction',
                'Groupe oiseaux',
                "Type de braconnage",
                "Type de l'espèce",
                "Nom de l'espèce",
                "Autre info de l'espèce",
                "Description de l'oiseau",
                "Le nombre d'oiseau",
                "Le nombre d'oiseaux mis en vente",
                "Prix de vente",
                "Lieu de la vente",
                "Nombre d'oiseaux détenus",
                "Interdiction de la chasse",
                "Présence des forces de l'ordre",
                "Contact des autorités compétentes",
                'Liste des autorités compétentes',
                "Intervention immédiate",
                "Type d'intervention",
                "L'objectif de la détention",
                "Autre objectif",
                "Indications sur l'état de l'oiseau",
                "Autre indication",
                "Lieu de l'infraction",
                "Gouvernorat de l'infraction",
                "Latitude",
                "Longitude",
                "Date de l'infraction",
                "L'heure de l'infraction",
                "Description de l'infraction",
                "Etat",
                "Date de création"

            ))->cells('A1:AH1', function($cells) {

                $cells->setBackground('#1E86CF');
                $cells->setFont(array(
                    'family'     => 'Calibri',
                    'size'       => '12',
                    'bold'       =>  true
                ));
                $cells->setFontColor('#ffffff');

            });

            foreach ($claim as $key => $claim) {

                $braconnage = '';
                $contact= '' ;

                $braconnage_link = Claimtypelink::where('claim_id',$claim->id)->with('claimbrac')->get();
                $contact_link = Claimcontactlink::where('claim_id',$claim->id)->with('claimcontactaut')->get();

                if(isset($braconnage_link)){
                    foreach ($braconnage_link as $key => $value) {
                        $braconnage = $braconnage.$value->claimbrac['title_fr'].' | ';
                    }
                }

                if(isset($contact_link)){
                    foreach ($contact_link as $key => $value) {
                        $contact = $contact.$value->claimcontactaut['title_fr'].' | ';
                    }
                }

                $sheet->row($i, array(

                    $claim->user['name'],
                    $claim->reference,
                    $claim->name_infraction,
                    $claim->group_oiseau,
                    $braconnage,
                    $claim->type_espece,
                    $claim->bird['title_fr'],
                    $claim->type_espece_other,
                    $claim->description_oiseau,
                    $claim->num_espece,
                    $claim->num_espece_vente,
                    $claim->prix_vente,
                    $claim->lieu_vente,
                    $claim->num_espece_detenu,
                    $claim->interdiction_chasse,
                    $claim->presence_ordre,
                    $claim->contact_autorite,
                    $contact,
                    $claim->intervention_immediate,
                    $claim->type_intervention,
                    $claim->objectif_detention,
                    $claim->objectif_detention_other,
                    $claim->indication_etat_oiseau,
                    $claim->indication_etat_oiseau_other,
                    $claim->lieu_infraction,
                    $claim->governorate['title_fr'],
                    $claim->latitude,
                    $claim->longitude,
                    $claim->date_infraction,
                    $claim->time_infraction,
                    $claim->description_infraction,
                    $claim->etat,
                    $claim->created_at

                ));

                $i++;
            }

        });

    })->download('xls');
</code>```

答:
I have recreated your project sample to make this work:
Follow steps to implement exactly as I did:

Install package:

composer require maatwebsite/excel
```

<ol start="2">
<li>Now run the following command:</li>
</ol>

<pre class="lang-sh prettyprint-override"><code>php artisan make:export ClaimsExport --model=Claim
</code>```

This will create app/Exports/ClaimsExport.php. Paste following code:

<?php

namespace App\Exports;

use App\Claim;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use Maatwebsite\Excel\Concerns\WithEvents;
use PhpOffice\PhpSpreadsheet\Style\Border;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\FromCollection;

class ClaimsExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents, WithMapping
{
    //
    public function headings(): array
    {
        return [
            'Utilisateur',
            'Référence',
            'Infraction',
            'Groupe oiseaux',
            "Type de braconnage",
            "Type de l'espèce",
            "Nom de l'espèce",
            "Autre info de l'espèce",
            "Description de l'oiseau",
            "Le nombre d'oiseau",
            "Le nombre d'oiseaux mis en vente",
            "Prix de vente",
            "Lieu de la vente",
            "Nombre d'oiseaux détenus",
            "Interdiction de la chasse",
            "Présence des forces de l'ordre",
            "Contact des autorités compétentes",
            'Liste des autorités compétentes',
            "Intervention immédiate",
            "Type d'intervention",
            "L'objectif de la détention",
            "Autre objectif",
            "Indications sur l'état de l'oiseau",
            "Autre indication",
            "Lieu de l'infraction",
            "Gouvernorat de l'infraction",
            "Latitude",
            "Longitude",
            "Date de l'infraction",
            "L'heure de l'infraction",
            "Description de l'infraction",
            "Etat",
            "Date de création",
        ];
    }

    //
    public function collection()
    {
        return Claim::with('user')->get();
    }

    //
    public function map($claim): array
    {
        // TODO: following two lines are fake data for visualisation
        $braconnage = 'A|B';
        $contact = 'C|D';

        // TODO: Implement this
//        $braconnage_link = Claimtypelink::where('claim_id', $claim->id)->with('claimbrac')->get();
//        $contact_link = Claimcontactlink::where('claim_id', $claim->id)->with('claimcontactaut')->get();

        if (isset($braconnage_link)) {
            foreach ($braconnage_link as $key => $value) {
                $braconnage = $braconnage . $value->claimbrac['title_fr'] . ' | ';
            }
        }

        if (isset($contact_link)) {
            foreach ($contact_link as $key => $value) {
                $contact = $contact . $value->claimcontactaut['title_fr'] . ' | ';
            }
        }

        return [
            $claim->user['name'],
            $claim->reference,
            $claim->name_infraction,
            $claim->group_oiseau,
            $braconnage,
            $claim->type_espece,
            $claim->bird['title_fr'],
            $claim->type_espece_other,
            $claim->description_oiseau,
            $claim->num_espece,
            $claim->num_espece_vente,
            $claim->prix_vente,
            $claim->lieu_vente,
            $claim->num_espece_detenu,
            $claim->interdiction_chasse,
            $claim->presence_ordre,
            $claim->contact_autorite,
            $contact,
            $claim->intervention_immediate,
            $claim->type_intervention,
            $claim->objectif_detention,
            $claim->objectif_detention_other,
            $claim->indication_etat_oiseau,
            $claim->indication_etat_oiseau_other,
            $claim->lieu_infraction,
            $claim->governorate['title_fr'],
            $claim->latitude,
            $claim->longitude,
            $claim->date_infraction,
            $claim->time_infraction,
            $claim->description_infraction,
            $claim->etat,
            $claim->created_at,
        ];
    }

    //
    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $styleArray = [
                    'font' => [
                        'bold' => true,
                        'size' => 12,
                        'name' => 'Calibri',
                        'color' => ['argb' => 'FFFFFFFF'],
                    ],
                    'borders' => [
                        'outline' => [
                            'borderStyle' => Border::BORDER_THIN,
                        ],
                    ],
                    'fill' => [
                        'fillType' => Fill::FILL_SOLID,
                        'startColor' => [
                            'argb' => 'FF1E86CF',
                        ],
                    ],
                ];

                $event->sheet->getDelegate()->getStyle('A1:AG1')->applyFromArray($styleArray);
            },
        ];
    }
}
```

<ul>
<li><p>You will find TODO there. Try to implement that by yourself. I don't know what does <strong>Claimtypelink</strong> and <strong>Claimcontactlink do.</strong></p>

<ol start="4">
<li>Now inside controller add following method:</li>
</ol></li>
</ul>

<pre class="lang-php prettyprint-override"><code>public function export()
{
    $name = 'Liste réclamations ' . date('d-m-Y H-i') . '.xlsx';

    return Excel::download(new ClaimsExport, $name);
}
</code>```

and add this in top of that file:

use App\Exports\ClaimsExport;
use Maatwebsite\Excel\Facades\Excel;
```

<ol start="5">
<li>Inside routes add:</li>
</ol>

<pre class="lang-php prettyprint-override"><code>Route::get('claims/export', 'ClaimController@export')->name('export');
</code>```

and you are good to go.

Body:
I migrated my application to laravel 5.7.When installing the packages in the composer.json i upgraded from "maatwebsite/excel:~2.1.0" to "maatwebsite/excel": "^3.1".So now my export function does not work anymore.I tried to follow the upgrade in https://docs.laravel-excel.com/3.1 but didn't work for me.this is the old code that used to work in the old version:

$claim = Claim::all();
$count = Claim::count();
$name = 'Liste réclamations '.date('d-m-Y H-i');
    Excel::create($name, function($excel) use($claim, $count) {

        $excel->sheet('Sheetname', function($sheet) use($claim, $count) {

            $i = 2;
            $rows = $count;
            $rows++;

            $sheet->setHeight(1, 25);
            $sheet->setAutoSize(true);
            $sheet->setBorder('A1:AH'.$rows, 'thin');

            $sheet->row(1, array(

                'Utilisateur',
                'Référence',
                'Infraction',
                'Groupe oiseaux',
                "Type de braconnage",
                "Type de l'espèce",
                "Nom de l'espèce",
                "Autre info de l'espèce",
                "Description de l'oiseau",
                "Le nombre d'oiseau",
                "Le nombre d'oiseaux mis en vente",
                "Prix de vente",
                "Lieu de la vente",
                "Nombre d'oiseaux détenus",
                "Interdiction de la chasse",
                "Présence des forces de l'ordre",
                "Contact des autorités compétentes",
                'Liste des autorités compétentes',
                "Intervention immédiate",
                "Type d'intervention",
                "L'objectif de la détention",
                "Autre objectif",
                "Indications sur l'état de l'oiseau",
                "Autre indication",
                "Lieu de l'infraction",
                "Gouvernorat de l'infraction",
                "Latitude",
                "Longitude",
                "Date de l'infraction",
                "L'heure de l'infraction",
                "Description de l'infraction",
                "Etat",
                "Date de création"

            ))->cells('A1:AH1', function($cells) {

                $cells->setBackground('#1E86CF');
                $cells->setFont(array(
                    'family'     => 'Calibri',
                    'size'       => '12',
                    'bold'       =>  true
                ));
                $cells->setFontColor('#ffffff');

            });

            foreach ($claim as $key => $claim) {

                $braconnage = '';
                $contact= '' ;

                $braconnage_link = Claimtypelink::where('claim_id',$claim->id)->with('claimbrac')->get();
                $contact_link = Claimcontactlink::where('claim_id',$claim->id)->with('claimcontactaut')->get();

                if(isset($braconnage_link)){
                    foreach ($braconnage_link as $key => $value) {
                        $braconnage = $braconnage.$value->claimbrac['title_fr'].' | ';
                    }
                }

                if(isset($contact_link)){
                    foreach ($contact_link as $key => $value) {
                        $contact = $contact.$value->claimcontactaut['title_fr'].' | ';
                    }
                }

                $sheet->row($i, array(

                    $claim->user['name'],
                    $claim->reference,
                    $claim->name_infraction,
                    $claim->group_oiseau,
                    $braconnage,
                    $claim->type_espece,
                    $claim->bird['title_fr'],
                    $claim->type_espece_other,
                    $claim->description_oiseau,
                    $claim->num_espece,
                    $claim->num_espece_vente,
                    $claim->prix_vente,
                    $claim->lieu_vente,
                    $claim->num_espece_detenu,
                    $claim->interdiction_chasse,
                    $claim->presence_ordre,
                    $claim->contact_autorite,
                    $contact,
                    $claim->intervention_immediate,
                    $claim->type_intervention,
                    $claim->objectif_detention,
                    $claim->objectif_detention_other,
                    $claim->indication_etat_oiseau,
                    $claim->indication_etat_oiseau_other,
                    $claim->lieu_infraction,
                    $claim->governorate['title_fr'],
                    $claim->latitude,
                    $claim->longitude,
                    $claim->date_infraction,
                    $claim->time_infraction,
                    $claim->description_infraction,
                    $claim->etat,
                    $claim->created_at

                ));

                $i++;
            }

        });

    })->download('xls');

Body:
I have recreated your project sample to make this work:
Follow steps to implement exactly as I did:

Install package:

composer require maatwebsite/excel

Now run the following command:

php artisan make:export ClaimsExport --model=Claim

This will create app/Exports/ClaimsExport.php. Paste following code:

<?php

namespace App\Exports;

use App\Claim;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use Maatwebsite\Excel\Concerns\WithEvents;
use PhpOffice\PhpSpreadsheet\Style\Border;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\FromCollection;

class ClaimsExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents, WithMapping
{
    //
    public function headings(): array
    {
        return [
            'Utilisateur',
            'Référence',
            'Infraction',
            'Groupe oiseaux',
            "Type de braconnage",
            "Type de l'espèce",
            "Nom de l'espèce",
            "Autre info de l'espèce",
            "Description de l'oiseau",
            "Le nombre d'oiseau",
            "Le nombre d'oiseaux mis en vente",
            "Prix de vente",
            "Lieu de la vente",
            "Nombre d'oiseaux détenus",
            "Interdiction de la chasse",
            "Présence des forces de l'ordre",
            "Contact des autorités compétentes",
            'Liste des autorités compétentes',
            "Intervention immédiate",
            "Type d'intervention",
            "L'objectif de la détention",
            "Autre objectif",
            "Indications sur l'état de l'oiseau",
            "Autre indication",
            "Lieu de l'infraction",
            "Gouvernorat de l'infraction",
            "Latitude",
            "Longitude",
            "Date de l'infraction",
            "L'heure de l'infraction",
            "Description de l'infraction",
            "Etat",
            "Date de création",
        ];
    }

    //
    public function collection()
    {
        return Claim::with('user')->get();
    }

    //
    public function map($claim): array
    {
        // TODO: following two lines are fake data for visualisation
        $braconnage = 'A|B';
        $contact = 'C|D';

        // TODO: Implement this
//        $braconnage_link = Claimtypelink::where('claim_id', $claim->id)->with('claimbrac')->get();
//        $contact_link = Claimcontactlink::where('claim_id', $claim->id)->with('claimcontactaut')->get();

        if (isset($braconnage_link)) {
            foreach ($braconnage_link as $key => $value) {
                $braconnage = $braconnage . $value->claimbrac['title_fr'] . ' | ';
            }
        }

        if (isset($contact_link)) {
            foreach ($contact_link as $key => $value) {
                $contact = $contact . $value->claimcontactaut['title_fr'] . ' | ';
            }
        }

        return [
            $claim->user['name'],
            $claim->reference,
            $claim->name_infraction,
            $claim->group_oiseau,
            $braconnage,
            $claim->type_espece,
            $claim->bird['title_fr'],
            $claim->type_espece_other,
            $claim->description_oiseau,
            $claim->num_espece,
            $claim->num_espece_vente,
            $claim->prix_vente,
            $claim->lieu_vente,
            $claim->num_espece_detenu,
            $claim->interdiction_chasse,
            $claim->presence_ordre,
            $claim->contact_autorite,
            $contact,
            $claim->intervention_immediate,
            $claim->type_intervention,
            $claim->objectif_detention,
            $claim->objectif_detention_other,
            $claim->indication_etat_oiseau,
            $claim->indication_etat_oiseau_other,
            $claim->lieu_infraction,
            $claim->governorate['title_fr'],
            $claim->latitude,
            $claim->longitude,
            $claim->date_infraction,
            $claim->time_infraction,
            $claim->description_infraction,
            $claim->etat,
            $claim->created_at,
        ];
    }

    //
    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $styleArray = [
                    'font' => [
                        'bold' => true,
                        'size' => 12,
                        'name' => 'Calibri',
                        'color' => ['argb' => 'FFFFFFFF'],
                    ],
                    'borders' => [
                        'outline' => [
                            'borderStyle' => Border::BORDER_THIN,
                        ],
                    ],
                    'fill' => [
                        'fillType' => Fill::FILL_SOLID,
                        'startColor' => [
                            'argb' => 'FF1E86CF',
                        ],
                    ],
                ];

                $event->sheet->getDelegate()->getStyle('A1:AG1')->applyFromArray($styleArray);
            },
        ];
    }
}

You will find TODO there. Try to implement that by yourself. I don't know what does Claimtypelink and Claimcontactlink do.

Now inside controller add following method:

public function export()
{
    $name = 'Liste réclamations ' . date('d-m-Y H-i') . '.xlsx';

    return Excel::download(new ClaimsExport, $name);
}

and add this in top of that file:

use App\Exports\ClaimsExport;
use Maatwebsite\Excel\Facades\Excel;

Inside routes add:

Route::get('claims/export', 'ClaimController@export')->name('export');

and you are good to go.


问:
Linq to SQL: Many to Many support class
I'd like to have a support class to help with the Many to Many relationship.

As I see it now it could be a double generic class you would define in one or both of the entity partial classes surrounding the relationship.

Getting it to allow access to the other table without having to specifically mention the relationship table should be easy. However adding or removing from the collection is somewhat trickier. You would ahve to add a row into the relationship table aswell and commit it or remove it based on what is done.

Could this be done through a function that is passed into this generic class?

Does a class like this exists and if not is it something that can be viably done?

答:
It's hard (perhaps even impossible) to create a solution in LINQ to SQL that feels like something native, because such a solution must work in the following ways:

The many collection should be modeled as a property on the other many entity.

It must support inserts, updates and deletes.

It should work when writing LINQ queries.

It is easy to make a solution for point 1. Take for instance a model with a Product class with a many-to-many relationship with Order. You could define the following property on the Order class:

```<code>public IEnumerable<Product> Products
{
    get { return this.OrderProducts.Select(op => op.Product); }
}
</code>```

This however doesn't work with point 2 and 3. While we could make a generic collection that allows inserting, LINQ to SQL will never be able to translate the use of this property back into a SQL query. For instance, the following LINQ query looks innocent:

```<code>var bigOrders =
    from order in context.Orders
    where order.Products.Any(p => p.Price > 100)
    select order;
</code>```

Unfortunately, this query will fail, because LINQ to SQL doesn't know how to map the Products property to SQL.

When you want this feature natively, you should consider migrating to Entity Framework (4.0 or up). EF supports this natively.

ContentLicense: CC BY-SA 3.0

Title: Linq to SQL: Many to Many support class

Body:
It's hard (perhaps even impossible) to create a solution in LINQ to SQL that feels like something native, because such a solution must work in the following ways:

The many collection should be modeled as a property on the other many entity.

It must support inserts, updates and deletes.

It should work when writing LINQ queries.

It is easy to make a solution for point 1. Take for instance a model with a Product class with a many-to-many relationship with Order. You could define the following property on the Order class:

public IEnumerable<Product> Products
{
    get { return this.OrderProducts.Select(op => op.Product); }
}

This however doesn't work with point 2 and 3. While we could make a generic collection that allows inserting, LINQ to SQL will never be able to translate the use of this property back into a SQL query. For instance, the following LINQ query looks innocent:

var bigOrders =
    from order in context.Orders
    where order.Products.Any(p => p.Price > 100)
    select order;

Unfortunately, this query will fail, because LINQ to SQL doesn't know how to map the Products property to SQL.

When you want this feature natively, you should consider migrating to Entity Framework (4.0 or up). EF supports this natively.


问:
How to render BULLET character in React Native?
Im trying to format data that has to be displayed on <Text>. Here is my formatData() method:

```<code>getFormattedData = (idA, idB) => {
    var formattedData = "";
    if (idA != null && idA != "") {
        formattedData = formattedData + "•" + " " + idA
    }
    if (idB != null && idB != "") {
        formattedData = formattedData + "•" + " " + idB
    }
    return formattedData;
};
</code>```

But in view, this is rendered as ABC • DEF. And not as ABC • DEF

When I use \u2B24 the bullet is very big and when using \2022, just the code is displayed.

How to render • with getFormattedData()?

答:
This works for me,

```<code>getFormattedData = (idA, idB) => {
    var formattedData = "";
    if (idA != null && idA != "") {
        formattedData = <div>{formattedData}•{idA}</div>
    }
    if (idB != null && idB != "") {
        formattedData = <div>{formattedData}•{idB}</div>
    }
    return formattedData;
};

render() {
    return (
        <div>{this.getFormattedData(12,"abc")}</div>
    );
  }
</code>```

Output:

•12

•abc

Body:
Im trying to format data that has to be displayed on <Text>. Here is my formatData() method:

getFormattedData = (idA, idB) => {
    var formattedData = "";
    if (idA != null && idA != "") {
        formattedData = formattedData + "•" + " " + idA
    }
    if (idB != null && idB != "") {
        formattedData = formattedData + "•" + " " + idB
    }
    return formattedData;
};

But in view, this is rendered as ABC • DEF. And not as ABC • DEF

When I use \u2B24 the bullet is very big and when using \2022, just the code is displayed.

How to render • with getFormattedData()?

Body:
This works for me,

getFormattedData = (idA, idB) => {
    var formattedData = "";
    if (idA != null && idA != "") {
        formattedData = <div>{formattedData}&#8226;{idA}</div>
    }
    if (idB != null && idB != "") {
        formattedData = <div>{formattedData}&#8226;{idB}</div>
    }
    return formattedData;
};

render() {
    return (
        <div>{this.getFormattedData(12,"abc")}</div>
    );
  }

Output:

•12

•abc


问:
Python interpolate problem, when looping through an inserting numbers to a list
Task:

A function that takes a list lst and an integer n.

If the difference between any two successive elements of the list is greater than n, then insert the average of the two elements as a new element between them. Repeat the process until the difference between all elements is less than n.

Problem:

Error when it needs to loop through the entire problem again.

Initial: [9.5, 10.0]

loop1: [9.5, 9.75, 10.0]

when debugging my loop2 skips the 9.625

loop2: [9.5, 9.75, 9.875, 10.0] --incorrect

loop2:

[9.5, 9.625, 9.75, 9.875, 10.0] --correct

I've already tried the sort() function Which resulted in passing everything except the last test which has a list of un-ordered numbers. So I am rather using insert() in the code below:

Code:

```<code>def interpolate(lst, n):
    count=0
    if lst==[]:
        return []
    if len(lst)==1:
        return lst
    final_val=lst[-1]
    while (lst[1]-lst[0])>n:
        x=(lst[count+1]-lst[count])/2
        length=len(lst)
        if abs(lst[count]-lst[count+1])>n:
            y=lst[count]+x
            lst.insert(count+1,y)
        count+=1
    return lst

print(interpolate([], 0.5))
#--lst = [] #--works
print(interpolate([9.0], 0.5))
#--lst = [9.0] #--works
print(interpolate([9.0, 10.0], 0.5))
#--lst = [9.0, 9.5, 10.0] #--works

print(interpolate([9.5, 10.0], 0.2))
#--lst = [9.5, 9.625, 9.75, 9.875, 10.0] #--ERROR
print(interpolate([-7.5, 10.66, 11.43], 5.3))
#--lst = [-7.5, -2.96, 1.58, 6.12, 10.66, 11.43] #--ERROR

print(interpolate([-4.0, -3.5, -3.0], 0.5))
#--lst = [-4.0, -3.5, -3.0]) #--works
print(interpolate([-4.0, -3.0, -3.5], 0.5))
#--lst = [-4.0, -3.5, -3.0, -3.5] #--works
</code>```

答:
The problem here is that you dont reset your counter after each iteration(so program searches for list elements indexed higher than length of the list) i added one if statement in the end of your while loop

```<code>if (count>len(lst)-2):
            count=0
</code>```

So it keeps everything in your style while fixing the issue

```<code>def interpolate(lst, n):
    count=0
    if lst==[]:
        return []
    if len(lst)==1:
        return lst
    final_val=lst[-1]

    while (lst[1]-lst[0])>n:
        x=(lst[count+1]-lst[count])/2
        length=len(lst)
        if abs(lst[count]-lst[count+1])>n:
            y=lst[count]+x
            lst.insert(count+1,y)
        count+=1
        if (count>len(lst)-2):
            count=0
    return lst
</code>```

Body:
Task:

A function that takes a list lst and an integer n.

If the difference between any two successive elements of the list is greater than n, then insert the average of the two elements as a new element between them. Repeat the process until the difference between all elements is less than n.

Problem:

Error when it needs to loop through the entire problem again.

Initial: [9.5, 10.0]

loop1: [9.5, 9.75, 10.0]

when debugging my loop2 skips the 9.625

loop2: [9.5, 9.75, 9.875, 10.0] --incorrect

loop2:

[9.5, 9.625, 9.75, 9.875, 10.0] --correct

I've already tried the sort() function Which resulted in passing everything except the last test which has a list of un-ordered numbers. So I am rather using insert() in the code below:

Code:

def interpolate(lst, n):
    count=0
    if lst==[]:
        return []
    if len(lst)==1:
        return lst
    final_val=lst[-1]
    while (lst[1]-lst[0])>n:
        x=(lst[count+1]-lst[count])/2
        length=len(lst)
        if abs(lst[count]-lst[count+1])>n:
            y=lst[count]+x
            lst.insert(count+1,y)
        count+=1
    return lst

print(interpolate([], 0.5))
#--lst = [] #--works
print(interpolate([9.0], 0.5))
#--lst = [9.0] #--works
print(interpolate([9.0, 10.0], 0.5))
#--lst = [9.0, 9.5, 10.0] #--works

print(interpolate([9.5, 10.0], 0.2))
#--lst = [9.5, 9.625, 9.75, 9.875, 10.0] #--ERROR
print(interpolate([-7.5, 10.66, 11.43], 5.3))
#--lst = [-7.5, -2.96, 1.58, 6.12, 10.66, 11.43] #--ERROR

print(interpolate([-4.0, -3.5, -3.0], 0.5))
#--lst = [-4.0, -3.5, -3.0]) #--works
print(interpolate([-4.0, -3.0, -3.5], 0.5))
#--lst = [-4.0, -3.5, -3.0, -3.5] #--works

Body:
The problem here is that you dont reset your counter after each iteration(so program searches for list elements indexed higher than length of the list) i added one if statement in the end of your while loop

if (count>len(lst)-2):
            count=0

So it keeps everything in your style while fixing the issue

def interpolate(lst, n):
    count=0
    if lst==[]:
        return []
    if len(lst)==1:
        return lst
    final_val=lst[-1]

    while (lst[1]-lst[0])>n:
        x=(lst[count+1]-lst[count])/2
        length=len(lst)
        if abs(lst[count]-lst[count+1])>n:
            y=lst[count]+x
            lst.insert(count+1,y)
        count+=1
        if (count>len(lst)-2):
            count=0
    return lst


问:
otp_code: wrong number of arguments in recent update of active_model_otp gem
I updated my Gemfile and rotp (4.1.0) and active_model_otp(1.2.0) gems got updated. Since then I've start getting error while calling @user.otp_code method associated with User modal "wrong number of arguments (given 2, expected 1)"

```<code>    /usr/local/lib/ruby/gems/2.3.0/gems/rotp-4.1.0/lib/rotp/totp.rb:17:in `at'
    /usr/local/lib/ruby/gems/2.3.0/gems/active_model_otp-1.2.0/lib/active_model/one_time_password.rb:77:in `otp_code'
    /home/app/controllers/api/v1/users_controller.rb:745:in `resetpassword'
</code>```

as far as I dig into it, I found this.
the issue is in arguments, it seems the latest rotp gem have updated below method to accept only 1 argument insted of 2 as compared to older version (3.3.1)

since the optional parameter has been removed, the active_model_otp-1.2.0 gem is giving error at line number 77

as per rotp-4.1.0

```<code>    def at(time)
        generate_otp(timecode(time))
    end
</code>```

as per rotp-3.3.1

```<code>    def at(time, padding=true)
        unless time.class == Time
            time = Time.at(time.to_i)
        end
        generate_otp(timecode(time), padding)
    end
</code>```

I tried making changes in the gem as below

```<code>    def otp_code(options = {})
     if otp_counter_based
        if options[:auto_increment]
          self.otp_counter += 1
          save if !new_record?
        end
        ROTP::HOTP.new(otp_column, digits: otp_digits).at(self.otp_counter)
      else
        if options.is_a? Hash
          time = options.fetch(:time, Time.now)
          padding = options.fetch(:padding, true)
        else
          time = options
          padding = true
        end
       # ROTP::TOTP.new(otp_column, digits: otp_digits).at(time, padding)
       # -- Commented Above Line to remove padding arguments from it.
        ROTP::TOTP.new(otp_column, digits: otp_digits).at(time)
      end
    end
</code>```

it worked but not sure what else will break, active-model gem was last updated in 2015, and rotp updated few months back.
please suggest suitable method, if I revert back to previous gem version of rotp then what else would break. I'm kind of stuck.

kindly help.

答:
Looks like if you want to use active_model_otp gem you'll have to downgrade rotp as suggested in the opened issue. Not sure if it breaks anything, probably it won't since it worked previously for you.

Seems like they don't rush to fix it, perhaps you can create a PR with a fix so that maybe they accept it.
Another option is to fork their repo, fix it and publish as your own gem to use it instead.

Body:
I updated my Gemfile and rotp (4.1.0) and active_model_otp(1.2.0) gems got updated. Since then I've start getting error while calling @user.otp_code method associated with User modal "wrong number of arguments (given 2, expected 1)"

    /usr/local/lib/ruby/gems/2.3.0/gems/rotp-4.1.0/lib/rotp/totp.rb:17:in `at'
    /usr/local/lib/ruby/gems/2.3.0/gems/active_model_otp-1.2.0/lib/active_model/one_time_password.rb:77:in `otp_code'
    /home/app/controllers/api/v1/users_controller.rb:745:in `resetpassword'

as far as I dig into it, I found this.
the issue is in arguments, it seems the latest rotp gem have updated below method to accept only 1 argument insted of 2 as compared to older version (3.3.1)

since the optional parameter has been removed, the active_model_otp-1.2.0 gem is giving error at line number 77

as per rotp-4.1.0

    def at(time)
        generate_otp(timecode(time))
    end

as per rotp-3.3.1

    def at(time, padding=true)
        unless time.class == Time
            time = Time.at(time.to_i)
        end
        generate_otp(timecode(time), padding)
    end

I tried making changes in the gem as below

    def otp_code(options = {})
     if otp_counter_based
        if options[:auto_increment]
          self.otp_counter += 1
          save if !new_record?
        end
        ROTP::HOTP.new(otp_column, digits: otp_digits).at(self.otp_counter)
      else
        if options.is_a? Hash
          time = options.fetch(:time, Time.now)
          padding = options.fetch(:padding, true)
        else
          time = options
          padding = true
        end
       # ROTP::TOTP.new(otp_column, digits: otp_digits).at(time, padding)
       # -- Commented Above Line to remove padding arguments from it.
        ROTP::TOTP.new(otp_column, digits: otp_digits).at(time)
      end
    end

it worked but not sure what else will break, active-model gem was last updated in 2015, and rotp updated few months back.
please suggest suitable method, if I revert back to previous gem version of rotp then what else would break. I'm kind of stuck.

kindly help.


问:
Angular component are not getting destroyed
In angular application, every time I route to a new page, my earlier page's component is staying in memory. It's not getting destroyed and when I route back to that page it creates a new instance.

Application is not created through angular CLI. It's a custom build application using the webpack configuration provided on angular website. Actually, I am doing performance improvement of the existing angular application and this demo app I created for isolation of issue.

Github
https://github.com/bytesofdhiren/angular-memory-issue

Basically, every time I route to home or register page, the application creates a new instance of the register component and home component. It's not destroying the earlier created component.

答:
Every component has a lifecycle you need to use:

```<code>OnDestroy();
</code>```

and you need to implements the method ngOnDestroy().
Follow this

Body:
Every component has a lifecycle you need to use:

OnDestroy();

and you need to implements the method ngOnDestroy().
Follow this


问:
Find all matches in column range and copy all value within range
First time user here.
I'm also a beginner trying to write a program in VBA for Excel 2010 and here's what I need to do.

I have a workbook containing two sheets, Sheet1 called "Process"
(have column A with titled "Item") and Sheet2 called "Master" (have column A with titled "Item" and column B with titled "Operation")

I need to compare these two columns A, if there's any data that match, I'd like to copy ALL data from column B "Operation" from sheet "Master" and place it into column B in sheet "Process".

The code from Mr. Mohit Bansal it's working perfectly, but after i try to put the code into real condition of worksheet, i'm facing new problem that if any same data in Column A "Item", it's only copy for first data.

Any help for figuring out how to get past this would be greatly appreciated.

Herewith i edit based on real condition of worksheet.

Sheet1 "Process"

```<code>-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |           |
|20Y        |           |
|20Y        |           |
|20YF0Blank |           |
|20YF0      |           |
|20YF0      |           |
|20YFGAfter |           |
|20YFG      |           |
|20YFG      |           |
|20YStandard|           |
|20Y        |           |
|20Y        |           |
|20Y        |           |
|20YF0Blank |           |
|20YF0      |           |
|20YF0      |           |
|20YFGAfter |           |
|20YFG      |           |
|20YFG      |           |
</code>```

Sheet2 "Master"

```<code>-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|21YF0      |QT2        |
|21YF0      |SB2        |
|21YF0      |MG2        |
|21YFG      |FG8        |
|21YFG      |SCR2       |
</code>```

Actual Result =

Sheet1 "Process"

```<code>-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|20YStandard|           |
|20Y        |Not copied |
|20Y        |Not copied |
|20Y        |Not copied |
|20YF0Blank |           |
|20YF0      |Not copied |
|20YF0      |Not copied |
|20YFGAfter |           |
|20YFG      |Not copied |
|20YFG      |Not copied |
</code>```

```<code>Sub Button2_Click()

pr = Worksheets("Process").Range("A2:B1000").Value

ma = Worksheets("Master").Range("A2:B8008").Value

Range("B:B").ClearContents

For i = LBound(pr, 1) To UBound(pr, 1)

    For j = LBound(ma, 1) To UBound(ma, 1)

        If ma(j, 1) = pr(i, 1) Then

            Worksheets("Process").Range("B" & i + 1).Value = ma(j, 2)
            ma(j, 1) = "---"

            Exit For

        End If
Next j
Next i
End Sub
</code>```

Expected Result =

Sheet1 "Process"

```<code>-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
</code>```

答:
This is working perfectly:

```<code>pr = Worksheets("Process").Range("A2:B11").Value
ma = Worksheets("Master").Range("A2:B13").Value

For i = LBound(pr, 1) To UBound(pr, 1)

    For j = LBound(ma, 1) To UBound(ma, 1)

        If ma(j, 1) = pr(i, 1) Then

            Worksheets("Process").Range("B" & i + 1).Value = ma(j, 2)
            ma(j, 1) = "---"
            Exit For

        End If
Next j
Next i
</code>```

New Answer

Only if 10 Rows Repeat themselves in Process Sheet

Sub Button2_Click()

```<code>pr = Worksheets("Process").Range("A2:B21").Value

ma = Worksheets("Master").Range("A2:B13").Value

Worksheets("Process").Range("B:B").ClearContents

For i = LBound(pr, 1) To UBound(pr, 1)

    If i = 11 Then ma = Worksheets("Master").Range("A2:B13").Value

    For j = LBound(ma, 1) To UBound(ma, 1)

        If ma(j, 1) = pr(i, 1) Then

            Worksheets("Process").Range("B" & i + 1).Value = ma(j, 2)
            ma(j, 1) = "---"

            Exit For

        End If
Next j
Next i
End Sub
</code>```

Body:
First time user here.
I'm also a beginner trying to write a program in VBA for Excel 2010 and here's what I need to do.

I have a workbook containing two sheets, Sheet1 called "Process"
(have column A with titled "Item") and Sheet2 called "Master" (have column A with titled "Item" and column B with titled "Operation")

I need to compare these two columns A, if there's any data that match, I'd like to copy ALL data from column B "Operation" from sheet "Master" and place it into column B in sheet "Process".

The code from Mr. Mohit Bansal it's working perfectly, but after i try to put the code into real condition of worksheet, i'm facing new problem that if any same data in Column A "Item", it's only copy for first data.

Any help for figuring out how to get past this would be greatly appreciated.

Herewith i edit based on real condition of worksheet.

Sheet1 "Process"

-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |           |
|20Y        |           |
|20Y        |           |
|20YF0Blank |           |
|20YF0      |           |
|20YF0      |           |
|20YFGAfter |           |
|20YFG      |           |
|20YFG      |           |
|20YStandard|           |
|20Y        |           |
|20Y        |           |
|20Y        |           |
|20YF0Blank |           |
|20YF0      |           |
|20YF0      |           |
|20YFGAfter |           |
|20YFG      |           |
|20YFG      |           |

Sheet2 "Master"

-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|21YF0      |QT2        |
|21YF0      |SB2        |
|21YF0      |MG2        |
|21YFG      |FG8        |
|21YFG      |SCR2       |

Actual Result =

Sheet1 "Process"

-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|20YStandard|           |
|20Y        |Not copied |
|20Y        |Not copied |
|20Y        |Not copied |
|20YF0Blank |           |
|20YF0      |Not copied |
|20YF0      |Not copied |
|20YFGAfter |           |
|20YFG      |Not copied |
|20YFG      |Not copied |

Sub Button2_Click()

pr = Worksheets("Process").Range("A2:B1000").Value

ma = Worksheets("Master").Range("A2:B8008").Value

Range("B:B").ClearContents

For i = LBound(pr, 1) To UBound(pr, 1)

    For j = LBound(ma, 1) To UBound(ma, 1)

        If ma(j, 1) = pr(i, 1) Then

            Worksheets("Process").Range("B" & i + 1).Value = ma(j, 2)
            ma(j, 1) = "---"

            Exit For

        End If
Next j
Next i
End Sub

Expected Result =

Sheet1 "Process"

-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |

Body:
This is working perfectly:

pr = Worksheets("Process").Range("A2:B11").Value
ma = Worksheets("Master").Range("A2:B13").Value

For i = LBound(pr, 1) To UBound(pr, 1)

    For j = LBound(ma, 1) To UBound(ma, 1)

        If ma(j, 1) = pr(i, 1) Then

            Worksheets("Process").Range("B" & i + 1).Value = ma(j, 2)
            ma(j, 1) = "---"
            Exit For

        End If
Next j
Next i

New Answer

Only if 10 Rows Repeat themselves in Process Sheet

Sub Button2_Click()

pr = Worksheets("Process").Range("A2:B21").Value

ma = Worksheets("Master").Range("A2:B13").Value

Worksheets("Process").Range("B:B").ClearContents

For i = LBound(pr, 1) To UBound(pr, 1)

    If i = 11 Then ma = Worksheets("Master").Range("A2:B13").Value

    For j = LBound(ma, 1) To UBound(ma, 1)

        If ma(j, 1) = pr(i, 1) Then

            Worksheets("Process").Range("B" & i + 1).Value = ma(j, 2)
            ma(j, 1) = "---"

            Exit For

        End If
Next j
Next i
End Sub


问:
json_decode help
I have been trying to use some API's from various services, At the moment im trying to retrieve data about a video on vimeo,

I have successfully got the file and read the contents, however, i do not know how to access each part of the file that is returned as a .json.

Basically, how do i access the data in the json file using PHP

Thanks

答:
```<code>$file_contents = file_get_contents("http://vimeo.com/api/v2/group/awesome/videos.json"), true);
</code>```

Read it into a variable using:

```<code>$data = json_decode($file_contents);
</code>```

then you can access the parts using:

```<code>echo $data->id;
echo $data->title;
</code>```

etc.

Just use print_r($data); to see all available fields.

Title: json_decode help

Body:
$file_contents = file_get_contents("http://vimeo.com/api/v2/group/awesome/videos.json"), true);

Read it into a variable using:

$data = json_decode($file_contents);

then you can access the parts using:

echo $data->id;
echo $data->title;

etc.

Just use print_r($data); to see all available fields.


问:
Cannot run React Native project with Expo
I have an old React Native project, now i want to run it with Expo. The problem is Expo software stuck at “waiting for package and tunnel to start” when i try to use Expo to open the project and start it. I am working on MacOS with watchman already installed.

Here's the structure of my project

My app.json:

```<code>{ "name": "myapp", "displayName": "myApp", "expo": { "sdkVersion": "28.0.0" } }
</code>```

package.json:

```<code>{
  "name": "MyApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "expo": "^28.0.0",
    "react": "15.4.1",
    "react-native": "0.42.0",
    "react-native-calendar-strip": "^0.1.4",
    "react-native-check-box": "^1.0.4",
    "react-native-checkbox": "^1.1.0",
    "react-native-code-push": "1.17.0-beta",
    "react-native-collapsible": "0.8.0",
    "react-native-datepicker": "^1.6.0",
    "react-native-fetch-blob": "0.10.6",
    "react-native-image-picker": "0.26.2",
    "react-native-keyboard-aware-scroll-view": "^0.2.9",
    "react-native-modal-picker": "0.0.16",
    "react-native-modalbox": "1.3.9",
    "react-native-pdf": "1.2.4",
    "react-native-picker": "4.0.18",
    "react-native-signature-pad": "git+https://github.com/silverspace/react-native-signature-pad/#greg/android_blank_workaround",
    "react-native-simple-store": "^1.2.0",
    "react-native-vector-icons": "4.0.1",
    "react-navigation": "1.0.0-beta.7",
    "react-redux": "5.0.3",
    "realm": "2.11.0",
    "redux": "3.6.0",
    "redux-logger": "2.8.2",
    "redux-thunk": "2.2.0",
    "tipsi-stripe": "3.2.0"
  },
  "devDependencies": {
    "babel-jest": "19.0.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "20.0.4",
    "react-test-renderer": "15.4.1"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

index.ios.js and and index.android.js have the same code: import './App';

Here's my App.js:

```<code>import React from 'react';
import {
  AppRegistry,
  Text,
  View,
  Button,
  AppState,
  DeviceEventEmitter
} from 'react-native';
import { BackAndroid } from 'react-native'
import { NavigationActions, StackNavigator } from 'react-navigation';
// Redux
import { Provider } from 'react-redux'
import store from './app/store'
import codePush from 'react-native-code-push';
import HomeNavigation from './app/Home/screens/HomeNavigation'
import simpleStore from 'react-native-simple-store';

import { HOST } from './app/Common/constants';
const GET_USER_URL = `${HOST}/api/user`;

let codePushOptions = {
   checkFrequency: codePush.CheckFrequency.ON_APP_RESUME,
   installMode: codePush.InstallMode.ON_NEXT_RESUME
};

class App extends React.Component {

   //Doing something here...

    render(){
        return(
            <Provider store={store}>
                <HomeNavigation />
            </Provider>
        )
    }
}

export default CodePushApp = codePush(codePushOptions)(App);

AppRegistry.registerComponent('MypApp', () => CodePushApp);
</code>```

I have try to install Expo on a Window PC but still have the same issues when try to run this project.

答:
I know this is late but if you have already installed expo-cli then try changing  the scripts section of your package.json file to the following

```<code>"scripts": {
"start": "expo start",
"eject": "expo eject",
"android": "expo start --android",
"ios": "expo start --ios",
"test": "jest"
</code>```

}

This worked for me

Body:
I have an old React Native project, now i want to run it with Expo. The problem is Expo software stuck at “waiting for package and tunnel to start” when i try to use Expo to open the project and start it. I am working on MacOS with watchman already installed.

Here's the structure of my project

My app.json:

{ "name": "myapp", "displayName": "myApp", "expo": { "sdkVersion": "28.0.0" } }

package.json:

{
  "name": "MyApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "expo": "^28.0.0",
    "react": "15.4.1",
    "react-native": "0.42.0",
    "react-native-calendar-strip": "^0.1.4",
    "react-native-check-box": "^1.0.4",
    "react-native-checkbox": "^1.1.0",
    "react-native-code-push": "1.17.0-beta",
    "react-native-collapsible": "0.8.0",
    "react-native-datepicker": "^1.6.0",
    "react-native-fetch-blob": "0.10.6",
    "react-native-image-picker": "0.26.2",
    "react-native-keyboard-aware-scroll-view": "^0.2.9",
    "react-native-modal-picker": "0.0.16",
    "react-native-modalbox": "1.3.9",
    "react-native-pdf": "1.2.4",
    "react-native-picker": "4.0.18",
    "react-native-signature-pad": "git+https://github.com/silverspace/react-native-signature-pad/#greg/android_blank_workaround",
    "react-native-simple-store": "^1.2.0",
    "react-native-vector-icons": "4.0.1",
    "react-navigation": "1.0.0-beta.7",
    "react-redux": "5.0.3",
    "realm": "2.11.0",
    "redux": "3.6.0",
    "redux-logger": "2.8.2",
    "redux-thunk": "2.2.0",
    "tipsi-stripe": "3.2.0"
  },
  "devDependencies": {
    "babel-jest": "19.0.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "20.0.4",
    "react-test-renderer": "15.4.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

index.ios.js and and index.android.js have the same code: import './App';

Here's my App.js:

import React from 'react';
import {
  AppRegistry,
  Text,
  View,
  Button,
  AppState,
  DeviceEventEmitter
} from 'react-native';
import { BackAndroid } from 'react-native'
import { NavigationActions, StackNavigator } from 'react-navigation';
// Redux
import { Provider } from 'react-redux'
import store from './app/store'
import codePush from 'react-native-code-push';
import HomeNavigation from './app/Home/screens/HomeNavigation'
import simpleStore from 'react-native-simple-store';

import { HOST } from './app/Common/constants';
const GET_USER_URL = `${HOST}/api/user`;

let codePushOptions = {
   checkFrequency: codePush.CheckFrequency.ON_APP_RESUME,
   installMode: codePush.InstallMode.ON_NEXT_RESUME
};

class App extends React.Component {

   //Doing something here...

    render(){
        return(
            <Provider store={store}>
                <HomeNavigation />
            </Provider>
        )
    }
}

export default CodePushApp = codePush(codePushOptions)(App);

AppRegistry.registerComponent('MypApp', () => CodePushApp);

I have try to install Expo on a Window PC but still have the same issues when try to run this project.

Body:
I know this is late but if you have already installed expo-cli then try changing  the scripts section of your package.json file to the following

"scripts": {
"start": "expo start",
"eject": "expo eject",
"android": "expo start --android",
"ios": "expo start --ios",
"test": "jest"

}

This worked for me


问:
How can I get inside parentheses value in a string?
How can I get inside parentheses value in a string?

```<code>String str= "United Arab Emirates Dirham (AED)";
</code>```

I need only AED text.

答:
The answer from @Cœur is probably correct, but unfortunately it did not work for me.
I had text similar to this:

```<code>mrewrwegsg {text in between braces} njanfjaenfjie a {text in between braces}
</code>```

It was way larger, but let's consider only this short part.

I used this code to get each text between bracelet and print it to the console:

```<code>Pattern p = Pattern.compile("\\{.*?\\}");
Matcher m = p.matcher(test);
while(m.find()) {
      System.out.println(m.group().subSequence(1, m.group().length()-1));
}
</code>```

It might be more complicated than @Cœur answer, but maybe there is someone like me, who can find my answer useful.

Body:
How can I get inside parentheses value in a string?

String str= "United Arab Emirates Dirham (AED)";

I need only AED text.

Body:
The answer from @Cœur is probably correct, but unfortunately it did not work for me.
I had text similar to this:

mrewrwegsg {text in between braces} njanfjaenfjie a {text in between braces}

It was way larger, but let's consider only this short part.

I used this code to get each text between bracelet and print it to the console:

Pattern p = Pattern.compile("\\{.*?\\}");
Matcher m = p.matcher(test);
while(m.find()) {
      System.out.println(m.group().subSequence(1, m.group().length()-1));
}

It might be more complicated than @Cœur answer, but maybe there is someone like me, who can find my answer useful.


问:
Setting values of a dynamically allocated array
I am trying to create and store values inside a matrix, represented as a 1 dimensional array.

When I try to set the values, my output comes out wrong.

Matrix Struct

```<code>struct matrix{
    char matrixName[50];
    int rows;
    int columns;
    float* data;
};
typedef struct matrix matrix_t;

matrix_t our_matrix[MAX_MATRICES];
</code>```

Creating the matrix:

```<code>int create_matrix(matrix_t* matrixP, int matrixLocation){

  char tempName[50];
  int rows, cols;

  printf("Enter a name for your matrix>\n");
  scanf("%s", tempName);

  printf("Enter the number of rows>\n");
  scanf("%d", &rows);

  printf("Enter the number of cols>\n");
  scanf("%d", &cols);

  float * data = (float *) malloc(rows * cols * sizeof(float));

  int row = 0, col = 0;
  for (row = 1; row <= rows; row++) {
    for (col = 1; col <= cols; col++) {

      data[(row-1) + (col-1) * cols] = 0;
    }
  }

  strcpy(matrixP[matrixLocation].matrixName, tempName);
  matrixP[matrixLocation].rows = rows;
  matrixP[matrixLocation].columns = cols;
  matrixP[matrixLocation].data = data;

  return 0;

}
</code>```

Setting Values:

```<code>int setValues(matrix_t* our_matrix, int number_of_matrices) {
  int i, matrix_index;
  for(i = 0; i < number_of_matrices; i++){
    printf("Matrix %i\t %i Rows\t %i Columns - Name: %s\n", i+1, our_matrix[i].rows, our_matrix[i].columns, our_matrix[i].matrixName);
  }

  printf("\nWhich matrix would you like to set the values for?\n");
  printf("Select a matrix number from the list above>\n");

  scanf("%d", &matrix_index);

  while(matrix_index < 1 || matrix_index > number_of_matrices){
    printf("Enter a number from the list of available matrices - number must be greater than zero and less than or equal to the number of available matrices:\n");
    scanf("%d", &matrix_index);
  }

  int max;
  matrix_index -= 1;
  max = our_matrix[matrix_index].columns;

  float *data = our_matrix[matrix_index].data;
  int row = 0, col = 0;
  for (row = 0; row < our_matrix[matrix_index].rows; row++) {
    for (col = 0; col < our_matrix[matrix_index].columns; col++) {

      printf("Enter the value for column number %d of row number %d>\n", col+1, row+2);
      scanf("%f", &data[(row) + (col) * (max)]);
    }
    /* separate rows by newlines */
  }
  our_matrix[matrix_index].data = data;
    return 0;
}
</code>```

When I try call setValues on a 5 x 2 matrix and I give it the values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 these are the values that I get:

I honestly can't fathom how it stores those values and not the 1:10 that i'm passing it.

答:
You have one little confusion in address computation: You inverted row ans col in multiplication.

You write (I replaced max by its value) in setValues

```<code>scanf("%f", &data[(row) + (col) * (our_matrix[matrix_index].columns)]);
</code>```

the same  in create_matrix  function:

```<code>data[(row-1) + (col-1) * cols] = 0;
</code>```

You should have written:

```<code>scanf("%f", &data[(col) + (row) * (our_matrix[matrix_index].columns)]);
</code>```

and

```<code>data[(col-1) + (row-1) * cols] = 0;
</code>```

You can do the math to be convinced:

If rows is 2 and cols is 10, with your method, the max index is 2 + 9 * 10 = 90, it's too big for a 2x10 matrix.

One more thing:

The function create_matrix can be simplified:

```<code>int create_matrix(matrix_t* matrixP, int matrixLocation){

  int rows, cols;

  printf("Enter a name for your matrix>\n");
  /* Warning, you should test what scanf returned! */
  scanf("%s", matrixP[matrixLocation].matrixName);

  printf("Enter the number of rows>\n");
  /* Warning, you should test what scanf returned! */
  scanf("%d", &rows);

  printf("Enter the number of cols>\n");
  /* Warning, you should test what scanf returned! */
  scanf("%d", &cols);

  matrixP[matrixLocation].rows = rows;
  matrixP[matrixLocation].cols = cols;

  /* Warning, you should test what calloc returned! */
  matrixP[matrixLocation].data = calloc(rows * cols, sizeof(float));

  return 0;

}
</code>```

Body:
I am trying to create and store values inside a matrix, represented as a 1 dimensional array.

When I try to set the values, my output comes out wrong.

Matrix Struct

struct matrix{
    char matrixName[50];
    int rows;
    int columns;
    float* data;
};
typedef struct matrix matrix_t;

matrix_t our_matrix[MAX_MATRICES];

Creating the matrix:

int create_matrix(matrix_t* matrixP, int matrixLocation){

  char tempName[50];
  int rows, cols;

  printf("Enter a name for your matrix>\n");
  scanf("%s", tempName);

  printf("Enter the number of rows>\n");
  scanf("%d", &rows);

  printf("Enter the number of cols>\n");
  scanf("%d", &cols);

  float * data = (float *) malloc(rows * cols * sizeof(float));

  int row = 0, col = 0;
  for (row = 1; row <= rows; row++) {
    for (col = 1; col <= cols; col++) {

      data[(row-1) + (col-1) * cols] = 0;
    }
  }

  strcpy(matrixP[matrixLocation].matrixName, tempName);
  matrixP[matrixLocation].rows = rows;
  matrixP[matrixLocation].columns = cols;
  matrixP[matrixLocation].data = data;

  return 0;

}

Setting Values:

int setValues(matrix_t* our_matrix, int number_of_matrices) {
  int i, matrix_index;
  for(i = 0; i < number_of_matrices; i++){
    printf("Matrix %i\t %i Rows\t %i Columns - Name: %s\n", i+1, our_matrix[i].rows, our_matrix[i].columns, our_matrix[i].matrixName);
  }

  printf("\nWhich matrix would you like to set the values for?\n");
  printf("Select a matrix number from the list above>\n");

  scanf("%d", &matrix_index);

  while(matrix_index < 1 || matrix_index > number_of_matrices){
    printf("Enter a number from the list of available matrices - number must be greater than zero and less than or equal to the number of available matrices:\n");
    scanf("%d", &matrix_index);
  }

  int max;
  matrix_index -= 1;
  max = our_matrix[matrix_index].columns;

  float *data = our_matrix[matrix_index].data;
  int row = 0, col = 0;
  for (row = 0; row < our_matrix[matrix_index].rows; row++) {
    for (col = 0; col < our_matrix[matrix_index].columns; col++) {

      printf("Enter the value for column number %d of row number %d>\n", col+1, row+2);
      scanf("%f", &data[(row) + (col) * (max)]);
    }
    /* separate rows by newlines */
  }
  our_matrix[matrix_index].data = data;
    return 0;
}

When I try call setValues on a 5 x 2 matrix and I give it the values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 these are the values that I get:

I honestly can't fathom how it stores those values and not the 1:10 that i'm passing it.

Body:
You have one little confusion in address computation: You inverted row ans col in multiplication.

You write (I replaced max by its value) in setValues

scanf("%f", &data[(row) + (col) * (our_matrix[matrix_index].columns)]);

the same  in create_matrix  function:

data[(row-1) + (col-1) * cols] = 0;

You should have written:

scanf("%f", &data[(col) + (row) * (our_matrix[matrix_index].columns)]);

and

data[(col-1) + (row-1) * cols] = 0;

You can do the math to be convinced:

If rows is 2 and cols is 10, with your method, the max index is 2 + 9 * 10 = 90, it's too big for a 2x10 matrix.

One more thing:

The function create_matrix can be simplified:

int create_matrix(matrix_t* matrixP, int matrixLocation){

  int rows, cols;

  printf("Enter a name for your matrix>\n");
  /* Warning, you should test what scanf returned! */
  scanf("%s", matrixP[matrixLocation].matrixName);

  printf("Enter the number of rows>\n");
  /* Warning, you should test what scanf returned! */
  scanf("%d", &rows);

  printf("Enter the number of cols>\n");
  /* Warning, you should test what scanf returned! */
  scanf("%d", &cols);

  matrixP[matrixLocation].rows = rows;
  matrixP[matrixLocation].cols = cols;

  /* Warning, you should test what calloc returned! */
  matrixP[matrixLocation].data = calloc(rows * cols, sizeof(float));

  return 0;

}


问:
How can I find which object in Java class can't be serialized?
I'm getting the following error in my application:

```<code>WARNING: Cannot serialize session attribute org.ajax4jsf.application.AjaxStateHolder for session 27420D80AE859865FCD27E869C330659
java.io.NotSerializableException: com.his.op.patreg.web.RegistrationForm$5
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1183)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1508)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at java.util.HashMap.writeObject(HashMap.java:1129)
    at sun.reflect.GeneratedMethodAccessor165.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at java.util.HashMap.writeObject(HashMap.java:1129)
    at sun.reflect.GeneratedMethodAccessor165.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547)
    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:440)
    at org.ajax4jsf.application.AjaxStateHolder.writeObject(AjaxStateHolder.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at org.apache.catalina.session.StandardSession.writeObject(StandardSession.java:1700)
    at org.apache.catalina.session.StandardSession.writeObjectData(StandardSession.java:1092)
    at org.apache.catalina.session.FileStore.save(FileStore.java:341)
    at org.apache.catalina.valves.PersistentValve.invoke(PersistentValve.java:187)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1137)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
</code>```

The stack trace isn't providing any good information on which object is not able to serialize. Is there a good way to find the problem child?
My Class is too big and contains a lot of properties and that property contains several other properties so its very difficult to find out which property is not serializable.

答:
Pass -Dsun.io.serialization.extendedDebugInfo=true to the JVM.

Eg: Add SET CATALINA_OPTS=%CATALINA_OPTS% -Dsun.io.serialization.extendedDebugInfo=true in the startup.bat

Body:
I'm getting the following error in my application:

WARNING: Cannot serialize session attribute org.ajax4jsf.application.AjaxStateHolder for session 27420D80AE859865FCD27E869C330659
java.io.NotSerializableException: com.his.op.patreg.web.RegistrationForm$5
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1183)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1377)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1173)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1508)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at java.util.HashMap.writeObject(HashMap.java:1129)
    at sun.reflect.GeneratedMethodAccessor165.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at java.util.HashMap.writeObject(HashMap.java:1129)
    at sun.reflect.GeneratedMethodAccessor165.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1547)
    at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:440)
    at org.ajax4jsf.application.AjaxStateHolder.writeObject(AjaxStateHolder.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1495)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1431)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1177)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at org.apache.catalina.session.StandardSession.writeObject(StandardSession.java:1700)
    at org.apache.catalina.session.StandardSession.writeObjectData(StandardSession.java:1092)
    at org.apache.catalina.session.FileStore.save(FileStore.java:341)
    at org.apache.catalina.valves.PersistentValve.invoke(PersistentValve.java:187)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1137)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

The stack trace isn't providing any good information on which object is not able to serialize. Is there a good way to find the problem child?
My Class is too big and contains a lot of properties and that property contains several other properties so its very difficult to find out which property is not serializable.