问:
Can not retrieve the id of a foreign key [Laravel]
I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.

When the User completes the form, I put the User & demands information inside those 2 tables.

But I do not know how to have the User id to put it inside the demands table.

Here is the function inside my Controller:

```<code>    public function store(Request $request){
        $demand = new Demand;
        $user = new user ;
        $user ->numStudent= $request->NumStudent;
        $user ->role_id = "3";
        $user ->Lastname = $request->LastName;
        $user ->FirstName= $request->FirstName;
        $user ->numero_etudiant = "12345678";
        $user ->email = $request->Email;
        $user ->password = bcrypt('idk');
        $user ->adress= $request->Adress;
        $user ->phone = $request->Phone;
        $user ->parcours = $request->Parcours;

        $demand->status_id= "3";
        //problem below
        $demand->User_id= $User;
        //
        $demand->time_id = $request->LoanTime;
        $demand->creation_date = $request->CreationDate;
        $demand->comments = "";

        $user ->save();
        $demand->save();

        return redirect('/demands_list');

    }

</code>```

But it says "Can't use method return value in write context".

Cordially

答:
Assuming by your tags that you are looking for an Eloquent (i.e. Laravel) way of doing this.

The short answer: use route model binding and keep your controller methods organized and single-focused.

As already answered, your User needs to be saved first.  I would recommend you do this step in its own controller:

// UsersController.php
public function store(Request $request) {
    $attributes = $request->validate([
       // validation rules
    ]);

    $user = User::create($attributes);

    return redirect('/users/' . $user->id);
}
```

<p>Now that you have a <code>User</code> created, you can then attach related models.  Create a separate set of routes pointing to a separate controller for handling the relationship:</p>

<pre class="lang-php prettyprint-override"><code>// routes/web.php
Route::get('/user/{user}/demands', 'UserDemandsController@index');
Route::post('/user/{user}/demands', 'UserDemandsController@store');
//                 ^^^^^^
//       used with route model binding

</code>```

Here's where route model binding comes into play, loading the model straight from the route parameters ({user}):

// UserDemandsController.php
public function store(Request $request, User $user) {  // <-- ROUTE MODEL BINDING
    $attributes = $request->validate([
       // validation rules
    ]);

    $user->demands()->create($attributes);
}
```

The result is very clean, simple code.

Body:
I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.

When the User completes the form, I put the User & demands information inside those 2 tables.

But I do not know how to have the User id to put it inside the demands table.

Here is the function inside my Controller:

    public function store(Request $request){
        $demand = new Demand;
        $user = new user ;
        $user ->numStudent= $request->NumStudent;
        $user ->role_id = "3";
        $user ->Lastname = $request->LastName;
        $user ->FirstName= $request->FirstName;
        $user ->numero_etudiant = "12345678";
        $user ->email = $request->Email;
        $user ->password = bcrypt('idk');
        $user ->adress= $request->Adress;
        $user ->phone = $request->Phone;
        $user ->parcours = $request->Parcours;

        $demand->status_id= "3";
        //problem below
        $demand->User_id= $User;
        //
        $demand->time_id = $request->LoanTime;
        $demand->creation_date = $request->CreationDate;
        $demand->comments = "";

        $user ->save();
        $demand->save();

        return redirect('/demands_list');

    }

But it says "Can't use method return value in write context".

Cordially

Body:
Assuming by your tags that you are looking for an Eloquent (i.e. Laravel) way of doing this.

The short answer: use route model binding and keep your controller methods organized and single-focused.

As already answered, your User needs to be saved first.  I would recommend you do this step in its own controller:

// UsersController.php
public function store(Request $request) {
    $attributes = $request->validate([
       // validation rules
    ]);

    $user = User::create($attributes);

    return redirect('/users/' . $user->id);
}

Now that you have a User created, you can then attach related models.  Create a separate set of routes pointing to a separate controller for handling the relationship:

// routes/web.php
Route::get('/user/{user}/demands', 'UserDemandsController@index');
Route::post('/user/{user}/demands', 'UserDemandsController@store');
//                 ^^^^^^
//       used with route model binding

Here's where route model binding comes into play, loading the model straight from the route parameters ({user}):

// UserDemandsController.php
public function store(Request $request, User $user) {  // <-- ROUTE MODEL BINDING
    $attributes = $request->validate([
       // validation rules
    ]);

    $user->demands()->create($attributes);
}

The result is very clean, simple code.


来源: stackexchange

问:
How does ConcurrentHashMap.get() prevent dirty read?
I am looking at the source code of ConcurrentHashMap and wondering how the get() method works without any monitor, here's the code:

```<code>public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek))) // mark here for possible dirty read
                    return e.val;
            }
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek)))) // mark here for possible dirty read
                    return e.val;
            }
        }
        return null;
    }
</code>```

The two lines I marked are doing the same thing: checking if the key of the current Node<K, V> equals to the key needed. If true, will return its corresponding value. But what if another thread cuts in before return and remove() this node from the data structure. Since the local variable e is still holding the reference of the removed node, GC will leave it be and the get() method will still return the removed value, thus causing a dirty read.

Did I miss something?

答:
It doesn't:

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. (More formally, an update operation for a given key bears a happens-before relation with any (non-null) retrieval for that key reporting the updated value.)

This is generally not a problem, since get will never return a result that couldn't have happened if the get method acquired a lock, blocking the update operation in the other thread. You just get the result as if the get call happened before the update operation began.

So, if you don't mind whether the get happens before or after the update, you also shouldn't mind it happening during the update, because there is no observable difference between during and before. If you do want the get to appear to happen after the update, then you will need to signal from the updating thread that the update is complete; waiting to acquire a lock wouldn't achieve that anyway, because you might get the lock before the update happens (in which case you'd get the same result as if you didn't acquire the lock).

ContentLicense: CC BY-SA 4.0

Body:
I am looking at the source code of ConcurrentHashMap and wondering how the get() method works without any monitor, here's the code:

public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek))) // mark here for possible dirty read
                    return e.val;
            }
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek)))) // mark here for possible dirty read
                    return e.val;
            }
        }
        return null;
    }

The two lines I marked are doing the same thing: checking if the key of the current Node<K, V> equals to the key needed. If true, will return its corresponding value. But what if another thread cuts in before return and remove() this node from the data structure. Since the local variable e is still holding the reference of the removed node, GC will leave it be and the get() method will still return the removed value, thus causing a dirty read.

Did I miss something?


问:
SOAP request object containing null values
I am trying to implement a SOAP web service in ASP.NET Core. I generated the proxy code with dotnet svcutil and a sample request with SoapUI.

The problem is that whenever I try to post the request to my service, the request object I get is not null, but all its values are. Specifically, I am testing it with an object of this class:

```<code>[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.3")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="riceviPrenotazione", WrapperNamespace="http://farpresa.esterni.ised.it/", IsWrapped=true)]
public partial class riceviPrenotazioneRequest
{

    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://farpresa.esterni.ised.it/", Order=0)]
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public prenotazione arg0;

    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://farpresa.esterni.ised.it/", Order=1)]
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public infoUtente arg1;

    public riceviPrenotazioneRequest()
    {
    }

    public riceviPrenotazioneRequest(prenotazione arg0, infoUtente arg1)
    {
        this.arg0 = arg0;
        this.arg1 = arg1;
    }
}
</code>```

This is the proxy implementation:

```<code>public class FederFarma : FarPreSaEsterniWs
{
    public Task<riceviPrenotazioneResponse> riceviPrenotazione(riceviPrenotazioneRequest request)
    {
        // code...
    }

    public Task<eliminaPrenotazioneResponse> eliminaPrenotazione(eliminaPrenotazioneRequest request)
    {
        // code...
    }

    public Task<verificaDisponibilitaResponse> verificaDisponibilita(verificaDisponibilitaRequest request)
    {
        // code...
    }
}
</code>```

The function being called is the first one (riceviPrenotazione). Its parameter (request) is not null, but arg0 and arg1 are.

This is my interface:

```<code>[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.3")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://farpresa.esterni.ised.it/", ConfigurationName="FarPreSaEsterniWs")]
public interface FarPreSaEsterniWs
{

