问:
Replace for loop with if statements by vectorised function in R
I'm having some trouble with a for loop that contains to many conditions and runs for ages (due to the size of the data frame). Hence, I would like to replace it with a vectorised function of the apply family. I have a variable of the format month/year and would like to define a year variable, depending on whether the month is smaller or equal to 10 (October), which would be defined as the very year, or larger than 10, which would be the year + 1 (e.g. 09/2001 = 2001, whereas 12/2001 = 2002). The date variable contains some NAs. Below I give a simplified version of my data frame, including the for-loop that I applied. Any hint for a vectorised function would be appreciated.

Example dataset:

```<code>d <- data.frame("10/2010")
names(d) <- "data"
d$data <- as.character(d$data)
d <- rbind(d, "11/2010","12/2009","08/2008", NA)
</code>```

For-loop:

```<code>d$ano <- NA
for(i in 1:length(d$data)){
  month <- as.numeric(substring(d$data[i],1,2))
  if(!is.na(d$data[i]) & month <=10){
    d$ano[i] <- substring(d$data[i],4,7)
  }
  if(!is.na(d$data[i]) & month >10){
      d$ano[i] <- as.numeric(substring(d$data[i],4,7))+1
  }
}
</code>```

答:
You can do this e.g. with ifelse:

```<code>d$ano <- as.numeric(substring(d$data,4,7)) + ifelse(as.numeric(substring(d$data,1,2)) <= 10, 0, 1)
</code>```

or using the fact that TRUE is 1 and FALSE is 0 as in the comment from Andrew Gustar:

```<code>d$ano <- as.numeric(substring(d$data,4,7)) + (as.numeric(substring(d$data,1,2)) > 10)
</code>```

Body:
I'm having some trouble with a for loop that contains to many conditions and runs for ages (due to the size of the data frame). Hence, I would like to replace it with a vectorised function of the apply family. I have a variable of the format month/year and would like to define a year variable, depending on whether the month is smaller or equal to 10 (October), which would be defined as the very year, or larger than 10, which would be the year + 1 (e.g. 09/2001 = 2001, whereas 12/2001 = 2002). The date variable contains some NAs. Below I give a simplified version of my data frame, including the for-loop that I applied. Any hint for a vectorised function would be appreciated.

Example dataset:

d <- data.frame("10/2010")
names(d) <- "data"
d$data <- as.character(d$data)
d <- rbind(d, "11/2010","12/2009","08/2008", NA)

For-loop:

d$ano <- NA
for(i in 1:length(d$data)){
  month <- as.numeric(substring(d$data[i],1,2))
  if(!is.na(d$data[i]) & month <=10){
    d$ano[i] <- substring(d$data[i],4,7)
  }
  if(!is.na(d$data[i]) & month >10){
      d$ano[i] <- as.numeric(substring(d$data[i],4,7))+1
  }
}

Body:
You can do this e.g. with ifelse:

d$ano <- as.numeric(substring(d$data,4,7)) + ifelse(as.numeric(substring(d$data,1,2)) <= 10, 0, 1)

or using the fact that TRUE is 1 and FALSE is 0 as in the comment from Andrew Gustar:

d$ano <- as.numeric(substring(d$data,4,7)) + (as.numeric(substring(d$data,1,2)) > 10)


来源: stackexchange

问:
Select default option value from typescript angular 6
I have a select html like this:

```<code><select ng-model='nrSelect' class='form-control'>
    <option value='47'>47</option>
    <option value='46'>46</option>
    <option value='45'>45</option>
</select>
</code>```

How can I select the default value from typescript for example 47 ?

答:
I think the best way to do it to bind it with ngModel. </p>

```<code><select name="num" [(ngModel)]="number">
                <option *ngFor="let n of numbers" [value]="n">{{n}}</option>
              </select>
</code>```

<p>and in ts file add </p>

```<code>number=47;
numbers=[45,46,47]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a select html like this:

<select ng-model='nrSelect' class='form-control'>
    <option value='47'>47</option>
    <option value='46'>46</option>
    <option value='45'>45</option>
</select>

How can I select the default value from typescript for example 47 ?

Body:
I think the best way to do it to bind it with ngModel.

<select name="num" [(ngModel)]="number">
                <option *ngFor="let n of numbers" [value]="n">{{n}}</option>
              </select>

and in ts file add

number=47;
numbers=[45,46,47]


问:
How to set all columns not null while creating table
I'm trying to create table which should have not null constraint for all of columns.

Is there any way to set all of columns not null instead of placing it in front of each column's name?

答:
Is there any way to set all of columns not null instead of placing it in front of each column's name?

No, sorry to say.


问:
Data from jQuery callback is failing to compare
I'm trying to make a "sign in status" thing.

Here is a summary of what is happening.

User fills our field and jQuery request is sent.
Credentials are validated.
Screen displays a welcome message.

So I can get the welcome message sent back to me if the credentials are valid (or error if credentials are false), but here is where the issue resides...

I am having a really difficult time storing anything in PHP as a global variable using my only jQuery (no included file) approach... So my workaround was to take the passed message (Let's just say when credentials are valid, I pass back something like "X" or "1"), and then when the data comes back in the jQuery, I put an if statement in the callback, but it isn't working.

I know that the data being passed is matching what is being compared, and i've tested many different things to pass back, but the comparison is not being done.

Perhaps it isn't possible to do things like if statements in a jQuery callback, but also maybe I'm doing something wrong.

HTML:

```<code><label>Sign In</label>
<br>
<label>Username</label>
<input type="text" id="name1">
 <label>Password</label>
<input type="text" id="pass1">
<br>
<button type="submit" id="button2">Sign In</button>
<div id = "xx1">Status: Offline</div>
   <div id = "xx2"></div>