    [System.ServiceModel.OperationContractAttribute(Action="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/riceviPrenotazioneRequest", ReplyAction="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/riceviPrenotazioneResponse")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
    System.Threading.Tasks.Task<riceviPrenotazioneResponse> riceviPrenotazione(riceviPrenotazioneRequest request);

    [System.ServiceModel.OperationContractAttribute(Action="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/eliminaPrenotazioneRequest", ReplyAction="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/eliminaPrenotazioneResponse")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
    System.Threading.Tasks.Task<eliminaPrenotazioneResponse> eliminaPrenotazione(eliminaPrenotazioneRequest request);

    [System.ServiceModel.OperationContractAttribute(Action="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/verificaDisponibilitaRequest", ReplyAction="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/verificaDisponibilitaResponse")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
    System.Threading.Tasks.Task<verificaDisponibilitaResponse> verificaDisponibilita(verificaDisponibilitaRequest request);
}
</code>```

And this is the XML I'm sending via SoapUI:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:far="http://farpresa.esterni.ised.it/">
   <soapenv:Header/>
   <soapenv:Body>
      <far:riceviPrenotazione>
         <!--Optional:-->
         <arg0>
            <!--Optional:-->
            <anagrafica>
               <!--Optional:-->
               <cellulare>3333333333</cellulare>
               <codice>123</codice>
               <!--Optional:-->
               <codiceFiscale>RSSMRA01A00L885A</codiceFiscale>
               <!--Optional:-->
               <cognome>Rossi</cognome>
               <!--Optional:-->
               <comuneDiNascita>
                  <!--Optional:-->
                  <codice>L885</codice>
                  <!--Optional:-->
                  <descrizione>Vignola</descrizione>
                  <!--Optional:-->
                  <fiscale>L885</fiscale>
                  <!--Optional:-->
                  <nazione>
                     <!--Optional:-->
                     <codice>ITA</codice>
                     <!--Optional:-->
                     <descrizione>Italia</descrizione>
                     <!--Optional:-->
                     <fiscale>ITA</fiscale>
                  </nazione>
                  <!--Optional:-->
                  <provincia>MO</provincia>
                  <!--Optional:-->
                  <regione>
                     <!--Optional:-->
                     <codice>ER</codice>
                     <!--Optional:-->
                     <descrizione>Emilia-Romagna</descrizione>
                  </regione>
               </comuneDiNascita>
               <!--Optional:-->
               <domicilioCap>41057</domicilioCap>
               <!--Optional:-->
               <domicilioComune>
                  <!--Optional:-->
                  <codice>F257</codice>
                  <!--Optional:-->
                  <descrizione>Modena</descrizione>
                  <!--Optional:-->
                  <fiscale>F257</fiscale>
                  <!--Optional:-->
                  <nazione>
                     <!--Optional:-->
                     <codice>ITA</codice>
                     <!--Optional:-->
                     <descrizione>Italia</descrizione>
                     <!--Optional:-->
                     <fiscale>ITA</fiscale>
                  </nazione>
                  <!--Optional:-->
                  <provincia>MO</provincia>
                  <!--Optional:-->
                  <regione>
                     <!--Optional:-->
                     <codice>ER</codice>
                     <!--Optional:-->
                     <descrizione>Emilia-Romagna</descrizione>
                  </regione>
               </domicilioComune>
               <!--Optional:-->
               <domicilioIndirizzo>Via Finta, 12</domicilioIndirizzo>
               <!--Optional:-->
               <nome>Mario</nome>
               <!--Optional:-->
               <sesso>M</sesso>
            </anagrafica>
            <!--Optional:-->
            <codice>111</codice>
            <!--Optional:-->
            <!--Zero or more repetitions:-->
            <listaPrenotato>
               <!--Optional:-->
               <prestazione>
                  <!--Optional:-->
                  <codice>222</codice>
                  <!--Optional:-->
                  <codiceRegionale>222</codiceRegionale>
                  <!--Optional:-->
                  <descrizione>Niente di che</descrizione>
                  <!--Optional:-->
                  <specialita>Nullafacentismo</specialita>
               </prestazione>
               <prezzoUnitario>10</prezzoUnitario>
               <quantita>1</quantita>
            </listaPrenotato>
            <!--Optional:-->
            <NRE>080A01234567890</NRE>
            <!--Optional:-->
            <note>Boh</note>
            <prezzoTotale>10</prezzoTotale>
         </arg0>
         <!--Optional:-->
         <arg1>
            <!--Optional:-->
            <nomeUtente>username</nomeUtente>
            <!--Optional:-->
            <password>password</password>
         </arg1>
      </far:riceviPrenotazione>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

According to what I found online, this seems a namespace problem, but all namespaces seem okay to me - SoapUI is consistent with the auto-generated classes, and most importantly they were generated from the same WSDL and not modified. What could be the cause?

答:
Looks like the same issue as mentioned on github: https://github.com/DigDes/SoapCore/issues/79 I assume from the comments you are using SoapCore

Answer was:

Just needed to change DataContractSerializer to XmlSerializer in startup:

```<code>app.UseSoapEndpoint<MyService>("/MyService.svc", new BasicHttpBinding(), SoapSerializer.DataContractSerializer);
</code>```

for this:

```<code>app.UseSoapEndpoint<MyService>("/MyService.svc", new BasicHttpBinding(), SoapSerializer.XmlSerializer);
</code>```

That solution worked for me.

Body:
I am trying to implement a SOAP web service in ASP.NET Core. I generated the proxy code with dotnet svcutil and a sample request with SoapUI.

The problem is that whenever I try to post the request to my service, the request object I get is not null, but all its values are. Specifically, I am testing it with an object of this class:

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.3")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="riceviPrenotazione", WrapperNamespace="http://farpresa.esterni.ised.it/", IsWrapped=true)]
public partial class riceviPrenotazioneRequest
{

    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://farpresa.esterni.ised.it/", Order=0)]
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public prenotazione arg0;

    [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://farpresa.esterni.ised.it/", Order=1)]
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public infoUtente arg1;

    public riceviPrenotazioneRequest()
    {
    }

    public riceviPrenotazioneRequest(prenotazione arg0, infoUtente arg1)
    {
        this.arg0 = arg0;
        this.arg1 = arg1;
    }
}

This is the proxy implementation:

public class FederFarma : FarPreSaEsterniWs
{
    public Task<riceviPrenotazioneResponse> riceviPrenotazione(riceviPrenotazioneRequest request)
    {
        // code...
    }

    public Task<eliminaPrenotazioneResponse> eliminaPrenotazione(eliminaPrenotazioneRequest request)
    {
        // code...
    }

    public Task<verificaDisponibilitaResponse> verificaDisponibilita(verificaDisponibilitaRequest request)
    {
        // code...
    }
}

The function being called is the first one (riceviPrenotazione). Its parameter (request) is not null, but arg0 and arg1 are.

This is my interface:

[System.CodeDom.Compiler.GeneratedCodeAttribute("dotnet-svcutil", "1.0.3")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://farpresa.esterni.ised.it/", ConfigurationName="FarPreSaEsterniWs")]
public interface FarPreSaEsterniWs
{

    [System.ServiceModel.OperationContractAttribute(Action="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/riceviPrenotazioneRequest", ReplyAction="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/riceviPrenotazioneResponse")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
    System.Threading.Tasks.Task<riceviPrenotazioneResponse> riceviPrenotazione(riceviPrenotazioneRequest request);

    [System.ServiceModel.OperationContractAttribute(Action="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/eliminaPrenotazioneRequest", ReplyAction="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/eliminaPrenotazioneResponse")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
    System.Threading.Tasks.Task<eliminaPrenotazioneResponse> eliminaPrenotazione(eliminaPrenotazioneRequest request);

    [System.ServiceModel.OperationContractAttribute(Action="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/verificaDisponibilitaRequest", ReplyAction="http://farpresa.esterni.ised.it/FarPreSaEsterniWs/verificaDisponibilitaResponse")]
    [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
    System.Threading.Tasks.Task<verificaDisponibilitaResponse> verificaDisponibilita(verificaDisponibilitaRequest request);
}

And this is the XML I'm sending via SoapUI:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:far="http://farpresa.esterni.ised.it/">
   <soapenv:Header/>
   <soapenv:Body>
      <far:riceviPrenotazione>

         <arg0>

            <anagrafica>

               <cellulare>3333333333</cellulare>
               <codice>123</codice>

               <codiceFiscale>RSSMRA01A00L885A</codiceFiscale>

               <cognome>Rossi</cognome>

               <comuneDiNascita>

                  <codice>L885</codice>

                  <descrizione>Vignola</descrizione>

                  <fiscale>L885</fiscale>

                  <nazione>

                     <codice>ITA</codice>

                     <descrizione>Italia</descrizione>

                     <fiscale>ITA</fiscale>
                  </nazione>

                  <provincia>MO</provincia>

                  <regione>

                     <codice>ER</codice>

                     <descrizione>Emilia-Romagna</descrizione>
                  </regione>
               </comuneDiNascita>

               <domicilioCap>41057</domicilioCap>

               <domicilioComune>

                  <codice>F257</codice>

                  <descrizione>Modena</descrizione>

                  <fiscale>F257</fiscale>

                  <nazione>

                     <codice>ITA</codice>

                     <descrizione>Italia</descrizione>

                     <fiscale>ITA</fiscale>
                  </nazione>

                  <provincia>MO</provincia>

                  <regione>

                     <codice>ER</codice>

                     <descrizione>Emilia-Romagna</descrizione>
                  </regione>
               </domicilioComune>

               <domicilioIndirizzo>Via Finta, 12</domicilioIndirizzo>

               <nome>Mario</nome>

               <sesso>M</sesso>
            </anagrafica>

            <codice>111</codice>

            <listaPrenotato>

               <prestazione>

                  <codice>222</codice>

                  <codiceRegionale>222</codiceRegionale>

                  <descrizione>Niente di che</descrizione>

                  <specialita>Nullafacentismo</specialita>
               </prestazione>
               <prezzoUnitario>10</prezzoUnitario>
               <quantita>1</quantita>
            </listaPrenotato>

            <NRE>080A01234567890</NRE>

            <note>Boh</note>
            <prezzoTotale>10</prezzoTotale>
         </arg0>

         <arg1>

            <nomeUtente>username</nomeUtente>

            <password>password</password>
         </arg1>
      </far:riceviPrenotazione>
   </soapenv:Body>
</soapenv:Envelope>

According to what I found online, this seems a namespace problem, but all namespaces seem okay to me - SoapUI is consistent with the auto-generated classes, and most importantly they were generated from the same WSDL and not modified. What could be the cause?

Body:
Looks like the same issue as mentioned on github: https://github.com/DigDes/SoapCore/issues/79 I assume from the comments you are using SoapCore

Answer was:

Just needed to change DataContractSerializer to XmlSerializer in startup:

app.UseSoapEndpoint<MyService>("/MyService.svc", new BasicHttpBinding(), SoapSerializer.DataContractSerializer);

for this:

app.UseSoapEndpoint<MyService>("/MyService.svc", new BasicHttpBinding(), SoapSerializer.XmlSerializer);

That solution worked for me.


问:
How to create a dataframe from a dictionary of un-equal length lists
Suppose we have a dictionary

```<code>dict = {'list1' = ['a','b','e'],
        'list2' = ['a','c'],
        'list3' = ['a','b','d']}
</code>```

How can we create a dataframe whose columns is predefined as below

```<code>         a    b    c    d    e    f
list1    1    1    0    0    1    0
list2    1    0    1    0    0    0
list3    1    1    0    1    0    0
</code>```

Any suggestions would be greatly appreciated.
Thanks

答:
This does the trick:

import pandas as pd

def sets_to_dataframe(d, keys):
    rows = []
    index = []
    for label, values in d.items():
        index.append(label)
        rows.append([int(key in values) for key in keys])
    return pd.DataFrame(rows, index=index, columns=keys)

d = {
    "list1": ["a", "b", "e"],
    "list2": ["a", "c"],
    "list3": ["a", "b", "d"],
}

print(
    sets_to_dataframe(
        d, keys=["a", "b", "c", "d", "e", "f"]
    )
)
```

<p>Output:</p>

```       a  b  c  d  e  f
list1  1  1  0  0  1  0
list2  1  0  1  0  0  0
list3  1  1  0  1  0  0
```

Body:
Suppose we have a dictionary

dict = {'list1' = ['a','b','e'],
        'list2' = ['a','c'],
        'list3' = ['a','b','d']}

How can we create a dataframe whose columns is predefined as below

         a    b    c    d    e    f
list1    1    1    0    0    1    0
list2    1    0    1    0    0    0
list3    1    1    0    1    0    0

Any suggestions would be greatly appreciated.
Thanks

Body:
This does the trick:

import pandas as pd

def sets_to_dataframe(d, keys):
    rows = []
    index = []
    for label, values in d.items():
        index.append(label)
        rows.append([int(key in values) for key in keys])
    return pd.DataFrame(rows, index=index, columns=keys)

d = {
    "list1": ["a", "b", "e"],
    "list2": ["a", "c"],
    "list3": ["a", "b", "d"],
}

print(
    sets_to_dataframe(
        d, keys=["a", "b", "c", "d", "e", "f"]
    )
)

Output:

       a  b  c  d  e  f
list1  1  1  0  0  1  0
list2  1  0  1  0  0  0
list3  1  1  0  1  0  0


问:
Load data from SQL Server to datagridview using a thread
I'm trying to load data from a SQL Server database into a DataGridView using threading with delegates and later will try to add a loading or waiting form. But I can't make it work.

Dim t1 As Thread

Private Delegate Sub delegate_updatedgv()

Private Sub mainform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    t1 = New Thread(AddressOf load_dgv)
    t1.Start()
End Sub

Private Function load_dgv()
    Try
        If DBCon.State = ConnectionState.Closed Then
            DBCon.Open()
        End If

        DBCmd = New SqlCommand("SELECT * FROM Jobs ", DBCon)
        DBCmd.ExecuteNonQuery()
        Dim DBDT = New DataTable
        Dim DBDA = New SqlDataAdapter(DBCmd)
        Dim RecordCount = DBDA.Fill(DBDT)
        assignit(DBDT)
        DBCon.Close()

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        If DBCon.State = ConnectionState.Open Then DBCon.Close()
    End Try
End Function

Sub assignit(ByVal x As DataTable)
    If Me.InvokeRequired Then
        Me.Invoke(New delegate_updatedgv(AddressOf assignit))
    End If
    GridControl1.DataSource = x
End Sub
```

and its not working at all

答:
Your delegate

Private Delegate Sub delegate_updatedgv()
```

<p>and your method </p>

<pre class="lang-vb prettyprint-override"><code>Sub assignit(ByVal x As DataTable)
</code>```

don't have the same signature. Actually the compiler already tells you this in an error message...

You could just use Action(Of DataTable). There is no need to create a new delegate.

You also needed to set the DataSource only when invoking on the UI thread. You can achieve that by using Else.

Sub assignit(ByVal x As DataTable)
    If Me.InvokeRequired Then
        Me.Invoke(New Action(Of DataTable)(AddressOf assignit))
    Else
        GridControl1.DataSource = x
    End If
End Sub
```

<p>Alternately, you can also declare the delegate properly. Either way</p>

<pre class="lang-vb prettyprint-override"><code>Private Delegate Sub delegate_updatedgv(x As DataTable)
</code>```

Also, the method / function Private Function load_dgv() has no return type, and nothing is returned. So it is better suited as a sub.

Private Sub load_dgv()
    ' ...
End Sub
```

The compiler also warns you about this.

Pay attention to compiler error messages!

Body:
I'm trying to load data from a SQL Server database into a DataGridView using threading with delegates and later will try to add a loading or waiting form. But I can't make it work.

Dim t1 As Thread

Private Delegate Sub delegate_updatedgv()

Private Sub mainform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    t1 = New Thread(AddressOf load_dgv)
    t1.Start()
End Sub

Private Function load_dgv()
    Try
        If DBCon.State = ConnectionState.Closed Then
            DBCon.Open()
        End If

        DBCmd = New SqlCommand("SELECT * FROM Jobs ", DBCon)
        DBCmd.ExecuteNonQuery()
        Dim DBDT = New DataTable
        Dim DBDA = New SqlDataAdapter(DBCmd)
        Dim RecordCount = DBDA.Fill(DBDT)
        assignit(DBDT)
        DBCon.Close()

    Catch ex As Exception
        MsgBox(ex.Message)
    Finally
        If DBCon.State = ConnectionState.Open Then DBCon.Close()
    End Try
End Function

Sub assignit(ByVal x As DataTable)
    If Me.InvokeRequired Then
        Me.Invoke(New delegate_updatedgv(AddressOf assignit))
    End If
    GridControl1.DataSource = x
End Sub

and its not working at all

Body:
Your delegate

Private Delegate Sub delegate_updatedgv()

and your method

Sub assignit(ByVal x As DataTable)

don't have the same signature. Actually the compiler already tells you this in an error message...

You could just use Action(Of DataTable). There is no need to create a new delegate.

You also needed to set the DataSource only when invoking on the UI thread. You can achieve that by using Else.

Sub assignit(ByVal x As DataTable)
    If Me.InvokeRequired Then
        Me.Invoke(New Action(Of DataTable)(AddressOf assignit))
    Else
        GridControl1.DataSource = x
    End If
End Sub

Alternately, you can also declare the delegate properly. Either way

Private Delegate Sub delegate_updatedgv(x As DataTable)

Also, the method / function Private Function load_dgv() has no return type, and nothing is returned. So it is better suited as a sub.

Private Sub load_dgv()
    ' ...
End Sub

The compiler also warns you about this.

Pay attention to compiler error messages!


问:
Addition to an integer variable which already has a set value
Its my second day of learning how to code. I chose C++ as my first language and decided to make a cpp project. This project has 4 question and 2 answers for each question (Yes and No). In the end it must cout you a result which depends on how many answers were correct. Everything i did was working except 1 thing.
So for example if you answered at least 3 of the questions incorrectly you will receive cout << "You are stupid";
And if the amount of incorrect answer is lower than 3 then you will receive a cout << "You are smart";

As i mentioned before, i did everything right except one thing.
In order to keep track of how many questions were correct/incorrect ive set a variable:

```<code>int amount_of_correct_answers;
amount_of_correct_answers = 0;
</code>```

Then i made it so that if the answer is correct, it will add 1 to this variable

```<code>if(answer == true_answer)
{
 amount_of_correct_answers + 1;
}
else
{
 amount_of_correct_answers + 0;
 }
</code>```

So in the end of the test you see the result(if you are stupid or smart). My question is:
How do i add/substract from a variable? How do i add 1 to a variable thats set as 0 if the answer is correct? Because the code i wrote above didnt work. I think i am on the right track and my problem is syntax because i have no idea how to add/substract to/from a variable with a set value.

P.S. Keep in mind that i am very new to coding as i mentioned before, so please explain it in simple words or an example. Thank you

答:
If you've got a variable called amount_of_correct_answers you can increment/decrement it in 3 ways:

```<code>amount_of_correct_answers = amount_of_correct_answers + 1;
amount_of_correct_answers+=1;
amount_of_correct_answers++; // you could use also ++amount_of_correct_answers in this case and have the same result
</code>```

Body:
Its my second day of learning how to code. I chose C++ as my first language and decided to make a cpp project. This project has 4 question and 2 answers for each question (Yes and No). In the end it must cout you a result which depends on how many answers were correct. Everything i did was working except 1 thing.
So for example if you answered at least 3 of the questions incorrectly you will receive cout << "You are stupid";
And if the amount of incorrect answer is lower than 3 then you will receive a cout << "You are smart";

As i mentioned before, i did everything right except one thing.
In order to keep track of how many questions were correct/incorrect ive set a variable:

int amount_of_correct_answers;
amount_of_correct_answers = 0;

Then i made it so that if the answer is correct, it will add 1 to this variable

if(answer == true_answer)
{
 amount_of_correct_answers + 1;
}
else
{
 amount_of_correct_answers + 0;
 }

So in the end of the test you see the result(if you are stupid or smart). My question is:
How do i add/substract from a variable? How do i add 1 to a variable thats set as 0 if the answer is correct? Because the code i wrote above didnt work. I think i am on the right track and my problem is syntax because i have no idea how to add/substract to/from a variable with a set value.

P.S. Keep in mind that i am very new to coding as i mentioned before, so please explain it in simple words or an example. Thank you

Body:
If you've got a variable called amount_of_correct_answers you can increment/decrement it in 3 ways:

amount_of_correct_answers = amount_of_correct_answers + 1;
amount_of_correct_answers+=1;
amount_of_correct_answers++; // you could use also ++amount_of_correct_answers in this case and have the same result


问:
Is there a way to Log my errors on a LIVE hosting/production server?
I built a Web App using PHP and Laravel. I've tested the app relentlessly for a long time now and everything works great on my local computer. In my .env file, AppDebug is set to true and in the documentation, it says to make sure on a LIVE hosting/production environment that it should be set to false. After setting it to false, the problem is now, my client is going through the app himself to test it out and when he creates a Game, which is just a simple Form with a few input fields and clicks the Submit button, he gets a 500 Server error. The weird thing is that the game is still being inserted into the database, even though he receives this error. If I put the AppDebug back to true, there is no 500 error message anymore and everything works as it should, but I cannot leave it set to true. And a 500 server error is not giving me enough of a description in order for me to debug this. So how can I debug this. Do errors in Laravel get logged somewhere that would be more descriptive in the error?</p>

答:
What I generally use is Telescope: https://laravel.com/docs/6.x/telescope

You have to change some things to get the errors in production:
In telescopeServiceProvider change this:

```<code>Telescope::filter(function (IncomingEntry $entry) {
   if ( $this->app->isLocal()) {
      return true;
   }
   ...
}
</code>```

To this:

```<code>Telescope::filter(function (IncomingEntry $entry) {
   return true; //this will prevent the condition of checking if is in local
   if ( $this->app->isLocal()) {
      return true;
   }
   ...
}
</code>```

But, you can see all the errors in /storage/logs as the others stated
Cheers!

Body:
What I generally use is Telescope: https://laravel.com/docs/6.x/telescope

You have to change some things to get the errors in production:
In telescopeServiceProvider change this:

Telescope::filter(function (IncomingEntry $entry) {
   if ( $this->app->isLocal()) {
      return true;
   }
   ...
}

To this:

Telescope::filter(function (IncomingEntry $entry) {
   return true; //this will prevent the condition of checking if is in local
   if ( $this->app->isLocal()) {
      return true;
   }
   ...
}

But, you can see all the errors in /storage/logs as the others stated
Cheers!


问:
Multiple instances of Prolog clauses with identical ground head. Any uses besides for this besides (dubious) control of computation?
In SWI Prolog:

Exact clause duplicates are allowed:

```<code>a(1).
a(1).
</code>```

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```

or even:

```<code>c :- format("Hello from first c!").
c :- format("Hello from second c!").
</code>```

```<code>Hello from first c!
true ;
Hello from second c!
true.
</code>```

More generally, so are clauses with identical fully ground heads but differing bodies:

```<code>b(1) :- format("Hello from first b!").
b(1) :- format("Hello from second b!").
</code>```

```<code>?- b(1).
Hello from first b!
true ;
Hello from second b!
true.
</code>```

Clauses with identical non-ground head feel somewhat more reasonable:

```<code>p(X) :- format("Yup, this is p(~w)",X).
p(X) :- format("Yup, this is also p(~w)",X).
p(X) :- format("You think you can get rid of good old p(~w) just like that?",X).
</code>```

```<code>?- p('homer simpson').
Yup, this is p(homer simpson)
true ;
Yup, this is also p(homer simpson)
true ;
You think you can get rid of good old p(homer simpson) just like that?
true.
</code>```

```<code>?- p(X).
Yup, this is p(_4782)
true ;
Yup, this is also p(_4782)
true ;
You think you can get rid of good old p(_4782) just like that?
true.
</code>```

This covers the reasonable case of clauses with a guarded body:

```<code>p(X) :- X < 0,   format("It's less than 0: ~w", X).
p(X) :- X =:= 0, format("It's exactly 0: ~w", X).
p(X) :- X > 0,   format("It's larger than 0: ~w", X).
</code>```

On second thoughts ... we already encounter the ultimate case in the built-in repeat:

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```0

Or can construct an intermediate case easily:

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```1

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```2

Somehow textbooks gloss over the fact that predicates have additional semantics: they can not only be false or true for any given ground arguments, but they can actually be true(n) - "true n times, n ≥ 0" .

From a theory standpoint, this is dubious, at least for vanilla classical logic.

On the other hand, it is useful from a computational standpoint for:

Side-effects (rather for output than for input, and rather marginally).

Control of the computation (i.e. repeat).

Are there any other uses?

I really feel the compiler should flag variable-less cases like a/1, c/0, b/1 above as errors (easy to detect), and even repeat/0 should probably have a value: repeat(Count). Anything which redoes successfully should NOT redo successfully in the same context on exactly the same ground arguments. It has the same squishy feeling of irrelevancy as a(X) :- b(Y). b(Z). Brrr!.

答:
Yes, for diagnostic purposes in pure programs. By duplicating a clause you can answer the question how often the clause contributes to solutions.

That is, you count the answers/solutions you get from a query and compare these to the same program plus the duplicated clause. If the number of (redundant) solutions now increases you know that this clause contributes. The ld factor tells you how often.

Note that a tracer cannot tell you this as easily.

Body:
In SWI Prolog:

Exact clause duplicates are allowed:

a(1).
a(1).

?- a(X).
X = 1 ;
X = 1.

or even:

c :- format("Hello from first c!").
c :- format("Hello from second c!").

Hello from first c!
true ;
Hello from second c!
true.

More generally, so are clauses with identical fully ground heads but differing bodies:

b(1) :- format("Hello from first b!").
b(1) :- format("Hello from second b!").

?- b(1).
Hello from first b!
true ;
Hello from second b!
true.

Clauses with identical non-ground head feel somewhat more reasonable:

p(X) :- format("Yup, this is p(~w)",X).
p(X) :- format("Yup, this is also p(~w)",X).
p(X) :- format("You think you can get rid of good old p(~w) just like that?",X).

?- p('homer simpson').
Yup, this is p(homer simpson)
true ;
Yup, this is also p(homer simpson)
true ;
You think you can get rid of good old p(homer simpson) just like that?
true.

?- p(X).
Yup, this is p(_4782)
true ;
Yup, this is also p(_4782)
true ;
You think you can get rid of good old p(_4782) just like that?
true.

This covers the reasonable case of clauses with a guarded body:

p(X) :- X < 0,   format("It's less than 0: ~w", X).
p(X) :- X =:= 0, format("It's exactly 0: ~w", X).
p(X) :- X > 0,   format("It's larger than 0: ~w", X).

On second thoughts ... we already encounter the ultimate case in the built-in repeat:

?- repeat.
true ;
true ;
true ;
true ;
…

Or can construct an intermediate case easily:

h :- member(_,[1,2,3]).

?- h.
true ;
true ;
true.

Somehow textbooks gloss over the fact that predicates have additional semantics: they can not only be false or true for any given ground arguments, but they can actually be true(n) - "true n times, n ≥ 0" .

From a theory standpoint, this is dubious, at least for vanilla classical logic.

On the other hand, it is useful from a computational standpoint for:

Side-effects (rather for output than for input, and rather marginally).

Control of the computation (i.e. repeat).

Are there any other uses?

I really feel the compiler should flag variable-less cases like a/1, c/0, b/1 above as errors (easy to detect), and even repeat/0 should probably have a value: repeat(Count). Anything which redoes successfully should NOT redo successfully in the same context on exactly the same ground arguments. It has the same squishy feeling of irrelevancy as a(X) :- b(Y). b(Z). Brrr!.


问:
Regular expression - repeat groups
I have text:

```<code><b>Title1:</b><br/><b>Title2:</b> Value1<br/><b>Title3:</b> Value2<br/><b>Title4:</b> Value3<br/>Value4<b>Title5:</b> Value5<br/>
</code>```

What regex to get:

```<code>[0] => <b>Title1:</b><br/>
[1] => <b>Title2:</b> Value1<br/>
[2] => <b>Title3:</b> Value2<br/>
[3] => <b>Title4:</b> Value3<br/>Value4
[4] => <b>Title5:</b> Value5<br/>
</code>```

My variant not working:
(.*?)(.*?)

答:
A resource like this can be very useful in troubleshooting regex: https://regex101.com/

Looks like you are missing an escape character in (.*?)(.*?)

(.*?)<\/b>(.*?) should stop an error from being thrown for that current regex and get you close to the result, you'll need to work with it a bit more to get the exact results you want though.

(.*?)<\/b>(.*?)
 should be a bit closer I think as it looks like you want to include the break tags.

Title: Regular expression - repeat groups

Body:
I have text:

Title1:
Title2: Value1
Title3: Value2
Title4: Value3
Value4Title5: Value5

What regex to get:

[0] => Title1:

[1] => Title2: Value1

[2] => Title3: Value2

[3] => Title4: Value3
Value4
[4] => Title5: Value5

My variant not working:
(.*?)(.*?)

Body:
A resource like this can be very useful in troubleshooting regex: https://regex101.com/

Looks like you are missing an escape character in <b>(.*?)</b>(.*?)

<b>(.*?)<\/b>(.*?) should stop an error from being thrown for that current regex and get you close to the result, you'll need to work with it a bit more to get the exact results you want though.

<b>(.*?)<\/b>(.*?)<br\/> should be a bit closer I think as it looks like you want to include the break tags.


问:
Problem with headers in specific services
In my component within my onInit() function, I have a call to list some data. This call is made to a service called "Permission.service" using the following code.

```<code>  ngOnInit() {
    this.listPermissions();
  }

  listPermissions(): void {
    this.permissionService.getPermissions().subscribe(
      res=>{
        this.permissionList=res;
      }
    )
  }
</code>```

However it gives me the following error log:

core.js:1673 ERROR TypeError: Cannot read property 'length' of
  undefined
      at http.js:108
      at Array.forEach ()
      at HttpHeaders.lazyInit (http.js:102)
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.init
  (http.js:166)
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.forEach
  (http.js:235)
      at Observable._subscribe (http.js:1445)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe
  (Observable.js:43)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
  (Observable.js:29)
      at subscribeTo.js:21
      at subscribeToResult (subscribeToResult.js:11)

Using the chrome debugger, the "x-access-token" header brings an undefined value. However calling a diferent service with the exact same code with the exception of the service name, it works just fine.

```<code>export class PermissionsService {
  constructor(private http: HttpClient, private loginService: LoginService, private globalService: GlobalsService) {}
  httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      "x-access-token": this.loginService.userInfo
    })
  };

  getPermissions(): Observable<any[]> {
    return this.http.get<any[]>(
      this.globalService.API_PATH + "readAllPermissions",
      this.httpOptions
    );
  }
...
</code>```

and below is the service that doesn't work:

```<code>export class RolePermissionService {

  constructor(private http: HttpClient, private loginService: LoginService, private globalService: GlobalsService) { }
  httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      "x-access-token": this.loginService.userInfo
    })
  };

  getPermissions(): Observable<any[]> {
    return this.http.get<any[]>(
      this.globalService.API_PATH + "readAllPermissions",
      this.httpOptions
    );
  }
</code>```

The userInfo variable is set in the login functionality before trying to access the component.

答: The problem was solved. I was using the httpOptions that Navbar was sending. But before the login the navbar was initialized already and my headers were undefined. In this service I create a function to initialize my httpOptions and everytime I use this method I get the auth token.</p>

Body:
In my component within my onInit() function, I have a call to list some data. This call is made to a service called "Permission.service" using the following code.

  ngOnInit() {
    this.listPermissions();
  }

  listPermissions(): void {
    this.permissionService.getPermissions().subscribe(
      res=>{
        this.permissionList=res;
      }
    )
  }

However it gives me the following error log:

core.js:1673 ERROR TypeError: Cannot read property 'length' of
  undefined
      at http.js:108
      at Array.forEach ()
      at HttpHeaders.lazyInit (http.js:102)
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.init
  (http.js:166)
      at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.forEach
  (http.js:235)
      at Observable._subscribe (http.js:1445)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe
  (Observable.js:43)
      at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe
  (Observable.js:29)
      at subscribeTo.js:21
      at subscribeToResult (subscribeToResult.js:11)

Using the chrome debugger, the "x-access-token" header brings an undefined value. However calling a diferent service with the exact same code with the exception of the service name, it works just fine.

export class PermissionsService {
  constructor(private http: HttpClient, private loginService: LoginService, private globalService: GlobalsService) {}
  httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      "x-access-token": this.loginService.userInfo
    })
  };

  getPermissions(): Observable<any[]> {
    return this.http.get<any[]>(
      this.globalService.API_PATH + "readAllPermissions",
      this.httpOptions
    );
  }
...

and below is the service that doesn't work:

export class RolePermissionService {

  constructor(private http: HttpClient, private loginService: LoginService, private globalService: GlobalsService) { }
  httpOptions = {
    headers: new HttpHeaders({
      "Content-Type": "application/json",
      "x-access-token": this.loginService.userInfo
    })
  };

  getPermissions(): Observable<any[]> {
    return this.http.get<any[]>(
      this.globalService.API_PATH + "readAllPermissions",
      this.httpOptions
    );
  }

The userInfo variable is set in the login functionality before trying to access the component.


问:
Cleaning dataframe columns for classification
I'm trying to remove all the irrelevant information from one of my columns in my dataframe but have no idea how to do it. I import the data from a CSV file straight to my dataframe.

```<code>0       [{"id": 28, "name": "Action"}, {"id": 12, "nam...

1       [{"id": 12, "name": "Adventure"}, {"id": 14, "...
2       [{"id": 28, "name": "Action"}, {"id": 12, "nam...

4798    [{"id": 28, "name": "Action"}, {"id": 80, "nam...
4799    [{"id": 35, "name": "Comedy"}, {"id": 10749, "...
4800    [{"id": 35, "name": "Comedy"}, {"id": 18, "nam...
</code>```

I would like to just have the genre e.g action, comedy, adventure. If anyone could help me or send me in the correct direction to do this it would be greatly appreciated.

答:
Here is an example:

```<code> ID    Name

 1     Action
 2     Comedy
 3     Adventure

 def printOneCol():
       my_sheet = 'Sheet1'
       file_name = 'C:/Users/you/Desktop/test.xlsx'
       df = pd.read_excel(file_name,sheet_name=my_sheet, usecols='B:B')
       print(df.to_string(index=False))
</code>```

This is via using excel. You can specify which column with usecols='B:B'

Hope it helps out.

Body:
I'm trying to remove all the irrelevant information from one of my columns in my dataframe but have no idea how to do it. I import the data from a CSV file straight to my dataframe.

0       [{"id": 28, "name": "Action"}, {"id": 12, "nam...

1       [{"id": 12, "name": "Adventure"}, {"id": 14, "...
2       [{"id": 28, "name": "Action"}, {"id": 12, "nam...

4798    [{"id": 28, "name": "Action"}, {"id": 80, "nam...
4799    [{"id": 35, "name": "Comedy"}, {"id": 10749, "...
4800    [{"id": 35, "name": "Comedy"}, {"id": 18, "nam...

I would like to just have the genre e.g action, comedy, adventure. If anyone could help me or send me in the correct direction to do this it would be greatly appreciated.

Body:
Here is an example:

 ID    Name

 1     Action
 2     Comedy
 3     Adventure

 def printOneCol():
       my_sheet = 'Sheet1'
       file_name = 'C:/Users/you/Desktop/test.xlsx'
       df = pd.read_excel(file_name,sheet_name=my_sheet, usecols='B:B')
       print(df.to_string(index=False))

This is via using excel. You can specify which column with usecols='B:B'

Hope it helps out.


问:
Julia dataframe directly access row
In Julia DataFrames it is possible to directly access a column :col of a dataframe df by writing df[!, :col]. Is it a similar fast way to directly access a row? I know I can do df[2, :] to get a copy of row 2, but I don't want a copy since I want to change the content of the row.

Cheers Sigurd

答:
Selecting a single row from a data frame returns a DataFrameRow, which is a view of the row in the original data frame. So any changes you make to the DataFrameRow will be reflected in the original data frame:

```<code>julia> using DataFrames

julia> df = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 5     │
│ 3   │ 3     │ 6     │

julia> dfr = df[2, :]
DataFrameRow
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 2   │ 2     │ 5     │

julia> dfr.b = 100
100

julia> df
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 100   │
│ 3   │ 3     │ 6     │
</code>```

Of course, if you just want to change the values of a few entries in a row, you can do that directly without having to first create a DataFrameRow:

```<code>julia> df = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 5     │
│ 3   │ 3     │ 6     │

julia> df[2, :] = [101, 102]
2-element Array{Int64,1}:
 101
 102

julia> df
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 101   │ 102   │
│ 3   │ 3     │ 6     │
</code>```

Title: Julia dataframe directly access row

Body:
Selecting a single row from a data frame returns a DataFrameRow, which is a view of the row in the original data frame. So any changes you make to the DataFrameRow will be reflected in the original data frame:

julia> using DataFrames

julia> df = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 5     │
│ 3   │ 3     │ 6     │

julia> dfr = df[2, :]
DataFrameRow
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 2   │ 2     │ 5     │

julia> dfr.b = 100
100

julia> df
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 100   │
│ 3   │ 3     │ 6     │

Of course, if you just want to change the values of a few entries in a row, you can do that directly without having to first create a DataFrameRow:

julia> df = DataFrame(a=1:3, b=4:6)
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 2     │ 5     │
│ 3   │ 3     │ 6     │

julia> df[2, :] = [101, 102]
2-element Array{Int64,1}:
 101
 102

julia> df
3×2 DataFrame
│ Row │ a     │ b     │
│     │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1   │ 1     │ 4     │
│ 2   │ 101   │ 102   │
│ 3   │ 3     │ 6     │


问:
issues with the in statement using a subquery
Issues with this statement

```<code>    select * from table
        where ID in (case when table1.changes = 40 THEN
        select top 1 STUFF((SELECT  ',' + CAST(ID as varchar) FROM Tabl1
                WHERE UserID = 121   FOR XML PATH('')), 1, 1, '')
                    FROM Tabl1 where UserID = 121
else
id
end
        )
</code>```

Using above, getting an error

Msg 245, Level 16, State 1, Line 3

Conversion failed when converting the nvarchar value '167,196,107,108,169,111,115,16,162' to data type int.

答:
Error is telling you the problem. You're trying to pass a delimited varchar to an int column.

You probably more want this:

```<code>SELECT *
FROM dbo.YourTabLe YT
WHERE EXISTS (SELECT 1
              FROM dbo.OtherTable OT
              WHERE OT.UserID = 121
                AND OT.ID = YT.ID);
</code>```

I personally prefer (NOT) EXISTS instead of (NOT) IN, mainly because NOT EXISTS handles NULL values gracefully, where as NOT IN does not.

Edit: based on the latest edit, however, it is a guess, as the new edit has a malformed query:

```<code>SELECT *
FROM dbo.YourTabLe YT
WHERE (EXISTS (SELECT 1
              FROM dbo.OtherTable OT
              WHERE OT.UserID = 121
                AND OT.ID = YT.ID)
  AND  YT.changes = 40)     --Changes was prefiexed with table1, which doesn't exist in your sample query.
   OR NOT(YT.changes = 40); --I've therefore assumed it was meant to be your table
</code>```

Body:
Issues with this statement

    select * from table
        where ID in (case when table1.changes = 40 THEN
        select top 1 STUFF((SELECT  ',' + CAST(ID as varchar) FROM Tabl1
                WHERE UserID = 121   FOR XML PATH('')), 1, 1, '')
                    FROM Tabl1 where UserID = 121
else
id
end
        )

Using above, getting an error

Msg 245, Level 16, State 1, Line 3

Conversion failed when converting the nvarchar value '167,196,107,108,169,111,115,16,162' to data type int.

Body:
Error is telling you the problem. You're trying to pass a delimited varchar to an int column.

You probably more want this:

SELECT *
FROM dbo.YourTabLe YT
WHERE EXISTS (SELECT 1
              FROM dbo.OtherTable OT
              WHERE OT.UserID = 121
                AND OT.ID = YT.ID);

I personally prefer (NOT) EXISTS instead of (NOT) IN, mainly because NOT EXISTS handles NULL values gracefully, where as NOT IN does not.

Edit: based on the latest edit, however, it is a guess, as the new edit has a malformed query:

SELECT *
FROM dbo.YourTabLe YT
WHERE (EXISTS (SELECT 1
              FROM dbo.OtherTable OT
              WHERE OT.UserID = 121
                AND OT.ID = YT.ID)
  AND  YT.changes = 40)     --Changes was prefiexed with table1, which doesn't exist in your sample query.
   OR NOT(YT.changes = 40); --I've therefore assumed it was meant to be your table


问:
Caller id faker
I want to develop an android application to fake my mobile number to outgoing call. How to do this in android? I havent seen any api/control available to do this? Does android allow this? Is it legal for all the countries? Please give me some insight in this.</p>

答:
I want to develop an android application to fake my mobile number to outgoing call. How to do this in android?

It is not possible.

Does android allow this? Is it legal for all the countries?

No, Android doesn't allow this - probably because it is almost certainly illegal in every country that runs telecommunication systems that conform to international regulations.

Your phone provider is responsible for providing your 'caller id' (your phone number) to whoever you call. In most cases (depending on which country and which provider) you will have the option to 'hide' your telephone number but that isn't guaranteed everywhere in the world nor with all providers.

Even then, this is something that you have to do manually and cannot be done by software. The link to the SO question that cularis mentions has an answer by me which explains (or tries to explain) why it isn't even possible to hide your 'caller id' with software.

ContentLicense: CC BY-SA 3.0

Title: Caller id faker


问:
Helm /bitnami/spark - how to load files to extraVolumeMounts?
I'm using the Helm chart to deploy Spark to Kubernetes in GCE. I've configured extraVolumes and extraVolumeMounts in values.yaml and they were created successfully during deployment.

What is the right way to add files to these volumes during the chart's deployment?

```<code>  ## Array to add extra volumes
  extraVolumes:
    - name: spark-volume

  ## Array to add extra mounts (normally used with extraVolumes)
  extraVolumeMounts:
    - name: spark-volume
      mountPath: /tmp/new-data
</code>```

答:
Depends where are the files. If you have them inside a repo I would use an initContainer to clone it.

This might look like this:

```<code>    initContainers:
      - name: git-clone-spark-volumes
        image: alpine/git
        args:
          - clone
          - --single-branch
          - --branch=master
          - --depth=1
          - --
          - https://github.com/your/repo.git
          - /tmp/new-data
        securityContext:
          runAsUser: 0
        volumeMounts:
          - name: spark-volume
            mountPath: /tmp/new-data
    extraVolumes:
      - name: spark-volume
        emptyDir: {}
    extraVolumeMounts:
      - name: spark-volume
        mountPath: /tmp/new-data
</code>```

This clones the repo (https://github.com/your/repo.git)  into /tmp/new-data folder, to where the spark-volume is mounted.

If your files are key=value based you could use ConfigMap:

```<code>$ kubectl create configmap spark-volume --from-file=configure-pod-container/configmap/game.properties --from-file=configure-pod-container/configmap/ui.properties
</code>```

Which can be used:

```<code>    extraVolumes:
      - name: spark-volume
        configMap:
          name: spark-volume
    extraVolumeMounts:
      - name: spark-volume
        mountPath: /tmp/new-data
</code>```

This is nicely described on Configure a Pod to Use a ConfigMap.

Body:
I'm using the Helm chart to deploy Spark to Kubernetes in GCE. I've configured extraVolumes and extraVolumeMounts in values.yaml and they were created successfully during deployment.

What is the right way to add files to these volumes during the chart's deployment?

  ## Array to add extra volumes
  extraVolumes:
    - name: spark-volume

  ## Array to add extra mounts (normally used with extraVolumes)
  extraVolumeMounts:
    - name: spark-volume
      mountPath: /tmp/new-data

Body:
Depends where are the files. If you have them inside a repo I would use an initContainer to clone it.

This might look like this:

    initContainers:
      - name: git-clone-spark-volumes
        image: alpine/git
        args:
          - clone
          - --single-branch
          - --branch=master
          - --depth=1
          - --
          - https://github.com/your/repo.git
          - /tmp/new-data
        securityContext:
          runAsUser: 0
        volumeMounts:
          - name: spark-volume
            mountPath: /tmp/new-data
    extraVolumes:
      - name: spark-volume
        emptyDir: {}
    extraVolumeMounts:
      - name: spark-volume
        mountPath: /tmp/new-data

This clones the repo (https://github.com/your/repo.git)  into /tmp/new-data folder, to where the spark-volume is mounted.

If your files are key=value based you could use ConfigMap:

$ kubectl create configmap spark-volume --from-file=configure-pod-container/configmap/game.properties --from-file=configure-pod-container/configmap/ui.properties

Which can be used:

    extraVolumes:
      - name: spark-volume
        configMap:
          name: spark-volume
    extraVolumeMounts:
      - name: spark-volume
        mountPath: /tmp/new-data

This is nicely described on Configure a Pod to Use a ConfigMap.


问:
Does props.history.listen in React Router need to be cleaned up in useEffect? If so, what is the right way to do it?
I am trying to implement something that requires listening to the location.

```<code>    useEffect(() => {
        props.history.listen(location => {
            // do stuff here
        });
        return () => {
            props.history.listen(location => {
                // now stop doing stuff
            });
        };
    }, []);
</code>```

I have seen reference to unlisten() but it's not backed up with a lot of upvotes, and if I do console.log(props.history.unlisten()) it comes back as not a function

This is done in App.js.  I am assuming this should be cleaned up, but I'm not sure it actually needs to be.

Does it need to be cleaned up?  If so, what is the correct way to do it?

答:
The return value from props.history.listen is a function. Calling that function will do the teardown, so you just need to return it:

```<code>useEffect(() => {
  const unlisten = props.history.listen(location => {
    // do stuff here
  });
  return unlisten;
}, []);
</code>```

Or:

```<code>useEffect(() => {
  return props.history.listen(location => {
    // do stuff here
  });
}, []);
</code>```

Body:
I am trying to implement something that requires listening to the location.

    useEffect(() => {
        props.history.listen(location => {
            // do stuff here
        });
        return () => {
            props.history.listen(location => {
                // now stop doing stuff
            });
        };
    }, []);

I have seen reference to unlisten() but it's not backed up with a lot of upvotes, and if I do console.log(props.history.unlisten()) it comes back as not a function

This is done in App.js.  I am assuming this should be cleaned up, but I'm not sure it actually needs to be.

Does it need to be cleaned up?  If so, what is the correct way to do it?

Body:
The return value from props.history.listen is a function. Calling that function will do the teardown, so you just need to return it:

useEffect(() => {
  const unlisten = props.history.listen(location => {
    // do stuff here
  });
  return unlisten;
}, []);

Or:

useEffect(() => {
  return props.history.listen(location => {
    // do stuff here
  });
}, []);


问:
String to array based on regex
I would like to split a string base on regex.

Expected input:

```<code>1. recipe description. 2. second step of the description that takes 30 minutes. 3. third step of the description that contain 20g of flour.
</code>```

Now like to split the string based on the starting number. Is that possible?

Expected outcome:

```<code>[
"recipe description.",
"second step of the description that takes 30 minutes.",
"third step of the description that contain 20g of flour."
]
</code>```

I already tried it with const steps = text.split(new RegExp("/^d./", "g")); but its not the expected outcome i would like to have.

答:
Try the following:

var text = "1. recipe description. 2. second step of the description that takes 30 minutes. 3. third step of the description that contain 20g of flour.";
var steps = text.split(/\s*\d+\.\s*/g).slice(1);
console.log(steps)```

This splits on a number followed by full stop, possibly with whitespace on either end.  Your current pattern seems to attempt to target a single digit only appearing at the start of the string, and there are other problems as well.

Slight edit: Call slice(1) on the array returned from the split, to remove a dummy empty string element resulting from the split on the first number.

Title: String to array based on regex

Body:
I would like to split a string base on regex.

Expected input:

1. recipe description. 2. second step of the description that takes 30 minutes. 3. third step of the description that contain 20g of flour.

Now like to split the string based on the starting number. Is that possible?

Expected outcome:

[
"recipe description.",
"second step of the description that takes 30 minutes.",
"third step of the description that contain 20g of flour."
]

I already tried it with const steps = text.split(new RegExp("/^d./", "g")); but its not the expected outcome i would like to have.

Body:
Try the following:

var text = "1. recipe description. 2. second step of the description that takes 30 minutes. 3. third step of the description that contain 20g of flour.";
var steps = text.split(/\s*\d+\.\s*/g).slice(1);
console.log(steps)

This splits on a number followed by full stop, possibly with whitespace on either end.  Your current pattern seems to attempt to target a single digit only appearing at the start of the string, and there are other problems as well.

Slight edit: Call slice(1) on the array returned from the split, to remove a dummy empty string element resulting from the split on the first number.


问:
Do I need Nginx with Gunicorn if I am not serving any static content?
In a typical python server setup it is recommended to have Nginx web server serve the static content and proxy the dynamic requests to  Gunicorn app server.
Now if I am not serving any static content through my python application do I still need Nginx in front of Gunicorn ? What would be the advantages ?
Detailed explanation would be really appreciated.

All the static content is served through CDN and the backend server will only need to serve the APIs(REST). So when I will only server dynamic content, will I need to have Nginx ? Does it have any advantage in case of high load etc.

答: No, I no longer deploy nginx specifically for the python app. I may have an application load balancer / nginx in the path to split requests to other apps, but not for load management. If using asyncio based systems, I typically don't even use an app server (uwsgi/gunicorn). This is including apps with very high throughput. Every layer of reverse-proxy / layer-7 load balancing will add a touch of latency- don't add it if you don't need it.</p>


问:
How would you structure mutual rating social network model on Firestore?
I think it would be easier to display my model with an example. The functionality of the app would be the following: It would be social network schema. A mutual friend model. When a user logins in the app, a list will be displayed. Each list item consist of a friend name - photos(photo1, photo2) - rating for each photo(calculated based on both ratings).

Example:

Logged in as UserA:

```<code>list item1:
[
 name: UserBName,
 photo1: 5 (UserA rated it 2, UserB rated it 8),
 photo2: 4 (UserA rated it 3, UserB rated it 5)
],
list item2:
[
 name: UserCName,
 photo1: 2 (UserA rated it 1, UserC rated it 4)
]
</code>```

I was thinking of creating a friend subcollection for each user document and inside having a structure like that:

```<code>UserB: {
     name: UserBName,
     photo1:{
      rating from UserA: 4
      rating from UserB: 2
     },
     photo2:{
      rating from UserA: 3
      rating from UserB: 5
     }
    }
</code>```

My issue is that UserB(document)->friends(subcollection)->UserA(document) would have the same data and i am not so sure if its a viable solution.

答:
Duplicating data and denormalizing data is common practice in NoSQL databases. It's used to flatten structures so queries can be run against the data. In the question we don't know what kind of queries you want to run other than

When a user logins in the app, a list will be displayed. Each list
  item consist of a friend name - photos(photo1, photo2) - rating for
  each photo(calculated based on both ratings).

Which doesn't require a query. Using the structure in the question, when UserB logs in, your app will read the UserB document which will contain their name and all of their photo's and ratings so all of that data will be available as soon as the document is read.

However...

If each user has LOTS of photos's that could be a LOT of data to be read in and could overwhelm the device. Additionally, if you are really trying to avoid duplicating data, then you need to put the data in one place.

I would change the structure completely to provide more flexibility in only reading in the data you want.

First a simpler user collection: the documentId's are the users uid and then store their name etc as field within each document

```<code>users
   uid_0:
      name:
   uid_1:
      name:
</code>```

Then a photos collection that stores the ratings

```<code>firestore_root
   photos
      photo_0
         uid_0: 4
         uid_1: 2
      photo_1
         uid_3: 2
         uid_2: 5
      photo_2
         uid_0: 3
         uid_1: 1
</code>```

So then when a user logs in, perform a query on the photo's node for all photos that contain a users uid with a rating > -1  (assuming ratings go from 0 to 5 for example). In this case that would be photo_0 and photo_2

in pseudo-code, to get all of the nodes that uid_1 has rated

```<code>queryPhotos() {
    photoCollection.whereField("uid_1", isGreaterThan: -1).getDocuments() { querySnapshot, error in
        //the snapshot will contain photo_0 and photo_2
        for doc in querySnapshot.documents { //iterate over each photo
            //you'll have all of the fields here and can calculate an average rating
            print(doc.documentID, doc.data())
        }
    }
}
</code>```

Body:
I think it would be easier to display my model with an example. The functionality of the app would be the following: It would be social network schema. A mutual friend model. When a user logins in the app, a list will be displayed. Each list item consist of a friend name - photos(photo1, photo2) - rating for each photo(calculated based on both ratings).

Example:

Logged in as UserA:

list item1:
[
 name: UserBName,
 photo1: 5 (UserA rated it 2, UserB rated it 8),
 photo2: 4 (UserA rated it 3, UserB rated it 5)
],
list item2:
[
 name: UserCName,
 photo1: 2 (UserA rated it 1, UserC rated it 4)
]

I was thinking of creating a friend subcollection for each user document and inside having a structure like that:

UserB: {
     name: UserBName,
     photo1:{
      rating from UserA: 4
      rating from UserB: 2
     },
     photo2:{
      rating from UserA: 3
      rating from UserB: 5
     }
    }

My issue is that UserB(document)->friends(subcollection)->UserA(document) would have the same data and i am not so sure if its a viable solution.

Body:
Duplicating data and denormalizing data is common practice in NoSQL databases. It's used to flatten structures so queries can be run against the data. In the question we don't know what kind of queries you want to run other than

When a user logins in the app, a list will be displayed. Each list
  item consist of a friend name - photos(photo1, photo2) - rating for
  each photo(calculated based on both ratings).

Which doesn't require a query. Using the structure in the question, when UserB logs in, your app will read the UserB document which will contain their name and all of their photo's and ratings so all of that data will be available as soon as the document is read.

However...

If each user has LOTS of photos's that could be a LOT of data to be read in and could overwhelm the device. Additionally, if you are really trying to avoid duplicating data, then you need to put the data in one place.

I would change the structure completely to provide more flexibility in only reading in the data you want.

First a simpler user collection: the documentId's are the users uid and then store their name etc as field within each document

users
   uid_0:
      name:
   uid_1:
      name:

Then a photos collection that stores the ratings

firestore_root
   photos
      photo_0
         uid_0: 4
         uid_1: 2
      photo_1
         uid_3: 2
         uid_2: 5
      photo_2
         uid_0: 3
         uid_1: 1

So then when a user logs in, perform a query on the photo's node for all photos that contain a users uid with a rating > -1  (assuming ratings go from 0 to 5 for example). In this case that would be photo_0 and photo_2

in pseudo-code, to get all of the nodes that uid_1 has rated

queryPhotos() {
    photoCollection.whereField("uid_1", isGreaterThan: -1).getDocuments() { querySnapshot, error in
        //the snapshot will contain photo_0 and photo_2
        for doc in querySnapshot.documents { //iterate over each photo
            //you'll have all of the fields here and can calculate an average rating
            print(doc.documentID, doc.data())
        }
    }
}


问:
Can the input for "Lasso" in python contain categorical variables?
I want to perform multiple linear regression in python with lasso. I am not sure whether the input observation matrix X can contain categorical variables. I read the instructions from here: lasso in python

But it is simple and not indicate the types allowed for. For example, my code includes:

```<code>model = Lasso(fit_intercept=False, alpha=0.01)
model.fit(X, y)
</code>```

In the code above, X is an observation matrix with size of n-by-p, can one of the p variables be categorical type?

答:
A previous poster has a good answer for this, you need to encode your categorical variables.  The standard way is one hot encoding (or dummy encoding), but there are a many  methods for doing this.

Here is a good library that has many different ways you can encode your categorical variables.  These are also implemented to work with Sci-kit learn.

https://contrib.scikit-learn.org/categorical-encoding/

Body:
I want to perform multiple linear regression in python with lasso. I am not sure whether the input observation matrix X can contain categorical variables. I read the instructions from here: lasso in python

But it is simple and not indicate the types allowed for. For example, my code includes:

model = Lasso(fit_intercept=False, alpha=0.01)
model.fit(X, y)

In the code above, X is an observation matrix with size of n-by-p, can one of the p variables be categorical type?


问:
z3py optimization as variables chosen from a list
For the example, how to write code in z3py to maximize value of a+b+c+d as a,b,c,d are all chosen from list [1,2,3,4,5,6,7,8], which is given as the input. a, b, c, d are distinct values.

```<code>a, b, c, d = Ints("a b c d")
o = Optimize()
list = [1,2,3,4,5,6,7,8]
o.maximize(a+b+c+d)
</code>```

how to write code corresponding to choose "a b c d" value from list. The correct out value of a+b+c+d is 26
Thanks!

答:
Here's one way:

from z3 import *

a, b, c, d = Ints("a b c d")
o = Optimize()

list = [1,2,3,4,5,6,7,8]
vars = [a, b, c, d]

for v in vars:
    o.add(Or([v == e for e in list]))

o.add(Distinct(*vars))

goal = Int("goal")
o.add(goal == a+b+c+d)

o.maximize(goal)
if o.check() == sat:
    print o.model()
else:
    print "not satisfiable"
```

<p>When I run this, I get:</p>

```$ python a.py
[d = 5, c = 8, b = 6, a = 7, goal = 26]
```

Body:
For the example, how to write code in z3py to maximize value of a+b+c+d as a,b,c,d are all chosen from list [1,2,3,4,5,6,7,8], which is given as the input. a, b, c, d are distinct values.

a, b, c, d = Ints("a b c d")
o = Optimize()
list = [1,2,3,4,5,6,7,8]
o.maximize(a+b+c+d)

how to write code corresponding to choose "a b c d" value from list. The correct out value of a+b+c+d is 26
Thanks!

Body:
Here's one way:

from z3 import *

a, b, c, d = Ints("a b c d")
o = Optimize()

list = [1,2,3,4,5,6,7,8]
vars = [a, b, c, d]

for v in vars:
    o.add(Or([v == e for e in list]))

o.add(Distinct(*vars))

goal = Int("goal")
o.add(goal == a+b+c+d)

o.maximize(goal)
if o.check() == sat:
    print o.model()
else:
    print "not satisfiable"

When I run this, I get:

$ python a.py
[d = 5, c = 8, b = 6, a = 7, goal = 26]


问:
Mathematical symbols rendering SVG unviewable
I am trying to display subtraction of 2 numbers with the subtraction symbol − to no success. It works when i simple use - but that is not how a subtraction symbol should look like. I've tried with —, ÷, &multiply; with no success. Is there a way to display these symbols in SVG within the <text> tag?

```<code>echo '<text x="165" y="'.$y_axis.'" font-size="30"
     font-family="Arial, Helvetica, sans-serif"
     fill="rgb(93, 130, 255)">
     −</text>';
</code>```

答: Instead of HTML Entity (named): − it must be in HTML Entity (HEX): −. The same format applies to other symbols.

Body:
I am trying to display subtraction of 2 numbers with the subtraction symbol − to no success. It works when i simple use - but that is not how a subtraction symbol should look like. I've tried with —, ÷, &multiply; with no success. Is there a way to display these symbols in SVG within the <text> tag?

echo '<text x="165" y="'.$y_axis.'" font-size="30"
     font-family="Arial, Helvetica, sans-serif"
     fill="rgb(93, 130, 255)">
     −</text>';

Body: Instead of HTML Entity (named): &minus; it must be in HTML Entity (HEX): &#x2212;. The same format applies to other symbols.


问:
Trouble mocking `Resolv::DNS.open`
I'm trying to mock the code below using MiniTest/Mocks. But I keep getting this error when running my test.

```<code>Minitest::Assertion: unexpected invocation: #<Mock:0x7fa76b53d5d0>.size()
unsatisfied expectations:
- expected exactly once, not yet invoked: #<Mock:0x7fa76b53d5d0>.getresources("_F5DC2A7B3840CF8DD20E021B6C4E5FE0.corwin.co", Resolv::DNS::Resource::IN::CNAME)
satisfied expectations:
- expected exactly once, invoked once: Resolv::DNS.open(any_parameters)
</code>```

code being tested

```<code>txt = Resolv::DNS.open do |dns|
            records = dns.getresources(options[:cname_origin], Resolv::DNS::Resource::IN::CNAME)
          end
          binding.pry
          return (txt.size > 0) ? (options[:cname_destination].downcase == txt.last.name.to_s.downcase) : false
</code>```

my test

```<code>::Resolv::DNS.expects(:open).returns(dns = mock)
  dns.expects(:getresources)
     .with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
     .returns([Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)])
     .once
</code>```

答:
Right now you are testing that Resolv::DNS receives open returns your mock but
since you seem to be trying to test that the dns mock is receiving messages you need to stub the method and provide it with the object to be yielded

Try this instead:

```<code> dns = mock
 dns.expects(:getresources)
   .with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
   .once
 ::Resolv::DNS.stub :open, [Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)], dns do
   # whatever code actually calls the "code being tested"
 end
 dns.verify
</code>```

The second argument to stub is the stubbed return value and third argument to stub is what will be yielded to the block in place of the original yielded.

In RSpec the syntax is a bit simpler (and more semantic) such that:

```<code> dns = double
 allow(::Resolv::DNS).to receive(:open).and_yield(dns)
 expect(:dns).to receive(:getresources).once
   .with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
   .and_return([Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)])
  # whatever code actually calls the "code being tested"
</code>```

Title: Trouble mocking `Resolv::DNS.open`

Body:
I'm trying to mock the code below using MiniTest/Mocks. But I keep getting this error when running my test.

Minitest::Assertion: unexpected invocation: #<Mock:0x7fa76b53d5d0>.size()
unsatisfied expectations:
- expected exactly once, not yet invoked: #<Mock:0x7fa76b53d5d0>.getresources("_F5DC2A7B3840CF8DD20E021B6C4E5FE0.corwin.co", Resolv::DNS::Resource::IN::CNAME)
satisfied expectations:
- expected exactly once, invoked once: Resolv::DNS.open(any_parameters)

code being tested

txt = Resolv::DNS.open do |dns|
            records = dns.getresources(options[:cname_origin], Resolv::DNS::Resource::IN::CNAME)
          end
          binding.pry
          return (txt.size > 0) ? (options[:cname_destination].downcase == txt.last.name.to_s.downcase) : false

my test

::Resolv::DNS.expects(:open).returns(dns = mock)
  dns.expects(:getresources)
     .with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
     .returns([Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)])
     .once

Body:
Right now you are testing that Resolv::DNS receives open returns your mock but
since you seem to be trying to test that the dns mock is receiving messages you need to stub the method and provide it with the object to be yielded

Try this instead:

 dns = mock
 dns.expects(:getresources)
   .with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
   .once
 ::Resolv::DNS.stub :open, [Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)], dns do
   # whatever code actually calls the "code being tested"
 end
 dns.verify

The second argument to stub is the stubbed return value and third argument to stub is what will be yielded to the block in place of the original yielded.

In RSpec the syntax is a bit simpler (and more semantic) such that:

 dns = double
 allow(::Resolv::DNS).to receive(:open).and_yield(dns)
 expect(:dns).to receive(:getresources).once
   .with(subject.cname_origin(true), Resolv::DNS::Resource::IN::CNAME)
   .and_return([Resolv::DNS::Resource::IN::CNAME.new(subject.cname_destination)])
  # whatever code actually calls the "code being tested"


问:
CheckBox to Highlight Range Google Sheets Formula/ Google Sheets

I am trying to get the result in the image attached. If I check a checkBox in Column A, I want it to also to highlight the same SKU & Location Column H,I(in Bright Green). Conditional formatting or if script could do this?

答:
try:

```<code>=REGEXMATCH($H2&$I2, TEXTJOIN("|", 1, FILTER($B$2:$B&$C$2:$C, $A$2:$A=TRUE)))
</code>```

UPDATE:

```<code>=REGEXMATCH($H2, TEXTJOIN("|", 1, FILTER($B$2:$B, $A$2:$A=TRUE)))
</code>```

Body:
try:

=REGEXMATCH($H2&$I2, TEXTJOIN("|", 1, FILTER($B$2:$B&$C$2:$C, $A$2:$A=TRUE)))

UPDATE:

=REGEXMATCH($H2, TEXTJOIN("|", 1, FILTER($B$2:$B, $A$2:$A=TRUE)))


问:
populating array without calloc and malloc in c?
I have code that looks like

```<code>int main(int argc, char *argv[]){
char ***matrix;
matrix = calloc(2, sizeof(char **));
for (int i=0; i<2; i++){
    matrix[i] = calloc(ROWS+2, sizeof(char*));
    for (int j=0; j<COLS; j++){
        matrix[i][j] = malloc(COLS+2);
        memset(matrix[i][j], (int)DEFAULT, COLS+2);
    }
}
</code>```

Is there a way to do a similar kind of thing without the use of malloc and calloc? For example, in the case of 1d array I know you can do something like this

```<code>unsigned char malloc_data[MAX_SIZE];
size_t malloc_used;  /* automatically initialized to zero */

void *stack_malloc(size_t size) {
void *p = &malloc_data[malloc_used];
if(size + malloc_used > MAX_SIZE) return 0;  /* out of memory */
malloc_used += size;
return p;
}
</code>```

OR something like this

```<code>static char *allocp = allocbuf[0];
if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */
</code>```

and

```<code>if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
</code>```

I want to try to use stack variables and temps instead of dynamic memory allocated ways. However, when I try to think about how to apply these types of ways to my three dimensional sense, my head starts spinning. Please help clarify things to me

答:
Assuming you want to keep the triple pointer usage, the storage can be allocated on the stack and initialized like this:

```<code>char ***matrix;
char **mats_[2];
char *mat_rows_[2][ROWS+2];
char mat_cols_[2][ROWS+2][COLS+2];
matrix = &mats_[0];
for (int i = 0; i < 2; i++) {
    matrix[i] = &mat_rows_[i][0];
    for (int j = 0; j < ROWS+2; j++) {
        matrix[i][j] = &mat_cols_[i][j][0];
        memset(matrix[i][j], (int)DEFAULT, COLS+2);
    }
}
</code>```

You could also define matrix as an array[2] of char ** instead of a single char ***, which would allow you to eliminate the mats_ variable:

```<code>char **matrix[2];
char *mat_rows_[2][ROWS+2];
char mat_cols_[2][ROWS+2][COLS+2];
for (int i = 0; i < 2; i++) {
    ...
</code>```

In the comments below, OP asked whether the memset was necessary. All the elements of mat_cols_[2][ROWS+2][COLS+2] need to be set to the same value DEFAULT. If DEFAULT can be replaced with 0, this is easy to do by defining mat_cols_ with an initializer with pretty much everything defaulting to 0:

```<code>char mat_cols_[2][ROWS+2][COLS+2] = { 0 };
</code>```

If DEFAULT cannot be replaced with 0, the only way to do it would be for the initializer to supply values for all the elements explicitly, which has a maintainability problem since the dimensions are defined in terms of the macros ROWS and COLS. The GNU C Compiler (GCC) has an extension to the C language designated initializers that allows a range of array elements to be initialized to the same value.  That could be used as follows:

```<code>char mat_cols_[2][ROWS+2][COLS+2] =
    {[0 ... 1] =
        {[0 ... ROWS+2-1] =
            {[0 ... COLS+2-1] = DEFAULT}
        }
    };
</code>```

Body:
I have code that looks like

int main(int argc, char *argv[]){
char ***matrix;
matrix = calloc(2, sizeof(char **));
for (int i=0; i<2; i++){
    matrix[i] = calloc(ROWS+2, sizeof(char*));
    for (int j=0; j<COLS; j++){
        matrix[i][j] = malloc(COLS+2);
        memset(matrix[i][j], (int)DEFAULT, COLS+2);
    }
}

Is there a way to do a similar kind of thing without the use of malloc and calloc? For example, in the case of 1d array I know you can do something like this

unsigned char malloc_data[MAX_SIZE];
size_t malloc_used;  /* automatically initialized to zero */

void *stack_malloc(size_t size) {
void *p = &malloc_data[malloc_used];
if(size + malloc_used > MAX_SIZE) return 0;  /* out of memory */
malloc_used += size;
return p;
}

OR something like this

static char *allocp = allocbuf[0];
if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */

and

if (p >= allocbuf && p < allocbuf + ALLOCSIZE)

I want to try to use stack variables and temps instead of dynamic memory allocated ways. However, when I try to think about how to apply these types of ways to my three dimensional sense, my head starts spinning. Please help clarify things to me

Body:
Assuming you want to keep the triple pointer usage, the storage can be allocated on the stack and initialized like this:

char ***matrix;
char **mats_[2];
char *mat_rows_[2][ROWS+2];
char mat_cols_[2][ROWS+2][COLS+2];
matrix = &mats_[0];
for (int i = 0; i < 2; i++) {
    matrix[i] = &mat_rows_[i][0];
    for (int j = 0; j < ROWS+2; j++) {
        matrix[i][j] = &mat_cols_[i][j][0];
        memset(matrix[i][j], (int)DEFAULT, COLS+2);
    }
}

You could also define matrix as an array[2] of char ** instead of a single char ***, which would allow you to eliminate the mats_ variable:

char **matrix[2];
char *mat_rows_[2][ROWS+2];
char mat_cols_[2][ROWS+2][COLS+2];
for (int i = 0; i < 2; i++) {
    ...

In the comments below, OP asked whether the memset was necessary. All the elements of mat_cols_[2][ROWS+2][COLS+2] need to be set to the same value DEFAULT. If DEFAULT can be replaced with 0, this is easy to do by defining mat_cols_ with an initializer with pretty much everything defaulting to 0:

char mat_cols_[2][ROWS+2][COLS+2] = { 0 };

If DEFAULT cannot be replaced with 0, the only way to do it would be for the initializer to supply values for all the elements explicitly, which has a maintainability problem since the dimensions are defined in terms of the macros ROWS and COLS. The GNU C Compiler (GCC) has an extension to the C language designated initializers that allows a range of array elements to be initialized to the same value.  That could be used as follows:

char mat_cols_[2][ROWS+2][COLS+2] =
    {[0 ... 1] =
        {[0 ... ROWS+2-1] =
            {[0 ... COLS+2-1] = DEFAULT}
        }
    };


问:
Alarm Manager events not fired (registering for notifications per day)
I am writing an application which needs a homewidget showing the current date. For that I have used the alarm manager registering as follows:-

```<code>Intent intent = new Intent(HomeScreenWidgetProvider.ACTION_UPDATE_DATE);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetId);
    intent.setData(getUriData(appWidgetId));
    PendingIntent datePendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarms = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarms.cancel(datePendingIntent);
    **alarms.setRepeating(AlarmManager.RTC, getTimeForMidnight(), AlarmManager.INTERVAL_DAY, datePendingIntent);**
</code>```

As you see, the above code registers for notifications first for the next 12.00AM with an interval of a day from there on. I update the date in my widget when I get a notification from alarm manager.

There is one big problem though. I don't get the alarm manager events when the date changes (at 12.00AM). And so the date does not change in my home screen widget.

The above code works fine in the emulator but not on the device. I am using Samsung Galaxy S 19000 for (real time) testing.

Is there a problem with use of alarm manager? Or is there an alternate way of receiving date change notifications?

答:
I think in setRepeating() method, you should set the first parameter as AlarmManager.RTC_WAKEUP. If you use AlarmManager.RTC, the alarm event won't be triggered when the device is asleep. Please see the SDK document about AlarmManager for more details.

Also, you can register a BroadcastReciever listening to ACTION_DATE_CHANGED, by which you can receive date change event.
Hope it helps.

Body:
I am writing an application which needs a homewidget showing the current date. For that I have used the alarm manager registering as follows:-

Intent intent = new Intent(HomeScreenWidgetProvider.ACTION_UPDATE_DATE);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetId);
    intent.setData(getUriData(appWidgetId));
    PendingIntent datePendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarms = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarms.cancel(datePendingIntent);
    **alarms.setRepeating(AlarmManager.RTC, getTimeForMidnight(), AlarmManager.INTERVAL_DAY, datePendingIntent);**

As you see, the above code registers for notifications first for the next 12.00AM with an interval of a day from there on. I update the date in my widget when I get a notification from alarm manager.

There is one big problem though. I don't get the alarm manager events when the date changes (at 12.00AM). And so the date does not change in my home screen widget.

The above code works fine in the emulator but not on the device. I am using Samsung Galaxy S 19000 for (real time) testing.

Is there a problem with use of alarm manager? Or is there an alternate way of receiving date change notifications?