</code>```

jQuery:

```<code>$(document).ready(function(){
        $("#button2").click(function(){
            var name1=$("#name1").val();
            var pass1=$("#pass1").val();
            var key = "signIn";
            $.ajax({
                url:'rpc.php',
                method:'POST',
                data:{
                    name1:name1,
                    pass1:pass1,
                    key:key

                },
               success:function(data){
                   if(data === '1')
                   {
                      document.getElementById('xx1').innerHTML = "Status: Online";
                   }
                   document.getElementById('xx2').innerHTML = data;
                   //var p = data;

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

(xx2 is updating by the way)

Lastly, relevant bits of my rpc.php:

```<code>else if($_POST['key'] === "signIn")
{
$name1=$_POST['name1'];
$pass1 = $_POST['pass1'];

if($name1 !== "" && $pass1 !== "")
{

    $sql = "SELECT * FROM whatever";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
    if($name1 === $row["username"])
    {
        $UNTrue = true;
        if (password_verify($pass1, $row['password'])) {
            $PassTrue = true;
        }

    }

}
} else {
//echo "0 results";
}

if($UNTrue === true && $PassTrue === true)
{
    echo "1";

$conn->close();
}
else
{

    echo "<p  align=center style = 'color:#ba261b'>(Incorrect Username or Password) </p>";

    $conn->close();
}

}
else
{

   echo "<p  align=center style = 'color:#ba261b'>(Please Fill Required Fields) </p>";

$conn->close();
}
}
</code>```

So data is "1" in this scenario, as displayed to my via xx2, and xx1 remains as "Status: Offline".

I'm wondering if I have to store the data in a JavaScript variable first, and then later somehow referencing it again ASAP.

The other option would be to figure out how to use PHP global variables without file inclusion.

答: Is it possible even though you're echoing "1", it's getting interpreted as a number? Assuming the data response you get in the success callback is literally just what your PHP script echoes, that's the first thing that jumps out to me, since (1 === "1") is false.

Body:
I'm trying to make a "sign in status" thing.

Here is a summary of what is happening.

User fills our field and jQuery request is sent.
Credentials are validated.
Screen displays a welcome message.

So I can get the welcome message sent back to me if the credentials are valid (or error if credentials are false), but here is where the issue resides...

I am having a really difficult time storing anything in PHP as a global variable using my only jQuery (no included file) approach... So my workaround was to take the passed message (Let's just say when credentials are valid, I pass back something like "X" or "1"), and then when the data comes back in the jQuery, I put an if statement in the callback, but it isn't working.

I know that the data being passed is matching what is being compared, and i've tested many different things to pass back, but the comparison is not being done.

Perhaps it isn't possible to do things like if statements in a jQuery callback, but also maybe I'm doing something wrong.

HTML:

Sign In

Username
<input type="text" id="name1">
 Password
<input type="text" id="pass1">

<button type="submit" id="button2">Sign In</button>

Status: Offline

jQuery:

$(document).ready(function(){
        $("#button2").click(function(){
            var name1=$("#name1").val();
            var pass1=$("#pass1").val();
            var key = "signIn";
            $.ajax({
                url:'rpc.php',
                method:'POST',
                data:{
                    name1:name1,
                    pass1:pass1,
                    key:key

                },
               success:function(data){
                   if(data === '1')
                   {
                      document.getElementById('xx1').innerHTML = "Status: Online";
                   }
                   document.getElementById('xx2').innerHTML = data;
                   //var p = data;

               }
            });
        });
    });

(xx2 is updating by the way)

Lastly, relevant bits of my rpc.php:

else if($_POST['key'] === "signIn")
{
$name1=$_POST['name1'];
$pass1 = $_POST['pass1'];

if($name1 !== "" && $pass1 !== "")
{

    $sql = "SELECT * FROM whatever";
$result = $conn->query($sql);

if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
    if($name1 === $row["username"])
    {
        $UNTrue = true;
        if (password_verify($pass1, $row['password'])) {
            $PassTrue = true;
        }

    }

}
} else {
//echo "0 results";
}

if($UNTrue === true && $PassTrue === true)
{
    echo "1";

$conn->close();
}
else
{

    echo "
(Incorrect Username or Password)
";

    $conn->close();
}

}
else
{

   echo "
(Please Fill Required Fields)
";

$conn->close();
}
}

So data is "1" in this scenario, as displayed to my via xx2, and xx1 remains as "Status: Offline".

I'm wondering if I have to store the data in a JavaScript variable first, and then later somehow referencing it again ASAP.

The other option would be to figure out how to use PHP global variables without file inclusion.


问:
How do I stop a user from incresing the height of TextBox
I have an <asp:TextBox TextMode="MultiLine" Height=350 Width="200"> and have elements around it.

I don't want to allow the user to change the height and width of the asp:TextBox because it messes with the alignment of other elements around it.

Solution?

答:
[Answer added for future reference]

You can use resize: none; in CSS to disable the resize-functionality offered by Firefox/Safari. An example and explanation can be found here.

(thanks to BoltClock)

ContentLicense: CC BY-SA 3.0


问:
How to cut long labels in Matplotlib
I would like to cut long labels, so that only the first 4 letters are displayed, without changing the values in the original data frame.

Example:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text',d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');
```

Current output:

Desirable output:

答:
This is best solved by supplying the data in short form already.

```<code>df2 = d.copy()
df2["var"] = df2["var"].apply(lambda x: x[:4])

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=df2, orient='h');
</code>```

Title: How to cut long labels in Matplotlib

Body:
I would like to cut long labels, so that only the first 4 letters are displayed, without changing the values in the original data frame.

Example:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn

np.random.seed(89)

# Toy Dataset
d = pd.DataFrame(np.random.randint(0,3, size=(100, 1)), columns=['var'])
d['var'] = (np.where(d['var'] == 1,'Long loooooong loooooong text',d['var']))

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=d, orient='h');

Current output:

Desirable output:

Body:
This is best solved by supplying the data in short form already.

df2 = d.copy()
df2["var"] = df2["var"].apply(lambda x: x[:4])

# Plot
f, axes = plt.subplots()
sns.countplot(y='var', data=df2, orient='h');


问:
How to sign in to Apple ID in Xcode via command line?
I inherited a Xcode setup that builds an iOS app that uses Automatic Signing for the development builds. I now have the task to build some CI setup for this project, but without changing the actual Xcode project. This means I can't switch to manual signing for now.

As the project is building fine locally, I didn't expect this to be a big problem, but it turns out Automatic Signing (obviously, in hindsight) needs your Xcode to be signed into the Apple ID (Xcode => Preferences => Accounts) that should be used for automatically creating certificates.

Is there a way to add an Apple ID to Xcode via the command line?

This is what I already did:

I looked around already, but could not find any obvious answers via Google. All the questions and answers here on StackOverflow always mention "Just quickly open Xcode and enter your credentials" which unfortunately does not work on our CI setup.

I found this Jenkins "Xcode Plugin" that lets you import a .developerprofile that you can export from Xcode. But my Java is really rusty and I couldn't fully understand if this "only" imports profiles and identities, or also the list of accounts.

Playing around with an .developerprofile myself, it seems to include the account information (and all the certificates etc.) in a .zip file, so you can extract the files. That also includes a accounts.keychain and accounts.plist, but those are both encrypted with the password - which I don't know how to use to get to the real data to investigate there further.

I also tried to find out where Xcode originally saves the information if you add a new Apple ID: It seems to put the account names and passwords, and some token, into your "login" (com.apple.gs.xcode.auth.com.apple.account.AppleIDAuthentication.token) and "iCloud" keychain (Xcode-AlternateDSID and Xcode-Token). I also couldn't recreate the existing entries in Keychain access manually, as "Access Control" -> "Access group for this item:" was always different when creating an application password manually. Copying the items into a new keychain to be exported also didn't work, as the iCloud keychain doesn't let me copy stuff over to a new one (even after disabling keychain sync in iCloud, so the keychain is named "local items").

答:
First off, I'm not sure that what you are trying to do is a good idea.

Keep in mind that if you are going to set up Xcode to automatically request iOS developer certificates on every build, and that build executes on different machines (say, hosted CI such as Travis or Azure Pipelines), your iOS developer certificate will be revoked and regenerated every time.

A much better option (in my opinion) is to export your iOS development certificates and provisioning profiles via your developer profile, and import the development certificate and provisioning profile in your build environment. Then, if needed, update your Xcode project to use the certificate and profile you've just imported.

I think Fastlane can already do pretty much all that. If you're looking for inspiration, Azure Pipelines has similar functionality. The have a task which installs a provisioning profile, one which installs a certificate and one which builds an Xcode project and allows you to override the certificate and provisioning profiles used when signing your product.

Having said that, the accounts.plist and the accounts.keychain probably contain the information you are looking for. Both files are encrypted using AES encryption.

The key used to encrypt the file is derived from the password using PBKDF2 (Password-Based Key Derivation Function 2), using these parameters:

Hashing function: SHA256

Password: Your password

Salt: The byte representation of your password, using UTF8-encoding

Number of hashing iterations: 33333

Key length: 10

The 'magic numbers' are the default values used by Apple's SecKeyDeriveFromPassword function, as described here and implemented here

Once you have your encryption key, you can decrypt the file. You'll need an initialization vector (IV), which again is the default value used by Apple - a 16-byte array consisting entirely of zeros.

In C, you should be able to use use code like this to generate the encryption key:

CFStringRef password = CFSTR("verysecretstuff");
const char* saltBytes = CFStringGetCStringPtr(password, kCFStringEncodingUTF8);
CFDataRef salt = CFDataCreate(NULL, saltBytes, CFStringGetLength(password));

int keySizeInBits = kSecAES128;
CFNumberRef keySize = CFNumberCreate(NULL, kCFNumberIntType, &keySizeInBits);

int rounds = 33333;
CFNumberRef numberOfRounds = CFNumberCreate(NULL, kCFNumberIntType, &rounds);

CFMutableDictionaryRef parameters = CFDictionaryCreateMutable(NULL, 3, NULL, NULL);
CFDictionaryAddValue(parameters, kSecAttrKeyType, kSecAttrKeyTypeAES);
CFDictionaryAddValue(parameters, kSecAttrKeySizeInBits, keySize);
CFDictionaryAddValue(parameters, kSecAttrPRF, kSecAttrPRFHmacAlgSHA256);
CFDictionaryAddValue(parameters, kSecAttrRounds, numberOfRounds);
CFDictionaryAddValue(parameters, kSecAttrSalt, salt);

CFErrorRef error = NULL;
SecKeyRef key = SecKeyDeriveFromPassword(password, parameters, &error);
```

<p>To decrypt the data, use:</p>

<pre class="lang-c prettyprint-override"><code>const UInt *bytes = NULL; // Encrypted data
CFDataRef data = CFDataCreate(NULL, bytes, length);

CFErrorRef error = NULL;
SecTransformRef transform = SecDecryptTransformCreate(key, &error);
if ( transform == NULL )
{
    CFShow(error);
    CFRelease(error);
}

SecTransformSetAttribute(transform, kSecEncryptionMode, kSecModeCBCKey, &error);
SecTransformSetAttribute(transform, kSecPaddingKey, kSecPaddingPKCS7Key, &error);
SecTransformSetAttribute(transform, kSecTransformInputAttributeName, data, &error);
CFDataRef result = SecTransformExecute(transform, &error);

CFShow(result);

CFRelease(result);
CFRelease(data);
CFRelease(transform);
</code>```

Hope it helps!

Body:
First off, I'm not sure that what you are trying to do is a good idea.

Keep in mind that if you are going to set up Xcode to automatically request iOS developer certificates on every build, and that build executes on different machines (say, hosted CI such as Travis or Azure Pipelines), your iOS developer certificate will be revoked and regenerated every time.

A much better option (in my opinion) is to export your iOS development certificates and provisioning profiles via your developer profile, and import the development certificate and provisioning profile in your build environment. Then, if needed, update your Xcode project to use the certificate and profile you've just imported.

I think Fastlane can already do pretty much all that. If you're looking for inspiration, Azure Pipelines has similar functionality. The have a task which installs a provisioning profile, one which installs a certificate and one which builds an Xcode project and allows you to override the certificate and provisioning profiles used when signing your product.

Having said that, the accounts.plist and the accounts.keychain probably contain the information you are looking for. Both files are encrypted using AES encryption.

The key used to encrypt the file is derived from the password using PBKDF2 (Password-Based Key Derivation Function 2), using these parameters:

Hashing function: SHA256

Password: Your password

Salt: The byte representation of your password, using UTF8-encoding

Number of hashing iterations: 33333

Key length: 10

The 'magic numbers' are the default values used by Apple's SecKeyDeriveFromPassword function, as described here and implemented here

Once you have your encryption key, you can decrypt the file. You'll need an initialization vector (IV), which again is the default value used by Apple - a 16-byte array consisting entirely of zeros.

In C, you should be able to use use code like this to generate the encryption key:

CFStringRef password = CFSTR("verysecretstuff");
const char* saltBytes = CFStringGetCStringPtr(password, kCFStringEncodingUTF8);
CFDataRef salt = CFDataCreate(NULL, saltBytes, CFStringGetLength(password));

int keySizeInBits = kSecAES128;
CFNumberRef keySize = CFNumberCreate(NULL, kCFNumberIntType, &keySizeInBits);

int rounds = 33333;
CFNumberRef numberOfRounds = CFNumberCreate(NULL, kCFNumberIntType, &rounds);

CFMutableDictionaryRef parameters = CFDictionaryCreateMutable(NULL, 3, NULL, NULL);
CFDictionaryAddValue(parameters, kSecAttrKeyType, kSecAttrKeyTypeAES);
CFDictionaryAddValue(parameters, kSecAttrKeySizeInBits, keySize);
CFDictionaryAddValue(parameters, kSecAttrPRF, kSecAttrPRFHmacAlgSHA256);
CFDictionaryAddValue(parameters, kSecAttrRounds, numberOfRounds);
CFDictionaryAddValue(parameters, kSecAttrSalt, salt);

CFErrorRef error = NULL;
SecKeyRef key = SecKeyDeriveFromPassword(password, parameters, &error);

To decrypt the data, use:

const UInt *bytes = NULL; // Encrypted data
CFDataRef data = CFDataCreate(NULL, bytes, length);

CFErrorRef error = NULL;
SecTransformRef transform = SecDecryptTransformCreate(key, &error);
if ( transform == NULL )
{
    CFShow(error);
    CFRelease(error);
}

SecTransformSetAttribute(transform, kSecEncryptionMode, kSecModeCBCKey, &error);
SecTransformSetAttribute(transform, kSecPaddingKey, kSecPaddingPKCS7Key, &error);
SecTransformSetAttribute(transform, kSecTransformInputAttributeName, data, &error);
CFDataRef result = SecTransformExecute(transform, &error);

CFShow(result);

CFRelease(result);
CFRelease(data);
CFRelease(transform);

Hope it helps!


问:
What is different between Contextual Menu Button and Command Button in office ui fabric
Contextual Menu Button and Command Button  looks like same in office ui fabric.what are the differences to use those button individually   ?

Office ui fabric buttons

答: Its mostly a styling difference. Command Buttons are used in our command bar. All buttons can accept menuProps and have a contextual menu. </p>


问:
Spring 5 Java Config Set Default Profile
In my older Spring 4 web-app, I used an applicationContext.xml file, and my default spring profile was as follows;

```<code><beans profile="default">
    <context:property-placeholder location="file:/opt/myapp/myapp-ws.properties" />
</beans>
</code>```

And now I am using Spring 5 Framework, but NOT Spring Boot 2.x, and I want to do this in my Java Config class.

My main configuration class looks like this;

```<code>@Configuration
@ComponentScan(basePackages = "com.tomholmes.myapp")
@EnableWebMvc
public class MyAppConfig
{

}
</code>```

And I have the AppInitializer as follows;

```<code>public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{

    private static final Log logger = LogFactory.getLog(ApplicationInitializer.class);

    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        return new Class[]
        { MyAppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses()
    {
        return new Class[]{};
    }

    @Override
    protected String[] getServletMappings()
    {
        return new String[]
        { "/api/*" };
    }
}
</code>```

I've been doing some research on the Net since there is a lot of information on this, but a lot of it conflates Spring Boot,and I just want a Spring 5 without Spring Boot solution.   I'll keep looking, I am sure this is a simple issue.

Thanks!

答:
I haven't tested this, but a @Configuration class with both @Profile and @PropertySource should work:

```<code>@Configuration
@Profile("default")
@PropertySource("file:/opt/myapp/myapp-ws.properties")
public class MyappWebservicePropertyConfig {
}
</code>```

Body:
In my older Spring 4 web-app, I used an applicationContext.xml file, and my default spring profile was as follows;

<beans profile="default">
    <context:property-placeholder location="file:/opt/myapp/myapp-ws.properties" />
</beans>

And now I am using Spring 5 Framework, but NOT Spring Boot 2.x, and I want to do this in my Java Config class.

My main configuration class looks like this;

@Configuration
@ComponentScan(basePackages = "com.tomholmes.myapp")
@EnableWebMvc
public class MyAppConfig
{

}

And I have the AppInitializer as follows;

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{

    private static final Log logger = LogFactory.getLog(ApplicationInitializer.class);

    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        return new Class[]
        { MyAppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses()
    {
        return new Class[]{};
    }

    @Override
    protected String[] getServletMappings()
    {
        return new String[]
        { "/api/*" };
    }
}

I've been doing some research on the Net since there is a lot of information on this, but a lot of it conflates Spring Boot,and I just want a Spring 5 without Spring Boot solution.   I'll keep looking, I am sure this is a simple issue.

Thanks!

Body:
I haven't tested this, but a @Configuration class with both @Profile and @PropertySource should work:

@Configuration
@Profile("default")
@PropertySource("file:/opt/myapp/myapp-ws.properties")
public class MyappWebservicePropertyConfig {
}


问:
Finding neighbours in a two-dimensional array
Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding to the index in different combinations, like this:

```<code>array[i-1][i]
array[i-1][i-1]
array[i][i-1]
array[i+1][i]
</code>```

... And so on.

答:
Grid (vector 2D or one dimension... not the problem here)

X & Y, coordinate of your element (or just pass your vector element by ref...)

```<code>int neighbour(const Grid & g, const size_t & x, const size_t & y) {
    for (int i = -1; i < 2; ++i)
        for (int j = -1; j < 2; ++j)
            if (x + i >= 0 && x + i < g.row && y + j >= 0 && y + j < g.col)
                //Do some stuff
    return 0;
}
</code>```

OwnerDisplayName: Emil Svansø

Body:
Is there an easy way of finding the neighbours (that is, the eight elements around an element) of an element in a two-dimensional array? Short of just subtracting and adding to the index in different combinations, like this:

array[i-1][i]
array[i-1][i-1]
array[i][i-1]
array[i+1][i]

... And so on.

LastEditorDisplayName: mmyers

Body:
Grid (vector 2D or one dimension... not the problem here)

X & Y, coordinate of your element (or just pass your vector element by ref...)

int neighbour(const Grid & g, const size_t & x, const size_t & y) {
    for (int i = -1; i < 2; ++i)
        for (int j = -1; j < 2; ++j)
            if (x + i >= 0 && x + i < g.row && y + j >= 0 && y + j < g.col)
                //Do some stuff
    return 0;
}


问:
Creating new column in Spark using lit()
I'm quite new to Spark and Python so perhaps this is really obvious to someone more experienced.

I've created one column manually, and want to create another column where all values are 's'. The course I'm taking suggests using the lit() function. However, I cannot for the life of me figure out how. This code gives a this error: "TypeError: 'Column' object is not callable"

```<code>wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word'])
wordsDF.show()
from pyspark.sql.functions import lit, concat
pluralDF = ([(wordsDF.word.lit(),'s',)], ['words', 's'])
pluralDF.show()
</code>```

(I use the the show function to display the result to make sure I've got it right. If I only run line 1 and 2, it shows my list of animals, but line 4 and 5 fail.)

The code given by the tutor as a hint is this (for line 4):

```<code>pluralDF = wordsDF.<FILL IN>
</code>```

Any help is much appreciated. Thanks!

答:
Try the following :

```<code>import pyspark.sql.functions as F

wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word']) \
            .withColumns('words', F.lit('s'))
</code>```

If you want to add the 's' to the end of the strings try :

```<code>import pyspark.sql.functions as F

wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word']) \
            .withColumns('words', F.lit('s')) \
            .withColumns('words', F.concat(F.col('_1'), F.col('words')))
</code>```

Body:
I'm quite new to Spark and Python so perhaps this is really obvious to someone more experienced.

I've created one column manually, and want to create another column where all values are 's'. The course I'm taking suggests using the lit() function. However, I cannot for the life of me figure out how. This code gives a this error: "TypeError: 'Column' object is not callable"

wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word'])
wordsDF.show()
from pyspark.sql.functions import lit, concat
pluralDF = ([(wordsDF.word.lit(),'s',)], ['words', 's'])
pluralDF.show()

(I use the the show function to display the result to make sure I've got it right. If I only run line 1 and 2, it shows my list of animals, but line 4 and 5 fail.)

The code given by the tutor as a hint is this (for line 4):

pluralDF = wordsDF.<FILL IN>

Any help is much appreciated. Thanks!

Body:
Try the following :

import pyspark.sql.functions as F

wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word']) \
            .withColumns('words', F.lit('s'))

If you want to add the 's' to the end of the strings try :

import pyspark.sql.functions as F

wordsDF = sqlContext.createDataFrame([('cat',), ('elephant',), ('rat',), ('rat',), ('cat', )], ['word']) \
            .withColumns('words', F.lit('s')) \
            .withColumns('words', F.concat(F.col('_1'), F.col('words')))


问:
How to select the Google search bar using Javascript
I'm using the Chrome extension "Shortkeys" to write shortcut-executable Javascript code that selects the Google search bar while browsing Google searches. Important: I'm not trying to select Chrome's address bar, but the actual search bar on Google's website. I found the search bar element using "inspect element" and found it was inside a div with class "a4bIc". The first tag of the search bar element is "input". So my code is this:

```<code>var x = document.querySelectorAll("div.a4bIc input")[document.selectedResultId]
</code>```

Except it doesn't select the search bar. What am I missing?

答:
Three suggestions:

Looking at the way the google search HTML is structured it looks like you would be better off using the 'name' property in order to reliably select the search input. The selector you want to use is [name='q']

querySelectorAll returns a NodeList object. If I'm not mistaken then you cannot access a member of a NodeList using an ID (This is in contrast with the very similar HTMLCollection object. Don't worry, if it seems confusing, it's because it is!). For a simple lookup like this I suggest using querySelector which will simply return the first selected node directly.

Depending upon what you want to do with the google search bar it seems you will need to do some kind of combination of .focus() and .click(). In my test just now I was only able to get the dropdown of suggestions to appear by firing focus and then click after.

Putting all three of these together:

```<code>function openGoogleSearchUI(){
  let searchInput = document.querySelector("[name='q']");
  searchInput.focus();
  searchInput.click();
}
</code>```

Naturally you can adapt what you do with the input as you see fit, or just use the document.querySelector line to get the input element directly.

Caveat Emptor: I can only see that this works on the Google search UI that I received just now, in the UK, on desktop Chrome. No guarantees that it will work the same in the future or from a different device, as Google can change the structure of the code as they see fit at any time.

Body:
I'm using the Chrome extension "Shortkeys" to write shortcut-executable Javascript code that selects the Google search bar while browsing Google searches. Important: I'm not trying to select Chrome's address bar, but the actual search bar on Google's website. I found the search bar element using "inspect element" and found it was inside a div with class "a4bIc". The first tag of the search bar element is "input". So my code is this:

var x = document.querySelectorAll("div.a4bIc input")[document.selectedResultId]

Except it doesn't select the search bar. What am I missing?

Body:
Three suggestions:

Looking at the way the google search HTML is structured it looks like you would be better off using the 'name' property in order to reliably select the search input. The selector you want to use is [name='q']

querySelectorAll returns a NodeList object. If I'm not mistaken then you cannot access a member of a NodeList using an ID (This is in contrast with the very similar HTMLCollection object. Don't worry, if it seems confusing, it's because it is!). For a simple lookup like this I suggest using querySelector which will simply return the first selected node directly.

Depending upon what you want to do with the google search bar it seems you will need to do some kind of combination of .focus() and .click(). In my test just now I was only able to get the dropdown of suggestions to appear by firing focus and then click after.

Putting all three of these together:

function openGoogleSearchUI(){
  let searchInput = document.querySelector("[name='q']");
  searchInput.focus();
  searchInput.click();
}

Naturally you can adapt what you do with the input as you see fit, or just use the document.querySelector line to get the input element directly.

Caveat Emptor: I can only see that this works on the Google search UI that I received just now, in the UK, on desktop Chrome. No guarantees that it will work the same in the future or from a different device, as Google can change the structure of the code as they see fit at any time.


问:
TypeScript error: "Type 'number' is not assignable to type '0 | 1 | 2' ". Why am I getting this error?
I am getting a weird TypeScript error.

I have the following example:

```<code>interface Foo {
  prop: 0 | 1 | 2;
}

class Bar implements Foo {
  prop = 1;
}

</code>```

And I am getting the error:

```<code>src/example.ts:6:3 - error TS2416: Property 'prop' in type 'Bar' is not assignable to the same property in base type 'Foo'.
  Type 'number' is not assignable to type '0 | 1 | 2'.

6   prop = 1;
    ~~~~
</code>```

Why does this code give the error?

答:
Edit:

You can now also do the following (readonly, as const) if it fits your use case:

```<code>class Bar implements Foo {
  readonly prop = 1;
}
</code>```

or

```<code>class Bar implements Foo {
    prop = 1 as const;
}
</code>```

====

In your class, 1 is being inferred as the widened number type because it would be strange to infer a mutable identifier to only be able to take that one exact initial value.  In your interface, you're not inferring the type, you're explicitly annotating it (unavoidably).

Try casting prop = 1 as 1 or annotating prop : 1 | 2 | 3 = 1 or make type oneThroughThree = 1 | 2 | 3; and use that alias to annotate both places.  Best yet, use an numerical enum to cover your range of acceptable values and perhaps be more readable.

Body:
I am getting a weird TypeScript error.

I have the following example:

interface Foo {
  prop: 0 | 1 | 2;
}

class Bar implements Foo {
  prop = 1;
}

And I am getting the error:

src/example.ts:6:3 - error TS2416: Property 'prop' in type 'Bar' is not assignable to the same property in base type 'Foo'.
  Type 'number' is not assignable to type '0 | 1 | 2'.

6   prop = 1;
    ~~~~

Why does this code give the error?

Body:
Edit:

You can now also do the following (readonly, as const) if it fits your use case:

class Bar implements Foo {
  readonly prop = 1;
}

or

class Bar implements Foo {
    prop = 1 as const;
}

====

In your class, 1 is being inferred as the widened number type because it would be strange to infer a mutable identifier to only be able to take that one exact initial value.  In your interface, you're not inferring the type, you're explicitly annotating it (unavoidably).

Try casting prop = 1 as 1 or annotating prop : 1 | 2 | 3 = 1 or make type oneThroughThree = 1 | 2 | 3; and use that alias to annotate both places.  Best yet, use an numerical enum to cover your range of acceptable values and perhaps be more readable.


问:
Function parameter type for Mongoose schema, in Typescript?
I am trying to work out what is the right parameter type, for a mongoose document passed as parameter to a function.

Starting with the definition:

```<code>import mongoose, { Schema, Document } from 'mongoose';

export interface IUser extends Document {
  email: string;
  firstName: string;
  lastName: string;
}

const UserSchema: Schema = new Schema({
  email: { type: String, required: true, unique: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true }
});

export default mongoose.model<IUser>('User', UserSchema);
</code>```

Then we have a function that looks like:

```<code>function updateUser(user: IUser) {
  user.firstName = 'something';
  user.lastName = 'somethingElse';
  user.save();
}
</code>```

The issue here is that the Document type doe not have a save() function, so it fails. At the same time I can't specify User, since it throws the error "'User' refers to a value, but is being used as a type here.ts(2749)".

The user parameter is an object of a findOne() operation.

答: We ended up solving this by adding the @types/mongoose module and then the function as presented in the question worked.

Body:
I am trying to work out what is the right parameter type, for a mongoose document passed as parameter to a function.

Starting with the definition:

import mongoose, { Schema, Document } from 'mongoose';

export interface IUser extends Document {
  email: string;
  firstName: string;
  lastName: string;
}

const UserSchema: Schema = new Schema({
  email: { type: String, required: true, unique: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true }
});

export default mongoose.model<IUser>('User', UserSchema);

Then we have a function that looks like:

function updateUser(user: IUser) {
  user.firstName = 'something';
  user.lastName = 'somethingElse';
  user.save();
}

The issue here is that the Document type doe not have a save() function, so it fails. At the same time I can't specify User, since it throws the error "'User' refers to a value, but is being used as a type here.ts(2749)".

The user parameter is an object of a findOne() operation.


问:
List of stored procedure which using another stored procedure
We have almost 2100+ stored procedure in database. we are not able to check each stored procedure to find out whether it is using another stored procedure or not.

Any query to find out same?

Thanks,

Dhruval Shah

答: You could use the free SQL Search tool from Red Gate</p>


问:
How to hide/show HTML table rows at an interval
I am working on HTML tables. Here I have made a table and split into four columns to show up on a display screen, the table is fully dynamic.

Now what I have to do is to show 5 rows at a time on the screen. I am using CSS to do that. What I am doing is creating table in one go and populating the first 5 rows at once; then after 5 seconds that content gets refreshed and I have to show next five rows this will go on until the all the data loads

What I have tried

var tableValue = [{
    "Item Name": "MANCHOW  V SOUP",
    "SellingPrice": 100
  },
  {
    "Item Name": "MANCHOW NV SOUP ",
    "SellingPrice": 125
  },
  {
    "Item Name": "CEASER SALAD V",
    "SellingPrice": 175
  },
  {
    "Item Name": "CEASER SALAD NV",
    "SellingPrice": 230
  },
  {
    "Item Name": "GAMBUS REBOZADAS",
    "SellingPrice": 350
  },
  {
    "Item Name": "PANCO FISH FINGER",
    "SellingPrice": 270
  },
  {
    "Item Name": "MUSHROOM DUPLEX",
    "SellingPrice": 160
  },
  {
    "Item Name": "FRENCH FRIES",
    "SellingPrice": 99
  },
  {
    "Item Name": "HONEY GARLIC PRAWN",
    "SellingPrice": 350
  },
  {
    "Item Name": "CHICKEN MANCHURIAN",
    "SellingPrice": 180
  },
  {
    "Item Name": "MUSHROOM CHILLY",
    "SellingPrice": 120
  },
  {
    "Item Name": "SALT N PEPPER BABY CORN",
    "SellingPrice": 120
  },
  {
    "Item Name": "SOUTHERN STYLE CHICKEN",
    "SellingPrice": 210
  },
  {
    "Item Name": "PANEER NAGGETS",
    "SellingPrice": 210
  },
  {
    "Item Name": "HARA BHARA KEBAB",
    "SellingPrice": 160
  },
  {
    "Item Name": "CHICKEN TIKKA",
    "SellingPrice": 210
  },
  {
    "Item Name": "KALMI KEBAB",
    "SellingPrice": 250
  },
  {
    "Item Name": "PIZZA MARGARITTA",
    "SellingPrice": 200
  },
  {
    "Item Name": "PIZZA VEG FARMHOUSE",
    "SellingPrice": 200
  },
  {
    "Item Name": "BBQ CHICKEN PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "CHICKEN TIKKA PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "PESTO SAUCE",
    "SellingPrice": 175
  },
  {
    "Item Name": "ARABIATA",
    "SellingPrice": 160
  },
  {
    "Item Name": "PINK SAUCE",
    "SellingPrice": 160
  },
  {
    "Item Name": "GARBANZO BEAN SALAD",
    "SellingPrice": 90
  },
  {
    "Item Name": "MASALA PAPAD",
    "SellingPrice": 50
  },
  {
    "Item Name": "PEANUT MASALA",
    "SellingPrice": 60
  },
  {
    "Item Name": "GAJAR KA HALWA",
    "SellingPrice": 90
  },
  {
    "Item Name": "WATERMELON MARTINI",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Kiwi martini",
    "SellingPrice": 281.25
  },
  {
    "Item Name": " Apple gin",
    "SellingPrice": 225
  },
  {
    "Item Name": "Cucumber  cooler ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Martini",
    "SellingPrice": 225
  },
  {
    "Item Name": "Pink lady",
    "SellingPrice": 225
  },
  {
    "Item Name": " Bloody marry",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Cosmopolitan",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Sex on the beach",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Bull frog",
    "SellingPrice": 506.25
  },
  {
    "Item Name": "Long  island iced tea ",
    "SellingPrice": 393.75
  },
  {
    "Item Name": "Pinacolada",
    "SellingPrice": 225
  },
  {
    "Item Name": "Daiquiri",
    "SellingPrice": 225
  },
  {
    "Item Name": "Mojito ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Whisky sour",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Hot toddy",
    "SellingPrice": 225
  },
  {
    "Item Name": "Margarita",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Tequila sunrise",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Red sangria",
    "SellingPrice": 225
  },
  {
    "Item Name": "White sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "Rose sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "By chance special ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Made in heaven",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Strawberry delight",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "DRAGON",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Mangochil ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Cucumber cola",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mojito",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mary",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin pinacolada",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "CORONA",
    "SellingPrice": 438.75
  },
  {
    "Item Name": "CRAFT BEERS",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "BIRA WHITE 330",
    "SellingPrice": 157.5
  },
  {
    "Item Name": "BIRA BLONDE 330",
    "SellingPrice": 135
  },
  {
    "Item Name": "BIRA STRONG 650",
    "SellingPrice": 213.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "TESTING ITEM",
    "SellingPrice": 22
  }
]

myFun();
window.setInterval(showRows, 5000);
showRows();

function myFun() {
  addTable(tableValue);
}

function showRows() {
  $(".hidden:lt(5)").removeClass("hidden"); // this one is to hide previous 5 rows and show next five
}

function addTable(tableValue) {
  var $tbl = $("
", {
      "class": "table"
    }),

    $tb = $("
"),
    $trh = $("
");

  var split = Math.round(tableValue.length / 4);
  for (i = 0; i < split; i++) {
    $tr = $("
", {
      class: "hidden"
    }); //ading class
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {

        $("", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($tr);
      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tbody>tr>td {
  white-space: nowrap;
  border-collapse: collapse;
  font-family: Verdana;
  font-size: 8pt;
  font-weight: bold;
  white-space: nowrap;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden {
  display: none;
}</code>```

<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

```

When I am loading the page it is loading 5 rows which is perfect, but after 5 seconds next five rows are rendering but first five are not hiding.

答:
Your function showRows() only removes class hidden, it won't hide the previous five.
And your selector is based on the element that has hidden class. So, even though if you hid the previous five, it will just show that five items again.
The easy way to fix this is giving each table row an index and hide item based on their index, or rework your selector to select which five you want to display.</p>

Body:
I am working on HTML tables. Here I have made a table and split into four columns to show up on a display screen, the table is fully dynamic.

Now what I have to do is to show 5 rows at a time on the screen. I am using CSS to do that. What I am doing is creating table in one go and populating the first 5 rows at once; then after 5 seconds that content gets refreshed and I have to show next five rows this will go on until the all the data loads

What I have tried

var tableValue = [{
    "Item Name": "MANCHOW  V SOUP",
    "SellingPrice": 100
  },
  {
    "Item Name": "MANCHOW NV SOUP ",
    "SellingPrice": 125
  },
  {
    "Item Name": "CEASER SALAD V",
    "SellingPrice": 175
  },
  {
    "Item Name": "CEASER SALAD NV",
    "SellingPrice": 230
  },
  {
    "Item Name": "GAMBUS REBOZADAS",
    "SellingPrice": 350
  },
  {
    "Item Name": "PANCO FISH FINGER",
    "SellingPrice": 270
  },
  {
    "Item Name": "MUSHROOM DUPLEX",
    "SellingPrice": 160
  },
  {
    "Item Name": "FRENCH FRIES",
    "SellingPrice": 99
  },
  {
    "Item Name": "HONEY GARLIC PRAWN",
    "SellingPrice": 350
  },
  {
    "Item Name": "CHICKEN MANCHURIAN",
    "SellingPrice": 180
  },
  {
    "Item Name": "MUSHROOM CHILLY",
    "SellingPrice": 120
  },
  {
    "Item Name": "SALT N PEPPER BABY CORN",
    "SellingPrice": 120
  },
  {
    "Item Name": "SOUTHERN STYLE CHICKEN",
    "SellingPrice": 210
  },
  {
    "Item Name": "PANEER NAGGETS",
    "SellingPrice": 210
  },
  {
    "Item Name": "HARA BHARA KEBAB",
    "SellingPrice": 160
  },
  {
    "Item Name": "CHICKEN TIKKA",
    "SellingPrice": 210
  },
  {
    "Item Name": "KALMI KEBAB",
    "SellingPrice": 250
  },
  {
    "Item Name": "PIZZA MARGARITTA",
    "SellingPrice": 200
  },
  {
    "Item Name": "PIZZA VEG FARMHOUSE",
    "SellingPrice": 200
  },
  {
    "Item Name": "BBQ CHICKEN PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "CHICKEN TIKKA PIZZA",
    "SellingPrice": 225
  },
  {
    "Item Name": "PESTO SAUCE",
    "SellingPrice": 175
  },
  {
    "Item Name": "ARABIATA",
    "SellingPrice": 160
  },
  {
    "Item Name": "PINK SAUCE",
    "SellingPrice": 160
  },
  {
    "Item Name": "GARBANZO BEAN SALAD",
    "SellingPrice": 90
  },
  {
    "Item Name": "MASALA PAPAD",
    "SellingPrice": 50
  },
  {
    "Item Name": "PEANUT MASALA",
    "SellingPrice": 60
  },
  {
    "Item Name": "GAJAR KA HALWA",
    "SellingPrice": 90
  },
  {
    "Item Name": "WATERMELON MARTINI",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Kiwi martini",
    "SellingPrice": 281.25
  },
  {
    "Item Name": " Apple gin",
    "SellingPrice": 225
  },
  {
    "Item Name": "Cucumber  cooler ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Martini",
    "SellingPrice": 225
  },
  {
    "Item Name": "Pink lady",
    "SellingPrice": 225
  },
  {
    "Item Name": " Bloody marry",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Cosmopolitan",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Sex on the beach",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Bull frog",
    "SellingPrice": 506.25
  },
  {
    "Item Name": "Long  island iced tea ",
    "SellingPrice": 393.75
  },
  {
    "Item Name": "Pinacolada",
    "SellingPrice": 225
  },
  {
    "Item Name": "Daiquiri",
    "SellingPrice": 225
  },
  {
    "Item Name": "Mojito ",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Whisky sour",
    "SellingPrice": 281.25
  },
  {
    "Item Name": "Hot toddy",
    "SellingPrice": 225
  },
  {
    "Item Name": "Margarita",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Tequila sunrise",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "Red sangria",
    "SellingPrice": 225
  },
  {
    "Item Name": "White sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "Rose sangria",
    "SellingPrice": 247.5
  },
  {
    "Item Name": "By chance special ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Made in heaven",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Strawberry delight",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "DRAGON",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Mangochil ",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Cucumber cola",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mojito",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin mary",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "Virgin pinacolada",
    "SellingPrice": 168.75
  },
  {
    "Item Name": "CORONA",
    "SellingPrice": 438.75
  },
  {
    "Item Name": "CRAFT BEERS",
    "SellingPrice": 337.5
  },
  {
    "Item Name": "BIRA WHITE 330",
    "SellingPrice": 157.5
  },
  {
    "Item Name": "BIRA BLONDE 330",
    "SellingPrice": 135
  },
  {
    "Item Name": "BIRA STRONG 650",
    "SellingPrice": 213.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "KINGFISHER PREMIUM 330",
    "SellingPrice": 123.75
  },
  {
    "Item Name": "KINGFISHER PREMIUM 650",
    "SellingPrice": 202.5
  },
  {
    "Item Name": "TESTING ITEM",
    "SellingPrice": 22
  }
]

myFun();
window.setInterval(showRows, 5000);
showRows();

function myFun() {
  addTable(tableValue);
}

function showRows() {
  $(".hidden:lt(5)").removeClass("hidden"); // this one is to hide previous 5 rows and show next five
}

function addTable(tableValue) {
  var $tbl = $("
", {
      "class": "table"
    }),

    $tb = $("
"),
    $trh = $("
");

  var split = Math.round(tableValue.length / 4);
  for (i = 0; i < split; i++) {
    $tr = $("
", {
      class: "hidden"
    }); //ading class
    for (j = 0; j < 4; j++) {
      $.each(tableValue[split * j + i], function(key, value) {

        $("", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($tr);
      });
    }
    $tr.appendTo($tb);
  }
  $tbl.append($tb);
  $("#DisplayTable").html($tbl);
}

tbody>tr>td {
  white-space: nowrap;
  border-collapse: collapse;
  font-family: Verdana;
  font-size: 8pt;
  font-weight: bold;
  white-space: nowrap;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden {
  display: none;
}

<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

When I am loading the page it is loading 5 rows which is perfect, but after 5 seconds next five rows are rendering but first five are not hiding.


问:
after read(signalfd), does it need a call to waitid()?
Does a call to read() on a signalfd conssume the SIGCHLD?
Or does I need to conssume with waitid() call after?

I received readable event on signalfd by a call to epoll_wait(), Then I do a read() on signalfd, that give all informations needed in signalfd_siginfo.
I loop on read() until return -1 and errno=EAGAIN.
But with the shell command ps aux, processes are still here with <defunct>.

If I loop with waitid() I don't have the problem.
Why I need waitid() call after read(signalfd) ?

I can't see this behavior in manpages and I can't find source example on that.

答:
You need to call wait on getting SIGCHLD from signalfd. This is clearly evidenced by your <defunct> output from ps.

If you don't ever care about child process return codes, set SIGCHLD to be handled by SIG_IGN. No more zombies.


问:
How to fix a view from going off of a page when it is constrained to a card view
I have recently converted over an android project into androidx and I am having issues with trying to stop views going off of the page. My layout is as follows, a Constraint Layout that contains a Card View and a Text View. Within this Card View I have a Constraint Layout that contains the Text View. Outside of the Card View I have a Button which is constrained to the Card View.

The issue with this is that when I run the program the Card View goes off of the screen and the button moves all the way to the top even though they are all constrained properly.

I will show below the code I am using to achieve this and an image of my result on the emulator.

Here is the layout in the editor [1]: https://imgur.com/a/0FLa1IK

Here is the layout shown on the Emulator [2]: https://imgur.com/a/SsvKiOG

Any help would be greatly appreciated.

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/materialButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="Text View Test"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

    <Button
        android:id="@+id/materialButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="256dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

</code>```

答:
I'm not so sure about android x but the constraint layouts are used for removing the nested layouts so, you should not be using constraint layout inside card view. Try this code as a reference. It might help.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:id="@+id/cv_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="Text View Test"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

    </android.support.v7.widget.CardView>

    <Button
        android:id="@+id/materialButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="280dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cv_text" />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I have recently converted over an android project into androidx and I am having issues with trying to stop views going off of the page. My layout is as follows, a Constraint Layout that contains a Card View and a Text View. Within this Card View I have a Constraint Layout that contains the Text View. Outside of the Card View I have a Button which is constrained to the Card View.

The issue with this is that when I run the program the Card View goes off of the screen and the button moves all the way to the top even though they are all constrained properly.

I will show below the code I am using to achieve this and an image of my result on the emulator.

Here is the layout in the editor [1]: https://imgur.com/a/0FLa1IK

Here is the layout shown on the Emulator [2]: https://imgur.com/a/SsvKiOG

Any help would be greatly appreciated.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toTopOf="@+id/materialButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="Text View Test"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.cardview.widget.CardView>

    <Button
        android:id="@+id/materialButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="256dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
I'm not so sure about android x but the constraint layouts are used for removing the nested layouts so, you should not be using constraint layout inside card view. Try this code as a reference. It might help.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:id="@+id/cv_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="Text View Test"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

    </android.support.v7.widget.CardView>

    <Button
        android:id="@+id/materialButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="280dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/cv_text" />

</android.support.constraint.ConstraintLayout>


问:
Realloc() discards qualifiers
I am just writing a code that has to reallocate an array X of pointers to constant strings A,B,C (see scheme below):

```<code> _______ _______ _______     ________     ________________
|char* A|char* B|char* C|...|char** X|...|char*** pref_arr|...
 """"""" """"""" """""""     """"""""     """"""""""""""""
     __                             __
    |\______________________/      |\__________/
</code>```

I have the array of A,B,C, pointer to that array X and a pointer pref_arr that points to X.
I had no space in the scheme, but all the chars are qualified as const.

I then have the following code

```<code>function(const char*** pref_arr, int new_length) {
    const char** new_pref_arr = realloc(**pref_arr, sizeof(const char*) * new_length);
    // some other stuff to do...
}
</code>```

where I am trying to reallocate the array X to a length new_length.
The problem is, that my IDE warns me that passing const char* to a void* discards qualifiers.

答:
the problem here is, that you are dereferencing too much, one asterisk is precisely what you want, instead of two. See below:

```<code>function(const char*** pref_arr) {
    const char** new_pref_arr = realloc(*pref_arr, sizeof(const char*) * N);
    // some other stuff to do...
}
</code>```

What were you doing in your code was that you were trying to reallocate the string A (because **pref_arr points precisely there - through double dereferencing), which is probably not what you wanted.

Title: Realloc() discards qualifiers

Body:
I am just writing a code that has to reallocate an array X of pointers to constant strings A,B,C (see scheme below):

 _______ _______ _______     ________     ________________
|char* A|char* B|char* C|...|char** X|...|char*** pref_arr|...
 """"""" """"""" """""""     """"""""     """"""""""""""""
     __                             __
    |\______________________/      |\__________/

I have the array of A,B,C, pointer to that array X and a pointer pref_arr that points to X.
I had no space in the scheme, but all the chars are qualified as const.

I then have the following code

function(const char*** pref_arr, int new_length) {
    const char** new_pref_arr = realloc(**pref_arr, sizeof(const char*) * new_length);
    // some other stuff to do...
}

where I am trying to reallocate the array X to a length new_length.
The problem is, that my IDE warns me that passing const char* to a void* discards qualifiers.

Body:
the problem here is, that you are dereferencing too much, one asterisk is precisely what you want, instead of two. See below:

function(const char*** pref_arr) {
    const char** new_pref_arr = realloc(*pref_arr, sizeof(const char*) * N);
    // some other stuff to do...
}

What were you doing in your code was that you were trying to reallocate the string A (because **pref_arr points precisely there - through double dereferencing), which is probably not what you wanted.


问:
How to create add-on for Mozilla Thunderbird desktop app?
I am beginner to Mozilla Addons Development. I want to create add-on Mozilla Thunderbird desktop app. I researched how to create it but i found only browser extension.

Where should I start?

Thanks. I would be very thankful to you.

答:
The documentation for add-ons development has been updated very recently, you can find it here:

https://developer.thunderbird.net/add-ons/about-add-ons

I'd suggest subscribing to this mailing list and announcing what you do, it's also a useful place to ask add-on development questions and make suggestions about it:

https://mail.mozilla.org/listinfo/tb-planning


问:
How to install ipa file (no jailbreak)
I uploaded this ipa file on the website https://www.diawi.com/
I tried to install on the phone but it respond "Ongame could not be installed at this time."
I tried to sign again but still failed.
Please guide me to edit this ipa file so I can install it on my iphone.
Link file: http://ongame.tk/file/Ongame240.ipa
image http://ongame.tk/file/err.jpg</p>

答: You are not allowed to make any changes with the ipa file, you have to rebuild and create a separate ipa with the updated provisioning profile.</p>

Title: How to install ipa file (no jailbreak)


问:
css or xpath selector: elements which have any attribute with specific value
I want to match all elements in an HTML Dom tree which have any attribute with the value "foo". It should either be a CSS or a XPath selector.

My naive approach would be something like this as css selector:

```<code>*[*='foo']
</code>```

How is the correct syntax?

答:
CSS does not define an attribute selector that takes a wildcard as its name.

XPath, however, does. The following expression should work:

```<code>//*[@*="foo"]
</code>```

Body:
I want to match all elements in an HTML Dom tree which have any attribute with the value "foo". It should either be a CSS or a XPath selector.

My naive approach would be something like this as css selector:

*[*='foo']

How is the correct syntax?

Body:
CSS does not define an attribute selector that takes a wildcard as its name.

XPath, however, does. The following expression should work:

//*[@*="foo"]


问:
how can I make an insert of a select field with sqlalchemy?
I have a form where I have a text field and a selection field and the question I have is how can I insert the bd in the selection field, this field in the table is an external key and what I need is to insert the value of the selection field.
I would greatly appreciate your help.

```<code>@detalle_grupo_estadisticas.route("/show/<id>", methods = ['GET', 'POST'])
def show(id):
    title = 'Grupo estadisticas'
    page = 1
    per_page = 3
    CamposGrupo = forms.Fields_Detalle_Grupo_Estadisticas(request.form)
    grup_list = GrupoEstadisticas.query.all()

    if request.method == 'POST' and CamposGrupo.validate():
        grupo_edit = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
        grupo_edit.nombre = CamposGrupo.Nombre.Data
        grupo_edit.id_grupoEstadisticas = CamposGrupo.GrupoEstadistica.Value
        db.session.add(grupo_edit)
        db.session.commit()
        return  redirect(url_for('detalle_grupo_estadisticas.index'))

    grupo = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
    CamposGrupo.Nombre.data = grupo.nombre
    CamposGrupo.GrupoEstadistica.choices=[(g.id_grupoEstadisticas,g.nombre) for g in grup_list]
    return render_template('/detalle_grupo_estadisticas/show.html', title=title, CamposGrupo = CamposGrupo, grupo = grupo)
</code>```

What I want to insert is the value of the field selection field

these are the models

```<code>class DetalleGrupoEstadisticas(db.Model):
    __tablename__ = 'detalle_grupo_estadisticas'
    id_detalle_grupo_estadisticas = db.Column(db.Integer, primary_key=True)

    nombre = db.Column(db.String(80), nullable=False)
    id_grupoEstadisticas = db.Column(db.Integer, db.ForeignKey('grupo_estadisticas.id_grupoEstadisticas'))

    grupoestadistica = db.relationship('GrupoEstadisticas', back_populates='detallesgrupo', lazy=True)

class GrupoEstadisticas(db.Model):
    __tablename__ = 'grupo_estadisticas'
    id_grupoEstadisticas = db.Column(db.Integer, primary_key=True)

    nombre = db.Column(db.String(80), nullable=False)
    descripcion = db.Column(db.String(200), nullable=False)

    estadisticas= db.relationship('Estadisticas', back_populates='grupoestadisticas', lazy=True)
    detallesgrupo= db.relationship('DetalleGrupoEstadisticas', back_populates='grupoestadistica', lazy=True)
</code>```

答:
This is how I was able to solve the problem.

view

```<code>@detalle_grupo_estadisticas.route("/show/<id>", methods = ['GET', 'POST'])
def show(id):
    title = 'Grupo estadisticas'
    page = 1
    per_page = 3
    CamposGrupo = forms.Fields_Detalle_Grupo_Estadisticas(request.form)
    grup_list = GrupoEstadisticas.query.all()
    if request.method == 'POST' and CamposGrupo.validate():

        grupo_edit = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
        grupo_edit.nombre = CamposGrupo.Nombre.data
        grupo_edit.grupoestadistica = CamposGrupo.GrupoEstadistica.data
        #this is where I had the error that I was inserting in id_grupoStadisticas and it had to be with the variable of the relationship
        db.session.add(grupo_edit)
        db.session.commit()
        return  redirect(url_for('detalle_grupo_estadisticas.index'))

    grupo = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
    CamposGrupo.Nombre.data = grupo.nombre
    CamposGrupo.GrupoEstadistica.choices=[(g.id_grupoEstadisticas,g.nombre) for g in grup_list]
    return render_template('/detalle_grupo_estadisticas/show.html', title=title, CamposGrupo = CamposGrupo, grupo = grupo)
</code>```

form

```<code>class Fields_Detalle_Grupo_Estadisticas(Form):
    Nombre = StringField('Grupo', validators=[InputRequired(), Length(min=2, max=30, message = 'Mayor a 2 caracteres y menor a 30')])
    GrupoEstadistica = QuerySelectField('Grupo Estadistica',query_factory=lambda: GrupoEstadisticas.query,
                                        get_pk=lambda g: g.id_grupoEstadisticas,
                                        get_label=lambda g: g.nombre)
</code>```

Body:
I have a form where I have a text field and a selection field and the question I have is how can I insert the bd in the selection field, this field in the table is an external key and what I need is to insert the value of the selection field.
I would greatly appreciate your help.

@detalle_grupo_estadisticas.route("/show/<id>", methods = ['GET', 'POST'])
def show(id):
    title = 'Grupo estadisticas'
    page = 1
    per_page = 3
    CamposGrupo = forms.Fields_Detalle_Grupo_Estadisticas(request.form)
    grup_list = GrupoEstadisticas.query.all()

    if request.method == 'POST' and CamposGrupo.validate():
        grupo_edit = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
        grupo_edit.nombre = CamposGrupo.Nombre.Data
        grupo_edit.id_grupoEstadisticas = CamposGrupo.GrupoEstadistica.Value
        db.session.add(grupo_edit)
        db.session.commit()
        return  redirect(url_for('detalle_grupo_estadisticas.index'))

    grupo = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
    CamposGrupo.Nombre.data = grupo.nombre
    CamposGrupo.GrupoEstadistica.choices=[(g.id_grupoEstadisticas,g.nombre) for g in grup_list]
    return render_template('/detalle_grupo_estadisticas/show.html', title=title, CamposGrupo = CamposGrupo, grupo = grupo)

What I want to insert is the value of the field selection field

these are the models

class DetalleGrupoEstadisticas(db.Model):
    __tablename__ = 'detalle_grupo_estadisticas'
    id_detalle_grupo_estadisticas = db.Column(db.Integer, primary_key=True)

    nombre = db.Column(db.String(80), nullable=False)
    id_grupoEstadisticas = db.Column(db.Integer, db.ForeignKey('grupo_estadisticas.id_grupoEstadisticas'))

    grupoestadistica = db.relationship('GrupoEstadisticas', back_populates='detallesgrupo', lazy=True)

class GrupoEstadisticas(db.Model):
    __tablename__ = 'grupo_estadisticas'
    id_grupoEstadisticas = db.Column(db.Integer, primary_key=True)

    nombre = db.Column(db.String(80), nullable=False)
    descripcion = db.Column(db.String(200), nullable=False)

    estadisticas= db.relationship('Estadisticas', back_populates='grupoestadisticas', lazy=True)
    detallesgrupo= db.relationship('DetalleGrupoEstadisticas', back_populates='grupoestadistica', lazy=True)

Body:
This is how I was able to solve the problem.

view

@detalle_grupo_estadisticas.route("/show/<id>", methods = ['GET', 'POST'])
def show(id):
    title = 'Grupo estadisticas'
    page = 1
    per_page = 3
    CamposGrupo = forms.Fields_Detalle_Grupo_Estadisticas(request.form)
    grup_list = GrupoEstadisticas.query.all()
    if request.method == 'POST' and CamposGrupo.validate():

        grupo_edit = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
        grupo_edit.nombre = CamposGrupo.Nombre.data
        grupo_edit.grupoestadistica = CamposGrupo.GrupoEstadistica.data
        #this is where I had the error that I was inserting in id_grupoStadisticas and it had to be with the variable of the relationship
        db.session.add(grupo_edit)
        db.session.commit()
        return  redirect(url_for('detalle_grupo_estadisticas.index'))

    grupo = DetalleGrupoEstadisticas.query.filter_by(id_detalle_grupo_estadisticas=id).first()
    CamposGrupo.Nombre.data = grupo.nombre
    CamposGrupo.GrupoEstadistica.choices=[(g.id_grupoEstadisticas,g.nombre) for g in grup_list]
    return render_template('/detalle_grupo_estadisticas/show.html', title=title, CamposGrupo = CamposGrupo, grupo = grupo)

form

class Fields_Detalle_Grupo_Estadisticas(Form):
    Nombre = StringField('Grupo', validators=[InputRequired(), Length(min=2, max=30, message = 'Mayor a 2 caracteres y menor a 30')])
    GrupoEstadistica = QuerySelectField('Grupo Estadistica',query_factory=lambda: GrupoEstadisticas.query,
                                        get_pk=lambda g: g.id_grupoEstadisticas,
                                        get_label=lambda g: g.nombre)


问:
C# List<String> Print Items
very new to c# here and following tutorials on PluralSight.

i have the following files (Classes i think ?)

Program.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customers
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomerList customers = new CustomerList();

            customers.AddCustomer("Apple");
            customers.AddCustomer("Microsoft");
        }
    }
}
</code>```

And CustomerList.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customers
{
    public class CustomerList
    {
        public CustomerList()
        {
            customers = new List<string>();
        }

        public void AddCustomer(string customer)
        {
            customers.Add(customer);
        }

        private List<String> customers;
    }
}
</code>```

The snag i'm hitting is i just want to list out the items within the list and doing so is stumping me. I did try to use a foreach statement as follows.

```<code>      foreach (string customer in customers)
        {
            Console.WriteLine(customer);
        }
</code>```

from within Program.cs but i'm unable to do so as it states

"foreach statement cannot operate on variables of type 'CustomerList' because 'CustomerList' does not contain a public instance definition for 'GetEnumerator'"

However if i keep all my code within Program.cs and use the following i am able to write out each item within list.

```<code>private List<string> customers;

static void Main(string[] args)
{
    customers = new List<String>();
    AddCustomers(customers);

    foreach(string customer in customers) {

         Console.WriteLine(customer);
    }

}

private void AddCustomers(List<string> customers)
    {
        customers.Add("Apple");
        customers.Add("Microsoft");
    }
</code>```

Like i say, very new, so please go easy one me.

答:
You need to begin by examining your CustomList definition and the instance customers. The instance customers, is not a collection and hence cannot be enumerated as the error description says. But rather, it is an instance of CustomerList, which has a property called customer.

The property customer is a collection of Strings and can be enumerated, however, in your case, you have declared it as private.

So, the first change you need to do is to make it public property. Please note I have not made the variable public, but rather made it Public Property. You can learn more on properties here

```<code>public List<String> customers {get;set;}
</code>```

And then, in your foreach you can do as following.

```<code>foreach (string customer in customers.customers)
{
    Console.WriteLine(customer);
}
</code>```

This is however, changes that might be needed to make your existing code working. But, if you were to rewrite the entire code , you have couple of options.

a) Could do away with CustomerList class and use List directly.

```<code>var customers = new List<string>();
customers.Add("Apple");
</code>```

b) Use the CustomerList class but use the public property Customers to add to the list directly

```<code>public class CustomerList
{
    public CustomerList()
    {
        customers = new List<string>();
    }

    public List<String> Customers;
}
</code>```

Client Code

```<code>CustomerList customers = new CustomerList();

customers.Customers.Add("Apple");
customers.Customers.Add("Microsoft");
</code>```

c) The third option is to implement IEnumerable interface, but however, considering the requirement of your code,  and fact that you are still learning C#, I would say it might be an overkill. It would be better to get a firm understanding of Collections and Classes/Properties first, before you actually go ahead with IEnumerable implementation

Title: C# List<String> Print Items

Body:
very new to c# here and following tutorials on PluralSight.

i have the following files (Classes i think ?)

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customers
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomerList customers = new CustomerList();

            customers.AddCustomer("Apple");
            customers.AddCustomer("Microsoft");
        }
    }
}

And CustomerList.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customers
{
    public class CustomerList
    {
        public CustomerList()
        {
            customers = new List<string>();
        }

        public void AddCustomer(string customer)
        {
            customers.Add(customer);
        }

        private List<String> customers;
    }
}

The snag i'm hitting is i just want to list out the items within the list and doing so is stumping me. I did try to use a foreach statement as follows.

      foreach (string customer in customers)
        {
            Console.WriteLine(customer);
        }

from within Program.cs but i'm unable to do so as it states

"foreach statement cannot operate on variables of type 'CustomerList' because 'CustomerList' does not contain a public instance definition for 'GetEnumerator'"

However if i keep all my code within Program.cs and use the following i am able to write out each item within list.

private List<string> customers;

static void Main(string[] args)
{
    customers = new List<String>();
    AddCustomers(customers);

    foreach(string customer in customers) {

         Console.WriteLine(customer);
    }

}

private void AddCustomers(List<string> customers)
    {
        customers.Add("Apple");
        customers.Add("Microsoft");
    }

Like i say, very new, so please go easy one me.

Body:
You need to begin by examining your CustomList definition and the instance customers. The instance customers, is not a collection and hence cannot be enumerated as the error description says. But rather, it is an instance of CustomerList, which has a property called customer.

The property customer is a collection of Strings and can be enumerated, however, in your case, you have declared it as private.

So, the first change you need to do is to make it public property. Please note I have not made the variable public, but rather made it Public Property. You can learn more on properties here

public List<String> customers {get;set;}

And then, in your foreach you can do as following.

foreach (string customer in customers.customers)
{
    Console.WriteLine(customer);
}

This is however, changes that might be needed to make your existing code working. But, if you were to rewrite the entire code , you have couple of options.

a) Could do away with CustomerList class and use List directly.

var customers = new List<string>();
customers.Add("Apple");

b) Use the CustomerList class but use the public property Customers to add to the list directly

public class CustomerList
{
    public CustomerList()
    {
        customers = new List<string>();
    }

    public List<String> Customers;
}

Client Code

CustomerList customers = new CustomerList();

customers.Customers.Add("Apple");
customers.Customers.Add("Microsoft");

c) The third option is to implement IEnumerable interface, but however, considering the requirement of your code,  and fact that you are still learning C#, I would say it might be an overkill. It would be better to get a firm understanding of Collections and Classes/Properties first, before you actually go ahead with IEnumerable implementation


问:
conflicting types for Function’ struct error in C
I currently am trying to pass a struct to a different file using a header file. It also gives me the warning "struct Connection’ declared inside parameter list". Three are three files, piggy1.h,piggg1.c, and ear.c. Any thoughts on why I can't get this code to compile?
Thanks so much guys!</p>

```<code>//piggy1.h----------------------------------------
void ear(struct Connection *connect1);

//-------------------------------------------------*
//ear.c --------------------------------------------
include "piggy1.h"

void ear(struct Connection *connect1){}

//---------------------------------------------------*
//piggy1.c -------------------------------------------

include "piggy1.h"

struct Connection{
int llport;
int rrport;
char rraddr[50];
int noleft;
int noright;
};

 main(argc, argv)

int argc;
char *argv[];
{
int cases;
int noright = -1;
int noleft = -1;
int rraddr = -1;
int llport = -1;
int rrport = -1;
struct Connection connect;
}
</code>```

答:
Conflicting error means the parameters passes in your definition section and parameters passed in your declaration section do not match.

In your case, the error is shown because definition and declaration of ear function is done before the struct definition.

The compiler doesn't recognise your parameters and so an error is thrown.

Body:
I currently am trying to pass a struct to a different file using a header file. It also gives me the warning "struct Connection’ declared inside parameter list". Three are three files, piggy1.h,piggg1.c, and ear.c. Any thoughts on why I can't get this code to compile?
Thanks so much guys!

//piggy1.h----------------------------------------
void ear(struct Connection *connect1);

//-------------------------------------------------*
//ear.c --------------------------------------------
include "piggy1.h"

void ear(struct Connection *connect1){}

//---------------------------------------------------*
//piggy1.c -------------------------------------------

include "piggy1.h"

struct Connection{
int llport;
int rrport;
char rraddr[50];
int noleft;
int noright;
};

 main(argc, argv)

int argc;
char *argv[];
{
int cases;
int noright = -1;
int noleft = -1;
int rraddr = -1;
int llport = -1;
int rrport = -1;
struct Connection connect;
}


问:
Laravel Recursive Relationships
I'm working on a project in Laravel. I have an Account model that can have a parent or can have children, so I have my model set up like so:

```<code>public function immediateChildAccounts()
{
    return $this->hasMany('Account', 'act_parent', 'act_id');
}

public function parentAccount()
{
    return $this->belongsTo('Account', 'act_parent', 'act_id');
}
</code>```

This works fine. What I want to do is get all children under a certain account. Currently, I'm doing this:

```<code>public function allChildAccounts()
{
    $childAccounts = $this->immediateChildAccounts;
    if (empty($childAccounts))
        return $childAccounts;

    foreach ($childAccounts as $child)
    {
        $child->load('immediateChildAccounts');
        $childAccounts = $childAccounts->merge($child->allChildAccounts());
    }

    return $childAccounts;
}
</code>```

This also works, but I have to worry if it's slow. This project is the re-write of an old project we use at work. We will have several thousand accounts that we migrate over to this new project. For the few test accounts I have, this method poses no performance issues.

Is there a better solution? Should I just run a raw query? Does Laravel have something to handle this?

In summary
What I want to do, for any given account, is get every single child account and every child of it's children and so on in a single list/collection. A diagram:

```<code>A -> B -> D
|--> C -> E
     |--> F
G -> H
</code>```

If I run A->immediateChildAccounts(), I should get {B, C}

If I run A->allChildAccounts(), I should get {B, D, C, E, F} (order doesn't matter)

Again, my method works, but it seems like I'm doing way too many queries.

Also, I'm not sure if it's okay to ask this here, but it is related. How can I get a list of all accounts that don't include the child accounts? So basically the inverse of that method above. This is so a user doesn't try to give an account a parent that's already it's child. Using the diagram from above, I want (in pseudocode):

Account::where(account_id not in (A->allChildAccounts())). So I would get {G, H}

Thanks for any insight.

答:
I've created a package that uses common table expressions (CTE) to implement recursive relationships: https://github.com/staudenmeir/laravel-adjacency-list

You can use the descendants relationship to get all children of an account recursively:

class Account extends Model
{
    use \Staudenmeir\LaravelAdjacencyList\Eloquent\HasRecursiveRelationships;
}

$allChildren = Account::find($id)->descendants;
```

Title: Laravel Recursive Relationships

Body:
I'm working on a project in Laravel. I have an Account model that can have a parent or can have children, so I have my model set up like so:

public function immediateChildAccounts()
{
    return $this->hasMany('Account', 'act_parent', 'act_id');
}

public function parentAccount()
{
    return $this->belongsTo('Account', 'act_parent', 'act_id');
}

This works fine. What I want to do is get all children under a certain account. Currently, I'm doing this:

public function allChildAccounts()
{
    $childAccounts = $this->immediateChildAccounts;
    if (empty($childAccounts))
        return $childAccounts;

    foreach ($childAccounts as $child)
    {
        $child->load('immediateChildAccounts');
        $childAccounts = $childAccounts->merge($child->allChildAccounts());
    }

    return $childAccounts;
}

This also works, but I have to worry if it's slow. This project is the re-write of an old project we use at work. We will have several thousand accounts that we migrate over to this new project. For the few test accounts I have, this method poses no performance issues.

Is there a better solution? Should I just run a raw query? Does Laravel have something to handle this?

In summary
What I want to do, for any given account, is get every single child account and every child of it's children and so on in a single list/collection. A diagram:

A -> B -> D
|--> C -> E
     |--> F
G -> H

If I run A->immediateChildAccounts(), I should get {B, C}

If I run A->allChildAccounts(), I should get {B, D, C, E, F} (order doesn't matter)

Again, my method works, but it seems like I'm doing way too many queries.

Also, I'm not sure if it's okay to ask this here, but it is related. How can I get a list of all accounts that don't include the child accounts? So basically the inverse of that method above. This is so a user doesn't try to give an account a parent that's already it's child. Using the diagram from above, I want (in pseudocode):

Account::where(account_id not in (A->allChildAccounts())). So I would get {G, H}

Thanks for any insight.


问:
Perpendicular on a line from a given point
How can I draw a perpendicular on a line segment from a given point? My line segment is defined as (x1, y1), (x2, y2), If I draw a perpendicular from a point (x3,y3) and it meets to line on point (x4,y4). I want to find out this (x4,y4).</p>

答:
This is a vectorized Matlab function for finding pairwise projections of m points onto n line segments. Here xp and yp are m by 1 vectors holding coordinates of m different points, and x1, y1, x2 and y2 are n by 1 vectors holding coordinates of start and end points of n different line segments.
It returns m by n matrices, x and y, where x(i, j) and y(i, j) are coordinates of projection of i-th point onto j-th line.

The actual work is done in first few lines and the rest of the function runs a self-test demo, just in case where it is called with no parameters. It's relatively fast, I managed to find projections of 2k points onto 2k line segments in less than 0.05s.

```<code>function [x, y] = projectPointLine(xp, yp, x1, y1, x2, y2)
if nargin > 0
        xd = (x2-x1)';
    yd = (y2-y1)';
    dAB = xd.*xd + yd.*yd;
    u = bsxfun(@rdivide, bsxfun(@times, bsxfun(@minus, xp, x1'), xd) + ...
        bsxfun(@times, bsxfun(@minus, yp, y1'), yd), dAB);
    x = bsxfun(@plus, x1', bsxfun(@times, u, xd));
    y = bsxfun(@plus, y1', bsxfun(@times, u, yd));
else
    nLine = 3;
    nPoint = 2;
    xp = rand(nPoint, 1) * 2 -1;
    yp = rand(nPoint, 1) * 2 -1;
    x1 = rand(nLine, 1) * 2 -1;
    y1 = rand(nLine, 1) * 2 -1;
    x2 = rand(nLine, 1) * 2 -1;
    y2 = rand(nLine, 1) * 2 -1;
    tic;
    [x, y] = projectPointLine(xp, yp, x1, y1, x2, y2);
    toc
    close all;
    plot([x1'; x2'], [y1'; y2'], '.-', 'linewidth', 2, 'markersize', 20);
    axis equal;
    hold on
    C = lines(nPoint + nLine);
    for i=1:nPoint
        scatter(x(i, :), y(i, :), 100, C(i+nLine, :), 'x', 'linewidth', 2);
        scatter(xp(i), yp(i), 100, C(i+nLine, :), 'x', 'linewidth', 2);
    end
    for i=1:nLine
        scatter(x(:, i)', y(:, i)', 100, C(i, :), 'o', 'linewidth', 2);
    end
end
end
</code>```

Body:
This is a vectorized Matlab function for finding pairwise projections of m points onto n line segments. Here xp and yp are m by 1 vectors holding coordinates of m different points, and x1, y1, x2 and y2 are n by 1 vectors holding coordinates of start and end points of n different line segments.
It returns m by n matrices, x and y, where x(i, j) and y(i, j) are coordinates of projection of i-th point onto j-th line.

The actual work is done in first few lines and the rest of the function runs a self-test demo, just in case where it is called with no parameters. It's relatively fast, I managed to find projections of 2k points onto 2k line segments in less than 0.05s.

function [x, y] = projectPointLine(xp, yp, x1, y1, x2, y2)
if nargin > 0
        xd = (x2-x1)';
    yd = (y2-y1)';
    dAB = xd.*xd + yd.*yd;
    u = bsxfun(@rdivide, bsxfun(@times, bsxfun(@minus, xp, x1'), xd) + ...
        bsxfun(@times, bsxfun(@minus, yp, y1'), yd), dAB);
    x = bsxfun(@plus, x1', bsxfun(@times, u, xd));
    y = bsxfun(@plus, y1', bsxfun(@times, u, yd));
else
    nLine = 3;
    nPoint = 2;
    xp = rand(nPoint, 1) * 2 -1;
    yp = rand(nPoint, 1) * 2 -1;
    x1 = rand(nLine, 1) * 2 -1;
    y1 = rand(nLine, 1) * 2 -1;
    x2 = rand(nLine, 1) * 2 -1;
    y2 = rand(nLine, 1) * 2 -1;
    tic;
    [x, y] = projectPointLine(xp, yp, x1, y1, x2, y2);
    toc
    close all;
    plot([x1'; x2'], [y1'; y2'], '.-', 'linewidth', 2, 'markersize', 20);
    axis equal;
    hold on
    C = lines(nPoint + nLine);
    for i=1:nPoint
        scatter(x(i, :), y(i, :), 100, C(i+nLine, :), 'x', 'linewidth', 2);
        scatter(xp(i), yp(i), 100, C(i+nLine, :), 'x', 'linewidth', 2);
    end
    for i=1:nLine
        scatter(x(:, i)', y(:, i)', 100, C(i, :), 'o', 'linewidth', 2);
    end
end
end