问:
DbSet<xxx>' does not contain a definition for 'Update' and no accessible extension method 'Update'
here is my code block

```<code> foreach(var n in animalbirdAdoptionDetails)
 {
    int animalBirdsId = n.AnimalsAndBirdsId;
    int NoAnimal =  Convert.ToInt32(n.NoAnimalsAdopted);
    n.isActive = false;
    context.NameOfAnimalsAndBirds.Update(e2 => new entity
                     {
                         quantity = e2.quantity + moreQuantity
                     });
    context.SaveChanges();

  }

</code>```

DbSet' does not contain a definition for 'Update' and no accessible extension method 'Update' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)

答:
You are facing this error because in entity framework there is no update extension method available.

If you want to update existing records then you need to retrieve existing record by primary key reference or by any other table field reference.
and assign new value to table fields.

Eg.

```<code>foreach(var n in animalbirdAdoptionDetails)
{
    // remove unwanted variables and casting expression.
    // if not required then.
    int animalBirdsId = n.AnimalsAndBirdsId;
    int NoAnimal =  Convert.ToInt32(n.NoAnimalsAdopted);
    n.isActive = false;

    // Retrieve existing record
    var entity = context.NameOfAnimalsAndBirds.FirstOrDefault(x => x.Id == n.Id);

    // assign new value to existing property.
    entity.quantity = entity.quantity + moreQuantity;

    // in last just apply save changes.
    context.SaveChanges();
}
</code>```

Note: above code is for demonstration only. it is always good practice to update all entities at once and apply save changes (from outside of loop).

Body:
here is my code block

 foreach(var n in animalbirdAdoptionDetails)
 {
    int animalBirdsId = n.AnimalsAndBirdsId;
    int NoAnimal =  Convert.ToInt32(n.NoAnimalsAdopted);
    n.isActive = false;
    context.NameOfAnimalsAndBirds.Update(e2 => new entity
                     {
                         quantity = e2.quantity + moreQuantity
                     });
    context.SaveChanges();

  }

DbSet' does not contain a definition for 'Update' and no accessible extension method 'Update' accepting a first argument of type 'DbSet' could be found (are you missing a using directive or an assembly reference?)

Body:
You are facing this error because in entity framework there is no update extension method available.

If you want to update existing records then you need to retrieve existing record by primary key reference or by any other table field reference.
and assign new value to table fields.

Eg.

foreach(var n in animalbirdAdoptionDetails)
{
    // remove unwanted variables and casting expression.
    // if not required then.
    int animalBirdsId = n.AnimalsAndBirdsId;
    int NoAnimal =  Convert.ToInt32(n.NoAnimalsAdopted);
    n.isActive = false;

    // Retrieve existing record
    var entity = context.NameOfAnimalsAndBirds.FirstOrDefault(x => x.Id == n.Id);

    // assign new value to existing property.
    entity.quantity = entity.quantity + moreQuantity;

    // in last just apply save changes.
    context.SaveChanges();
}

Note: above code is for demonstration only. it is always good practice to update all entities at once and apply save changes (from outside of loop).


来源: stackexchange

问:
Copying files from a series of directories based off a list in a text file
I am attempting to use either rsync or cp in a for loop to copy files matching a list of 200 of names stored on new lines in a .txt file that match filenames with the .pdbqt extension that are in a series of subdirectories with one parent folder. The .txt file looks as follows:

```<code>file01
file02
file08
file75
file45
...
</code>```

I have attempted to use rsync with the following command:

```<code>rsync -a /home/ubuntu/Project/files/pdbqt/*/*.pdbqt \
--files-from=/home/ubuntu/Project/working/output.txt \
/home/ubuntu/Project/files/top/
</code>```

When I run the rsync command I receive:

```<code>rsync error: syntax or usage error (code 1) at options.c(2346) [client=3.1.2]
</code>```

I have written a bash script as follows in an attempt to get that to work:

```<code>#!/bin/bash
for i in "$(cat /home/ubuntu/Project/working/output.txt | tr '\n' '')"; do
    cp /home/ubuntu/Project/files/pdbqt/*/"$i".pdbqt /home/ubuntu/Project/files/top/;
done
</code>```

I understand cat isn't a great command to use but I could not figure out an alternate solution to it, as I am still new to using bash. Running that I get the following error:

```<code>tr: when not truncating set1, string2 must be non-empty
cp: cannot stat '/home/ubuntu/Project/files/pdbqt/*/.pdbqt': No such file or directory
</code>```

I assume that the cp error is thrown as a result of the tr error but I am not sure how else to get rid of the \n that is read from the new line separated list.

The expected results are that from the subdirectories in /pdbqt/ with the 12000 .pdbqt files the 200 files from the output.txt list would be copied from those subdirectories into the /top/ directory.

答:
Do dirs in Project/files/pdbqt/* or files *.pdbqt have dashes (-) in the name?

The error is showing the line in rsync source code options.c
"Your options have been rejected by the server.\n"

which makes me think that it's interpreting inodes (files/dirs) in your glob as rsync options.

```<code>for i in $( < /home/ubuntu/Project/working/output.txt LC_CTYPE=C tr '\n' ' ' )
do
  cp /home/ubuntu/Project/files/pdbqt/*/"${i}.pdbqt" /home/ubuntu/Project/files/top/
done
</code>```

I think your cat tr is missing a space

cat /home/ubuntu/Project/working/output.txt | tr '\n' ' '

John1024's use of while and read are better than mine.

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to use either rsync or cp in a for loop to copy files matching a list of 200 of names stored on new lines in a .txt file that match filenames with the .pdbqt extension that are in a series of subdirectories with one parent folder. The .txt file looks as follows:

file01
file02
file08
file75
file45
...

I have attempted to use rsync with the following command:

rsync -a /home/ubuntu/Project/files/pdbqt/*/*.pdbqt \
--files-from=/home/ubuntu/Project/working/output.txt \
/home/ubuntu/Project/files/top/

When I run the rsync command I receive:

rsync error: syntax or usage error (code 1) at options.c(2346) [client=3.1.2]

I have written a bash script as follows in an attempt to get that to work:

#!/bin/bash
for i in "$(cat /home/ubuntu/Project/working/output.txt | tr '\n' '')"; do
    cp /home/ubuntu/Project/files/pdbqt/*/"$i".pdbqt /home/ubuntu/Project/files/top/;
done

I understand cat isn't a great command to use but I could not figure out an alternate solution to it, as I am still new to using bash. Running that I get the following error:

tr: when not truncating set1, string2 must be non-empty
cp: cannot stat '/home/ubuntu/Project/files/pdbqt/*/.pdbqt': No such file or directory

I assume that the cp error is thrown as a result of the tr error but I am not sure how else to get rid of the \n that is read from the new line separated list.

The expected results are that from the subdirectories in /pdbqt/ with the 12000 .pdbqt files the 200 files from the output.txt list would be copied from those subdirectories into the /top/ directory.

Body:
Do dirs in Project/files/pdbqt/* or files *.pdbqt have dashes (-) in the name?

The error is showing the line in rsync source code options.c
"Your options have been rejected by the server.\n"

which makes me think that it's interpreting inodes (files/dirs) in your glob as rsync options.

for i in $( < /home/ubuntu/Project/working/output.txt LC_CTYPE=C tr '\n' ' ' )
do
  cp /home/ubuntu/Project/files/pdbqt/*/"${i}.pdbqt" /home/ubuntu/Project/files/top/
done

I think your cat tr is missing a space

cat /home/ubuntu/Project/working/output.txt | tr '\n' ' '

John1024's use of while and read are better than mine.


问:
Conditionally convert string to int
In the line data=[int(x) if x else None for x in line.replace("\n","").split(",")] below I'd like to keep string values as string instead of throwing an exception if a value that can't be casted to int is encountered. Are there any elegant ways to do this? For instance, if you have on a given line 9327,Garlic Powder,104,13 then data would be [9327, "Garlic Powder", 104, 13]

Rik

```<code>file = open(file_path, 'r')

# get headers
try:
    header=next(file).replace("\n","").split(",")
except:
    raise Exception("The file {} is empty.".format(file.file_path))

count = 0 # to count number of rows

# loop through file and process data
for line in file:
    try:
        data=[int(x) if x else None for x in line.replace("\n","").split(",")]
    except:
        raise Exception("The file {} contains invalid data.".format(file.file_path))
    count += 1
    for f in callback_array:
        f(header,data)
</code>```

答:
You can define a function which checks if a string can be parsed to an integer. If it can, return the integer else return the string

```<code>def parse(s):

    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

line = '9327,Garlic Powder,104,13'
data=[parse(x) for x in line.replace("\n","").split(",")]

print(data)
</code>```

The output will be

```<code>[9327, 'Garlic Powder', 104, 13]
</code>```

Title: Conditionally convert string to int

Body:
In the line data=[int(x) if x else None for x in line.replace("\n","").split(",")] below I'd like to keep string values as string instead of throwing an exception if a value that can't be casted to int is encountered. Are there any elegant ways to do this? For instance, if you have on a given line 9327,Garlic Powder,104,13 then data would be [9327, "Garlic Powder", 104, 13]

Rik

file = open(file_path, 'r')

# get headers
try:
    header=next(file).replace("\n","").split(",")
except:
    raise Exception("The file {} is empty.".format(file.file_path))

count = 0 # to count number of rows

# loop through file and process data
for line in file:
    try:
        data=[int(x) if x else None for x in line.replace("\n","").split(",")]
    except:
        raise Exception("The file {} contains invalid data.".format(file.file_path))
    count += 1
    for f in callback_array:
        f(header,data)

Body:
You can define a function which checks if a string can be parsed to an integer. If it can, return the integer else return the string

def parse(s):

    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

line = '9327,Garlic Powder,104,13'
data=[parse(x) for x in line.replace("\n","").split(",")]

print(data)

The output will be

[9327, 'Garlic Powder', 104, 13]


问:
Create Component without folder
I need to create a component without the folder. I am using Angular-Cli command ng g c testing to create the component. But, the command creates an folder wrapper for the newly created component.

答:
ng g c test1 --flat --inline-template --inline-style

--flat allows us to create the new component without new folder.

--inline allows us to keep the template/style in the component file itself instead of creating separate file for those.

Title: Create Component without folder


问:
Server start error in Tomcat (getting java.lang.reflect.InvocationTargetException)
I am using Struts2 and Hibernate3 in my project, server is Tomcat 6.

I got such an error in my project, I can't get solution for this.

The server encountered an internal error () that prevented it from fulfilling this request.

Code:

```<code>java.lang.reflect.InvocationTargetException
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
    org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)
</code>```

答: I had done some mistake in hbm file and now I corrected that and it execute successfully.</p>

Body:
I am using Struts2 and Hibernate3 in my project, server is Tomcat 6.

I got such an error in my project, I can't get solution for this.

The server encountered an internal error () that prevented it from fulfilling this request.

Code:

java.lang.reflect.InvocationTargetException
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
    org.displaytag.filter.ResponseOverrideFilter.doFilter(ResponseOverrideFilter.java:125)


问:
"Not Supported by this Version of Xcode” and After Update Xcode Raises "Unsupported Swift Version"
After updating iPhone to iOS 12.2 I encountered this error in Xcode 10.1:

“This iPhone is running iOS 12.2, which may not be supported by this
  version of Xcode.”

So I have to update Xcode to latest version and after updating Xcode to 10.2, when I open the project, Xcode show another error that say:

Unsupported Swift Version

“MyProject” contains source code developed with Swift 3.x. This version of Xcode does not support building or migrating Swift 3.x
  targets.

Use Xcode 10.1 to migrate the code to Swift 4.

Now I couldn't run the project correctly in neither Xcode 10.1 nor 10.2!

I think I have to update my code to Swift 5 to Xcode 10.2 be able to compile the code. Am I right?

But updating the whole project is overwhelming.

Is there any other way to resolve the problem?

答:
I have same issue while migrating code from Swift 3.x to Swift 4+.x :

Try to check two main things :

Target and project setting swift version should be 4.2 or swift 5 ( in case of XCode 10.2)

change build system.


问:
Merge levels of same variable which are in consecutive columns
I have a csv data file which has 2 headers that means one header as a question and the second one as a sub header which has multiple levels or answers for the main header. Current csv look like below table

```
Header  Which country do you live?        Which country you previously visited?
Users    Canada  USA   UK  Mexico  Norway India  Singapore  Pakistan
User 1   Canada                                  Singapore
User 2                 UK                 India
User 3                     Mexico                           Pakistan
User 4                             Norway India
```

I need to transform it into below table

```
Users   Which country do you live?  Which country you previously visited?
User 1  Canada                      Singapore
User 2  UK                          India
User 3  Norway                      Pakistan
User 4  Mexico                      India
```

Can someone help me with this?

This is how my data look like

My input file look like this

and this is how my final output look like

答:
First back filling missing values by bfill, then select first column and remove second level of MultiIndex by DataFrame.droplevel:

```<code>print (df.columns)
MultiIndex(levels=[['Header', 'Which country do you live?'],
                   ['Canada', 'Mexico', 'UK', 'USA', 'Users']],
           codes=[[0, 1, 1, 1, 1], [4, 0, 3, 2, 1]])
</code>```

```<code>#if first column is not index, create it
#df = df.set_index([df.columns[0]])
#if empty strings repalce them to NaNs
#df = df.replace('', np.nan)

df = df.bfill(axis=1).iloc[:, 0].reset_index().droplevel(level=1, axis=1)
print (df)
   Header Which country do you live?
0  User 1                     Canada
1  User 2                         UK
2  User 3                     Mexico
3  User 4                     Norway
</code>```

EDIT:

```<code>df = df.groupby(level=0, axis=1).apply(lambda x: x.bfill(axis=1).iloc[:, 0])
print (df)
   Header Which country do you live? Which country you previously visited?
0  User 1                     Canada                             Singapore
1  User 2                         UK                                 India
2  User 3                     Mexico                              Pakistan
3  User 4                     Norway                                 India
</code>```

Body:
I have a csv data file which has 2 headers that means one header as a question and the second one as a sub header which has multiple levels or answers for the main header. Current csv look like below table

Header  Which country do you live?        Which country you previously visited?
Users    Canada  USA   UK  Mexico  Norway India  Singapore  Pakistan
User 1   Canada                                  Singapore
User 2                 UK                 India
User 3                     Mexico                           Pakistan
User 4                             Norway India

I need to transform it into below table

Users   Which country do you live?  Which country you previously visited?
User 1  Canada                      Singapore
User 2  UK                          India
User 3  Norway                      Pakistan
User 4  Mexico                      India

Can someone help me with this?

This is how my data look like

My input file look like this

and this is how my final output look like

Body:
First back filling missing values by bfill, then select first column and remove second level of MultiIndex by DataFrame.droplevel:

print (df.columns)
MultiIndex(levels=[['Header', 'Which country do you live?'],
                   ['Canada', 'Mexico', 'UK', 'USA', 'Users']],
           codes=[[0, 1, 1, 1, 1], [4, 0, 3, 2, 1]])

#if first column is not index, create it
#df = df.set_index([df.columns[0]])
#if empty strings repalce them to NaNs
#df = df.replace('', np.nan)

df = df.bfill(axis=1).iloc[:, 0].reset_index().droplevel(level=1, axis=1)
print (df)
   Header Which country do you live?
0  User 1                     Canada
1  User 2                         UK
2  User 3                     Mexico
3  User 4                     Norway

EDIT:

df = df.groupby(level=0, axis=1).apply(lambda x: x.bfill(axis=1).iloc[:, 0])
print (df)
   Header Which country do you live? Which country you previously visited?
0  User 1                     Canada                             Singapore
1  User 2                         UK                                 India
2  User 3                     Mexico                              Pakistan
3  User 4                     Norway                                 India


问:
Error while importing neurokit in jupyter notebook
In Jupyter notebook, I have to import neurokit.

There was this error:

ImportError: No module named neurokit

So I tried:

```<code>!pip install neurokit
</code>```

but there was another error:

IOError: [Errno 2] No such file or directory: 'README.md'

Can anyone help me with this?

This is the error:

```<code>!pip install neurokit

Collecting neurokit
  Using cached https://files.pythonhosted.org/packages/aa/e4/aac4c53fb12d52c292988897bff3d003a5798ec582b267f57057bfdf6c31/neurokit-0.2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\dell\appdata\local\temp\pip-install-i17inb\neurokit\setup.py", line 39, in <module>
        long_description = open('README.md').read(),
    IOError: [Errno 2] No such file or directory: 'README.md'
</code>```

答:
Try to install it as instructed in their github page:

Installation

Run the following:

```<code>pip install https://github.com/neuropsychology/NeuroKit.py/zipball/master
</code>```

If that's still not working, try not using the cached copy (from your logs, you have a cached neurokit-0.2.0.tar.gz) and also force re-installation:

```<code>pip install --no-cache-dir --force-reinstall https://github.com/neuropsychology/NeuroKit.py/zipball/master
</code>```

Body:
In Jupyter notebook, I have to import neurokit.

There was this error:

ImportError: No module named neurokit

So I tried:

!pip install neurokit

but there was another error:

IOError: [Errno 2] No such file or directory: 'README.md'

Can anyone help me with this?

This is the error:

!pip install neurokit

Collecting neurokit
  Using cached https://files.pythonhosted.org/packages/aa/e4/aac4c53fb12d52c292988897bff3d003a5798ec582b267f57057bfdf6c31/neurokit-0.2.0.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "c:\users\dell\appdata\local\temp\pip-install-i17inb\neurokit\setup.py", line 39, in <module>
        long_description = open('README.md').read(),
    IOError: [Errno 2] No such file or directory: 'README.md'

Body:
Try to install it as instructed in their github page:

Installation

Run the following:

pip install https://github.com/neuropsychology/NeuroKit.py/zipball/master

If that's still not working, try not using the cached copy (from your logs, you have a cached neurokit-0.2.0.tar.gz) and also force re-installation:

pip install --no-cache-dir --force-reinstall https://github.com/neuropsychology/NeuroKit.py/zipball/master


问:
Does "if constexpr(something false)" ALWAYS omit template instantiation
Will this template function f<X>() be always NOT instantiated?

```<code>if constexpr(something false){
     //some template function OR function in template class
     f<X>();
}
</code>```

Below is my test (coliru MCVE).

I created fun<S>() that will instantiate E<S> if and only if S!=void.

Then I call fun<void>(),fun<int>() and fun<float>().

I believe if constexpr(false) forces C++ compiler to skip the #1 part for fun<void>().

My countRunner should be ++ only 2 times.

Thus, if my assumption is true, the below program will always prints 2 in every compiler and every setting.

(It printed 2 for me, but the experiment alone proves nothing.)

```<code>#include<iostream>
int countRunner=0;
template<class T> class E{
    public: static int countIndex;
    public: E(){
        if(false){
            int unused=E::countIndex;
        }
    }
};
template<class T> int E<T>::countIndex=countRunner++;
template<class S> void fun(){
    if constexpr(!std::is_same_v<void,S>){
        E<S> e;  //#1  - S=int,float, but never void
    }
}
int main (){
    fun<void>();
    fun<int>();
    std::cout<<"testResult="<<countRunner<<std::endl;
    fun<float>();
}
</code>```

Can I rely that E<void> will never be instantiated?

Please provide some (semi-)official reference to make me calm down.

Edit: I just found http://eel.is/c++draft/stmt.if#2 and "If constexpr" in C++17 does not work in a non-templated function.

If the if statement is of the form if constexpr, the value of the
  condition shall be a contextually converted constant expression of
  type bool; this form is called a constexpr if statement. If the value
  of the converted condition is false, the first substatement is a
  discarded statement, otherwise the second substatement, if present, is
  a discarded statement. During the instantiation of an enclosing
  templated entity, if the condition is not value-dependent after its
  instantiation, the discarded substatement (if any) is not
  instantiated. [ Note: Odr-uses in a discarded statement do not require
  an entity to be defined. — end note  ] A case or default label
  appearing within such an if statement shall be associated with a
  switch statement within the same if statement. A label declared in a
  substatement of a constexpr if statement shall only be referred to by
  a statement in the same substatement.

I am still not sure about the word "instantiated" in the rule.  Does it have the same meaning as in "template instantiation"?

答:
Does it have the same meaning as in "template instantiation"?

Yes, it does. The specification speaks of "discarded" statements, and has meaning only in the context of template instantiation for some enclosing templated entity.

[stmt.if] (emphasis mine)

2 If the if statement is of the form if constexpr, the value of
  the condition shall be a contextually converted constant expression of
  type bool; this form is called a constexpr if statement. If the value
  of the converted condition is false, the first substatement is a
  discarded statement, otherwise the second substatement, if present, is
  a discarded statement. During the instantation of an enclosing
  templated entity, if the condition is not value-dependent after its
  instantiation, the discarded substatement (if any) is not
  instantiated.

The important bit is the condition being value-dependent after the parameters are substituted. On one leg, it means that if the condition depends only on the parameters of the immediately enclosing template that is being instantaited, it will not be part of the instantiation of that template.

In your case, it means exactly that if std::is_same_v<void,S> is true, the body of the "if" won't be part of the instantiated fun<void>.

Body:
Will this template function f<X>() be always NOT instantiated?

if constexpr(something false){
     //some template function OR function in template class
     f<X>();
}

Below is my test (coliru MCVE).

I created fun<S>() that will instantiate E<S> if and only if S!=void.

Then I call fun<void>(),fun<int>() and fun<float>().

I believe if constexpr(false) forces C++ compiler to skip the #1 part for fun<void>().

My countRunner should be ++ only 2 times.

Thus, if my assumption is true, the below program will always prints 2 in every compiler and every setting.

(It printed 2 for me, but the experiment alone proves nothing.)

#include<iostream>
int countRunner=0;
template<class T> class E{
    public: static int countIndex;
    public: E(){
        if(false){
            int unused=E::countIndex;
        }
    }
};
template<class T> int E<T>::countIndex=countRunner++;
template<class S> void fun(){
    if constexpr(!std::is_same_v<void,S>){
        E<S> e;  //#1  - S=int,float, but never void
    }
}
int main (){
    fun<void>();
    fun<int>();
    std::cout<<"testResult="<<countRunner<<std::endl;
    fun<float>();
}

Can I rely that E<void> will never be instantiated?

Please provide some (semi-)official reference to make me calm down.

Edit: I just found http://eel.is/c++draft/stmt.if#2 and "If constexpr" in C++17 does not work in a non-templated function.

If the if statement is of the form if constexpr, the value of the
  condition shall be a contextually converted constant expression of
  type bool; this form is called a constexpr if statement. If the value
  of the converted condition is false, the first substatement is a
  discarded statement, otherwise the second substatement, if present, is
  a discarded statement. During the instantiation of an enclosing
  templated entity, if the condition is not value-dependent after its
  instantiation, the discarded substatement (if any) is not
  instantiated. [ Note: Odr-uses in a discarded statement do not require
  an entity to be defined. — end note  ] A case or default label
  appearing within such an if statement shall be associated with a
  switch statement within the same if statement. A label declared in a
  substatement of a constexpr if statement shall only be referred to by
  a statement in the same substatement.

I am still not sure about the word "instantiated" in the rule.  Does it have the same meaning as in "template instantiation"?


问:
How to active a button only when a file uploaded and checked terms and conditions?
I have a page which have to upload a list of people and agree to the terms and conditions before click on pay button. How to disable a button till they upload the file and checked into the terms and conditions checkbox?

```<code>    //fileuploadFunction (Convert to json)
    $(document).ready(function(){
          $("#employeelist").change(function(evt){
             window.selectedFile = evt.target.files[0];
             convertToExcel(); return false;
          });
    });
</code>```

    <input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" />

    <input type="checkbox" name="termsNcon" value="termsNcon" id="termsNcon" /> I have read and agree to the Terms and Conditions and Privacy Policy

    <button id="stripe-button"> >Continue to Pay</button>
```

I need to enable >Continue to Pay button only when a file is uploaded and checked on Terms and Conditions.

答:
$(document).on("change","#ckbx",function(){
if($(this).is(":checked")) {
$("#btn").prop("disabled",false);
}
else{
$("#btn").prop("disabled",true);
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="ckbx" type="checkbox" />
<input id="btn" type="button" disabled="true" value="submit" /></code>```

Body:
I have a page which have to upload a list of people and agree to the terms and conditions before click on pay button. How to disable a button till they upload the file and checked into the terms and conditions checkbox?

    //fileuploadFunction (Convert to json)
    $(document).ready(function(){
          $("#employeelist").change(function(evt){
             window.selectedFile = evt.target.files[0];
             convertToExcel(); return false;
          });
    });

    <input type="file" id="employeelist" name="employeelist" autofocus autocomplete="off" accept=".csv, .xls, .xlsx" />

    <input type="checkbox" name="termsNcon" value="termsNcon" id="termsNcon" /> I have read and agree to the Terms and Conditions and Privacy Policy

    <button id="stripe-button"> >Continue to Pay</button>

I need to enable >Continue to Pay button only when a file is uploaded and checked on Terms and Conditions.

Body:
$(document).on("change","#ckbx",function(){
if($(this).is(":checked")) {
$("#btn").prop("disabled",false);
}
else{
$("#btn").prop("disabled",true);
}
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="ckbx" type="checkbox" />
<input id="btn" type="button" disabled="true" value="submit" />


问:
Selecting default item from Combobox C#
I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.

I'm trying something like that:

```<code>SelectPrint11.SelectedIndex=2;
</code>```

but error is:

```<code>System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'
</code>```

Edit:

In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection

答:
You can set using SelectedIndex

```<code>comboBox1.SelectedIndex= 1;
</code>```

OR

SelectedItem

```<code>comboBox1.SelectedItem = "your value"; //
</code>```

The latter won't throw an exception if the value is not available in the combobox

EDIT

If the value to be selected is not specific then you would be better off with this

```<code>comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
</code>```

Title: Selecting default item from Combobox C#

Body:
I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.

I'm trying something like that:

SelectPrint11.SelectedIndex=2;

but error is:

System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'

Edit:

In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection

Body:
You can set using SelectedIndex

comboBox1.SelectedIndex= 1;

OR

SelectedItem

comboBox1.SelectedItem = "your value"; //

The latter won't throw an exception if the value is not available in the combobox

EDIT

If the value to be selected is not specific then you would be better off with this

comboBox1.SelectedIndex = comboBox1.Items.Count - 1;

ContentLicense: CC BY-SA 3.0


问:
mutiple sorting rule with IComparable and IComparer?
I'm new to C#, just a question on how to use IComparable and IComparer properly. Let's say we have the following class:

```<code>public class Student
{
    int score;
    string name;
}
</code>```

and I want to sort by socre (desc) first then sort by name (asc).

Now assume that I can't access to the Student class, so I can only use IComparer
so I have to make one help class(let's say it is called StudentComparer) and put the same logic into

```<code>
public class StudentComparer: IComparer
{
   int Compare(object o1, object o2)
   {
      Student s1 = o1 as Student;
      Student s2 = o2 as Student;
      // not checking null for simplicity
      if (s1.score == s2.score)
         return String.Compare(s1.name, s2.name);
      else if (s1.score < s2.score)
           return -1
      else
      return 1
   }
}
</code>```

Here is my question, if I just need to use a single rule later, for example, sometimes just sort by name and sometimes just sort by score. So I have to make another two help classes(ScoreComparer and NameComparer) that implement IComparer, which have duplicated code in StudentComparer as

```<code>public class ScoreComparer : IComparer
{
   int Compare(object o1, object o2)
   {
      //half logic of StudentComparer
   }
}

public class NameComparer: IComparer
{
   int Compare(object o1, object o2)
   {
      //half logic of StudentComparer
   }
}
</code>```

my case is pretty simple, image that if there is a complicated case, each comparer consist of hundreds line of code,so how can I avoid duplicated code? or is it a way to combine multiple Comparer A, B, C, D ... into a common Comparer so that it check A,B,C,D in sequence, just like order by clause in SQL

答:
Back in the days before linq, I used to use comparers a lot.

The way I've handled different sort options was by specifying these options in the constructor of the comparer implementation and then use that information in the Compare method.

Lucky for us, we now have linq so this entire thing can be done with a single, fluent line of code:

```<code>// sortedStudents is an IEnumerable<Student> sorted by score and name.
var sortedStudents = students.OrderBy(s => s.Score).ThenBy(s => s.Name);
</code>```

However, if for some reason you need to work the old-fashion way, using comparers and stuff like that, here is how I would handle this back then:

```<code>internal enum CompareBy
{
    NameOnly,
    ScoreAndName
}

public class StudentComparer: IComparer<Student>
{

    private CompareBy _compareBy
    public StudentComparer(CompareBy compareBy)
    {
        _compareBy = compareBy;
    }

    public int Compare(Student s1, Student s2)
    {
        // not checking null for simplicity

        var nameCompare = string.Compare(s1.name, s2.name);
        if(_compareBy == NameOnly)
        {
            return nameCompare;
        }
        // since there are only two members in the enum it's safe to write it like this.
        // if the enum grows, you must change the code.
        if (s1.score == s2.score)
        {
            return nameCompare;
        }
        else if (s1.score < s2.score)
        {
            return -1
        }
        return 1
   }
}
</code>```

Body:
I'm new to C#, just a question on how to use IComparable and IComparer properly. Let's say we have the following class:

public class Student
{
    int score;
    string name;
}

and I want to sort by socre (desc) first then sort by name (asc).

Now assume that I can't access to the Student class, so I can only use IComparer
so I have to make one help class(let's say it is called StudentComparer) and put the same logic into

public class StudentComparer: IComparer
{
   int Compare(object o1, object o2)
   {
      Student s1 = o1 as Student;
      Student s2 = o2 as Student;
      // not checking null for simplicity
      if (s1.score == s2.score)
         return String.Compare(s1.name, s2.name);
      else if (s1.score < s2.score)
           return -1
      else
      return 1
   }
}

Here is my question, if I just need to use a single rule later, for example, sometimes just sort by name and sometimes just sort by score. So I have to make another two help classes(ScoreComparer and NameComparer) that implement IComparer, which have duplicated code in StudentComparer as

public class ScoreComparer : IComparer
{
   int Compare(object o1, object o2)
   {
      //half logic of StudentComparer
   }
}

public class NameComparer: IComparer
{
   int Compare(object o1, object o2)
   {
      //half logic of StudentComparer
   }
}

my case is pretty simple, image that if there is a complicated case, each comparer consist of hundreds line of code,so how can I avoid duplicated code? or is it a way to combine multiple Comparer A, B, C, D ... into a common Comparer so that it check A,B,C,D in sequence, just like order by clause in SQL

Body:
Back in the days before linq, I used to use comparers a lot.

The way I've handled different sort options was by specifying these options in the constructor of the comparer implementation and then use that information in the Compare method.

Lucky for us, we now have linq so this entire thing can be done with a single, fluent line of code:

// sortedStudents is an IEnumerable<Student> sorted by score and name.
var sortedStudents = students.OrderBy(s => s.Score).ThenBy(s => s.Name);

However, if for some reason you need to work the old-fashion way, using comparers and stuff like that, here is how I would handle this back then:

internal enum CompareBy
{
    NameOnly,
    ScoreAndName
}

public class StudentComparer: IComparer<Student>
{

    private CompareBy _compareBy
    public StudentComparer(CompareBy compareBy)
    {
        _compareBy = compareBy;
    }

    public int Compare(Student s1, Student s2)
    {
        // not checking null for simplicity

        var nameCompare = string.Compare(s1.name, s2.name);
        if(_compareBy == NameOnly)
        {
            return nameCompare;
        }
        // since there are only two members in the enum it's safe to write it like this.
        // if the enum grows, you must change the code.
        if (s1.score == s2.score)
        {
            return nameCompare;
        }
        else if (s1.score < s2.score)
        {
            return -1
        }
        return 1
   }
}


问:
Firebase App crashed on launch when made active from background
I have a Firebase integrated to my swift app. All the initialisation done is programmatically and the FirebaseApp.config() is called the very first thing in didLaunchWithOptions in the AppDelegate.

But for some random reason, whenever the app is in the background for a long time, the app just crashes on the run, i.e making it's state active.
Interestingly, this crash happens exactly 2 times in the following flow:

```<code>1. The App is idle in background
2. You bring it to the active mode(You just tap the icon to open the app. All this while the app isn't killed)
3. Tap 1  ---- The App Crashes----
4. Tap 2  ---- The App Crashes----
5. Tap 3  ---- The App Runs Normally ----
</code>```

I tried to troubleshoot but all my efforts have gone in vain. I have tried setting up both the storyboards and programmatically launching app. Nothing works.

Following is the stack trace :

```<code>            SpotMi-Dev[74741:2958059] *** Terminating app due to uncaught exception 'FIRAppNotConfigured', reason: 'Failed to get default Firebase Database instance. Must call `[FIRApp configure]` (`FirebaseApp.configure()` in Swift) before using Firebase Database.'
        *** First throw call stack:
        (
        0   CoreFoundation                      0x000000010d3816fb __exceptionPreprocess + 331
        1   libobjc.A.dylib                     0x000000010c14aac5 objc_exception_throw + 48
        2   CoreFoundation                      0x000000010d381555 +[NSException raise:format:] + 197
        3   SpotMi-Dev                          0x0000000101be5ba1 +[FIRDatabase database] + 97
        4   SpotMi-Dev                          0x0000000101aaba6b $s10SpotMi_Dev13FBDataserviceCACycfc + 59
        5   SpotMi-Dev                          0x0000000101aac193 $s10SpotMi_Dev13FBDataserviceCACycfcTo + 19
        6   SpotMi-Dev                          0x0000000101aa696c $s10SpotMi_Dev13FBDataserviceCACycfC + 44
        7   SpotMi-Dev                          0x0000000101aa692c globalinit_33_8263DB418F9D5BC81149F56895386F46_func0 + 28
        8   libdispatch.dylib                   0x000000010ecaddb5 _dispatch_client_callout + 8
        9   libdispatch.dylib                   0x000000010ecaf83d _dispatch_once_callout + 66
        10  libswiftCore.dylib                  0x000000010e2c6579 swift_once + 25
        11  SpotMi-Dev                          0x0000000101aa69f4 $s10SpotMi_Dev13FBDataserviceC2dsACvau + 36
        12  SpotMi-Dev                          0x000000010180b013 $s10SpotMi_Dev9ProfileVCC18initializeUserPostyyF + 179
        13  SpotMi-Dev                          0x0000000101809278 $s10SpotMi_Dev9ProfileVCC11viewDidLoadyyF + 616
        14  SpotMi-Dev                          0x00000001018095b4 $s10SpotMi_Dev9ProfileVCC11viewDidLoadyyFTo + 36
        15  UIKitCore                           0x000000011589443b -[UIViewController loadViewIfRequired] + 1183
        16  UIKitCore                           0x0000000115894868 -[UIViewController view] + 27
        17  UIKitCore                           0x0000000115ebd4ad -[UIApplication(StateRestoration) _restoreApplicationPreservationStateWithSessionIdentifier:beginHandler:completionHandler:] + 6413
        18  UIKitCore                           0x0000000115eb8fdc -[UIApplication(StateRestoration) _doRestorationIfNecessary] + 211
        19  UIKitCore                           0x0000000115e8e2c9 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 208
        20  UIKitCore                           0x0000000115e8fcad -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3932
        21  UIKitCore                           0x0000000115e950c6 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1617
        22  UIKitCore                           0x00000001156da6d6 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 904
        23  UIKitCore                           0x00000001156e2fce +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
        24  UIKitCore                           0x00000001156da2ec -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 236
        25  UIKitCore                           0x00000001156dac48 -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 1091
        26  UIKitCore                           0x00000001156d8fba __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 782
        27  UIKitCore                           0x00000001156d8c71 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 433
        28  UIKitCore                           0x00000001156dd9b6 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 576
        29  UIKitCore                           0x00000001156de610 _performActionsWithDelayForTransitionContext + 100
        30  UIKitCore                           0x00000001156dd71d -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 223
        31  UIKitCore                           0x00000001156e26d0 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
        32  UIKitCore                           0x0000000115e939a8 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 514
        33  UIKitCore                           0x0000000115a4adfa -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 361
        34  FrontBoardServices                  0x00000001133a4125 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 448
        35  FrontBoardServices                  0x00000001133aded6 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 283
        36  FrontBoardServices                  0x00000001133ad700 __40-[FBSWorkspace _performDelegateCallOut:]_block_invoke + 53
        37  libdispatch.dylib                   0x000000010ecaddb5 _dispatch_client_callout + 8
        38  libdispatch.dylib                   0x000000010ecb12ba _dispatch_block_invoke_direct + 300
        39  FrontBoardServices                  0x00000001133df146 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
        40  FrontBoardServices                  0x00000001133dedfe -[FBSSerialQueue _performNext] + 451
        41  FrontBoardServices                  0x00000001133df393 -[FBSSerialQueue _performNextFromRunLoopSource] + 42
        42  CoreFoundation                      0x000000010d2e8be1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
        43  CoreFoundation                      0x000000010d2e8463 __CFRunLoopDoSources0 + 243
        44  CoreFoundation                      0x000000010d2e2b1f __CFRunLoopRun + 1231
        45  CoreFoundation                      0x000000010d2e2302 CFRunLoopRunSpecific + 626
        46  GraphicsServices                    0x000000011034e2fe GSEventRunModal + 65
        47  UIKitCore                           0x0000000115e96ba2 UIApplicationMain + 140
        48  SpotMi-Dev                          0x000000010174287b main + 75
        49  libdyld.dylib                       0x000000010ed22541 start + 1
        )
        libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

Following is the code from didLaunchWithOptions:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    #if DEVELOPMENT
        print("Development Mode Started")
    #else
        print("Production Mode Started")
    #endif
    FirebaseApp.configure()
    Messaging.messaging().delegate = self

    //other app functions

    return true
}
</code>```

I am calling the Firebase API in the viewDidLoad of init controller. And this is the Service through which it gets called and this even contains the crash aswell.

```<code>class FBDataservice : NSObject {
    static var ds = FBDataservice() //<------ Creates Error here on every single crash related to this issue

let DB_URL: DatabaseReference = Database.database().reference()
let ST_URL: StorageReference = Storage.storage().reference()

private lazy var _REF_BASE = DB_URL

}
</code>```

And then I just call FBDataservice.ds._REF_BASE.child("something").observe( .Event, with (Datasnapshot)) in the viewDidLoad or viewDidAppear. I am just mostly fetching the data. And then push data like updating app RunCounts on didBecameActive in AppDelegate

Any help will immensely be appreciated. Cheers

答:
Check FirebaseApp.app() if this is nil can you call the FirebaseApp.configure() again? You need to debug if this crashes in appDidBecomeActive: or didEneterInForeground: method.

Also please check where you use FirebaseDatabase at very first time after launching the application except the configuration line? I mean is in any ViewController or anywhere, we need to check the condition here.

Updated Question:

Regarding your updated question FBDataservice() where are you making its instance because as you create its instance it will create DB_URL and ST_URL url instances which are related to Firebase so probably Firebase is not configured before this. You can override its init method to check if Firebase is configured or not.

You took two variables which will be create in constructor whenever you will make an instance of this class.

Try one thing... replace

```<code>static var ds = FBDataservice()
</code>```

with

```<code>static var ds: FBDataservice {
    if FirebaseApp.app() == nil {
         FirebaseApp.configure()
    }
    return FBDataservice()
}
</code>```

Body:
I have a Firebase integrated to my swift app. All the initialisation done is programmatically and the FirebaseApp.config() is called the very first thing in didLaunchWithOptions in the AppDelegate.

But for some random reason, whenever the app is in the background for a long time, the app just crashes on the run, i.e making it's state active.
Interestingly, this crash happens exactly 2 times in the following flow:

1. The App is idle in background
2. You bring it to the active mode(You just tap the icon to open the app. All this while the app isn't killed)
3. Tap 1  ---- The App Crashes----
4. Tap 2  ---- The App Crashes----
5. Tap 3  ---- The App Runs Normally ----

I tried to troubleshoot but all my efforts have gone in vain. I have tried setting up both the storyboards and programmatically launching app. Nothing works.

Following is the stack trace :

            SpotMi-Dev[74741:2958059] *** Terminating app due to uncaught exception 'FIRAppNotConfigured', reason: 'Failed to get default Firebase Database instance. Must call `[FIRApp configure]` (`FirebaseApp.configure()` in Swift) before using Firebase Database.'
        *** First throw call stack:
        (
        0   CoreFoundation                      0x000000010d3816fb __exceptionPreprocess + 331
        1   libobjc.A.dylib                     0x000000010c14aac5 objc_exception_throw + 48
        2   CoreFoundation                      0x000000010d381555 +[NSException raise:format:] + 197
        3   SpotMi-Dev                          0x0000000101be5ba1 +[FIRDatabase database] + 97
        4   SpotMi-Dev                          0x0000000101aaba6b $s10SpotMi_Dev13FBDataserviceCACycfc + 59
        5   SpotMi-Dev                          0x0000000101aac193 $s10SpotMi_Dev13FBDataserviceCACycfcTo + 19
        6   SpotMi-Dev                          0x0000000101aa696c $s10SpotMi_Dev13FBDataserviceCACycfC + 44
        7   SpotMi-Dev                          0x0000000101aa692c globalinit_33_8263DB418F9D5BC81149F56895386F46_func0 + 28
        8   libdispatch.dylib                   0x000000010ecaddb5 _dispatch_client_callout + 8
        9   libdispatch.dylib                   0x000000010ecaf83d _dispatch_once_callout + 66
        10  libswiftCore.dylib                  0x000000010e2c6579 swift_once + 25
        11  SpotMi-Dev                          0x0000000101aa69f4 $s10SpotMi_Dev13FBDataserviceC2dsACvau + 36
        12  SpotMi-Dev                          0x000000010180b013 $s10SpotMi_Dev9ProfileVCC18initializeUserPostyyF + 179
        13  SpotMi-Dev                          0x0000000101809278 $s10SpotMi_Dev9ProfileVCC11viewDidLoadyyF + 616
        14  SpotMi-Dev                          0x00000001018095b4 $s10SpotMi_Dev9ProfileVCC11viewDidLoadyyFTo + 36
        15  UIKitCore                           0x000000011589443b -[UIViewController loadViewIfRequired] + 1183
        16  UIKitCore                           0x0000000115894868 -[UIViewController view] + 27
        17  UIKitCore                           0x0000000115ebd4ad -[UIApplication(StateRestoration) _restoreApplicationPreservationStateWithSessionIdentifier:beginHandler:completionHandler:] + 6413
        18  UIKitCore                           0x0000000115eb8fdc -[UIApplication(StateRestoration) _doRestorationIfNecessary] + 211
        19  UIKitCore                           0x0000000115e8e2c9 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 208
        20  UIKitCore                           0x0000000115e8fcad -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3932
        21  UIKitCore                           0x0000000115e950c6 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1617
        22  UIKitCore                           0x00000001156da6d6 __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 904
        23  UIKitCore                           0x00000001156e2fce +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 153
        24  UIKitCore                           0x00000001156da2ec -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 236
        25  UIKitCore                           0x00000001156dac48 -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 1091
        26  UIKitCore                           0x00000001156d8fba __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 782
        27  UIKitCore                           0x00000001156d8c71 -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 433
        28  UIKitCore                           0x00000001156dd9b6 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 576
        29  UIKitCore                           0x00000001156de610 _performActionsWithDelayForTransitionContext + 100
        30  UIKitCore                           0x00000001156dd71d -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 223
        31  UIKitCore                           0x00000001156e26d0 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 392
        32  UIKitCore                           0x0000000115e939a8 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 514
        33  UIKitCore                           0x0000000115a4adfa -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 361
        34  FrontBoardServices                  0x00000001133a4125 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 448
        35  FrontBoardServices                  0x00000001133aded6 __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 283
        36  FrontBoardServices                  0x00000001133ad700 __40-[FBSWorkspace _performDelegateCallOut:]_block_invoke + 53
        37  libdispatch.dylib                   0x000000010ecaddb5 _dispatch_client_callout + 8
        38  libdispatch.dylib                   0x000000010ecb12ba _dispatch_block_invoke_direct + 300
        39  FrontBoardServices                  0x00000001133df146 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
        40  FrontBoardServices                  0x00000001133dedfe -[FBSSerialQueue _performNext] + 451
        41  FrontBoardServices                  0x00000001133df393 -[FBSSerialQueue _performNextFromRunLoopSource] + 42
        42  CoreFoundation                      0x000000010d2e8be1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
        43  CoreFoundation                      0x000000010d2e8463 __CFRunLoopDoSources0 + 243
        44  CoreFoundation                      0x000000010d2e2b1f __CFRunLoopRun + 1231
        45  CoreFoundation                      0x000000010d2e2302 CFRunLoopRunSpecific + 626
        46  GraphicsServices                    0x000000011034e2fe GSEventRunModal + 65
        47  UIKitCore                           0x0000000115e96ba2 UIApplicationMain + 140
        48  SpotMi-Dev                          0x000000010174287b main + 75
        49  libdyld.dylib                       0x000000010ed22541 start + 1
        )
        libc++abi.dylib: terminating with uncaught exception of type NSException

Following is the code from didLaunchWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    #if DEVELOPMENT
        print("Development Mode Started")
    #else
        print("Production Mode Started")
    #endif
    FirebaseApp.configure()
    Messaging.messaging().delegate = self

    //other app functions

    return true
}

I am calling the Firebase API in the viewDidLoad of init controller. And this is the Service through which it gets called and this even contains the crash aswell.

class FBDataservice : NSObject {
    static var ds = FBDataservice() //<------ Creates Error here on every single crash related to this issue

let DB_URL: DatabaseReference = Database.database().reference()
let ST_URL: StorageReference = Storage.storage().reference()

private lazy var _REF_BASE = DB_URL

}

And then I just call FBDataservice.ds._REF_BASE.child("something").observe( .Event, with (Datasnapshot)) in the viewDidLoad or viewDidAppear. I am just mostly fetching the data. And then push data like updating app RunCounts on didBecameActive in AppDelegate

Any help will immensely be appreciated. Cheers

Body:
Check FirebaseApp.app() if this is nil can you call the FirebaseApp.configure() again? You need to debug if this crashes in appDidBecomeActive: or didEneterInForeground: method.

Also please check where you use FirebaseDatabase at very first time after launching the application except the configuration line? I mean is in any ViewController or anywhere, we need to check the condition here.

Updated Question:

Regarding your updated question FBDataservice() where are you making its instance because as you create its instance it will create DB_URL and ST_URL url instances which are related to Firebase so probably Firebase is not configured before this. You can override its init method to check if Firebase is configured or not.

You took two variables which will be create in constructor whenever you will make an instance of this class.

Try one thing... replace

static var ds = FBDataservice()

with

static var ds: FBDataservice {
    if FirebaseApp.app() == nil {
         FirebaseApp.configure()
    }
    return FBDataservice()
}


问:
Appium - Java - Android: toggleWifi method does not appear in eclipse auto suggestions?
So I have to turn ON/OFF device Wifi during test.

I am using:

appium - 1.12.1

Java-client - 4.1.2

Android OS version - 8.1.0

Device - Oppo F9 Pro

I have tried:

```<code>driver[deviceIndex].setConnection(Connection.NONE);
assertEquals(Connection.ALL, driver[deviceIndex].getConnection());
</code>```

But it's not working.

And below one also suggested by Appium to use:

```<code>driver.toggleWifi();
</code>```

But "toggleWifi" is not suggesting in eclipse.

Please let me know if you need any more info.

答:
Use the latest stable java-client. In order to use toggleWifi() and setNetworkConnection() method you must use AndroidDriver. If you are using AppiumDriver you must typeCast it to android driver like following.

```<code>((AndroidDriver) driver).toggleWifi();
((AndroidDriver) driver).setNetworkConnection(2);
</code>```

There are certain limitation of using setNetworkConnection() method

Check this link for more information about setNetworkConnection() method

Body:
So I have to turn ON/OFF device Wifi during test.

I am using:

appium - 1.12.1

Java-client - 4.1.2

Android OS version - 8.1.0

Device - Oppo F9 Pro

I have tried:

driver[deviceIndex].setConnection(Connection.NONE);
assertEquals(Connection.ALL, driver[deviceIndex].getConnection());

But it's not working.

And below one also suggested by Appium to use:

driver.toggleWifi();

But "toggleWifi" is not suggesting in eclipse.

Please let me know if you need any more info.

Body:
Use the latest stable java-client. In order to use toggleWifi() and setNetworkConnection() method you must use AndroidDriver. If you are using AppiumDriver you must typeCast it to android driver like following.

((AndroidDriver) driver).toggleWifi();
((AndroidDriver) driver).setNetworkConnection(2);

There are certain limitation of using setNetworkConnection() method

Check this link for more information about setNetworkConnection() method


问:
jsGrid Filtering issue calling data from .net controller
Successfully performing CRUD operations with jsGrid but unable able to get the filter working

I've searched everywhere (SO, YouTube, js-grid.com). Turning to the SO community for help after being stuck with this problem all day

View

```<code>@model MyNamespace.Models.ViewModels.VehicleViewModel
<h1>Vehicles</h1>
<div id="jsGrid"></div>

    <script>
    var lastPrevItem;

    $(function () {
        var result = $.Deferred();

            $("#jsGrid").jsGrid({
                height: "400px",
                width: "100%",
                inserting: true,
                editing: true,
                sorting: true,
                paging: true,
                autoload: true,
                loadMessage: "Please, wait...",
                pageSize: 10,
                pageButtonCount: 5,
                readonly: false,
                filtering: true,
                deleteConfirm: "Do you really want to delete?",

                controller: {
                    loadData: function (filter) {
                        var d = $.Deferred();
                        $.ajax({
                            type: "GET",
                            url: "/Vehicles/GridJsonGet",
                            data: {
                                data: filter
                            },
                            dataType: "json",
                            success: function (filter) {
                                filter ? console.log("success", filter) : alert("Could not load vehicles");
                            }

                        }).done(function (response) {
                                d.resolve(response);
                            });
                        return d.promise();
                    },

                    insertItem: function (item) {
                        var ajaxDeferredInsert = $.ajax({
                            type: "POST",
                            url: "/Vehicles/GridJsonPost",
                            data: item,
                            dataType: "json",
                            success: function (item) {
                                item ? console.log("Add Vehicle success") : alert("Vehicle could not be added");
                            }
                        });
                        ajaxDeferredInsert.done(function (insertItem) {
                            console.log("inserted item", insertItem);
                            result.resolve(insertItem);
                        }).fail(function () {
                            result.resolve(lastPrevItem);
                        });

                        return result.promise();
                    },

                    updateItem: function (item) {

                        var ajaxDeferredUpdate = $.ajax({
                            type: "PUT",
                            url: "/Vehicles/GridJsonPut/" + item.VehicleId,
                            data: item,
                            dataType: "json",
                            success: function (item) {
                                item ? console.log("Update success", item) : alert("Vehicle could not be updated");
                            }
                        });
                        ajaxDeferredUpdate.done(function (updatedItem) {
                            result.resolve(updatedItem);
                        }).fail(function () {
                            result.resolve(lastPrevItem);
                        });

                        return result.promise();
                    },

                    deleteItem: function (item) {
                        return $.ajax({
                            type: "DELETE",
                            url: "/Vehicles/GridJsonDelete/" + item.VehicleId,
                            data: item,
                            dataType: "json",
                            success: function (item) {
                                if (item) {
                                    console.log("Delete success");
                                }
                                else {
                                    alert("Vehicle could not be deleted");
                                    location.reload();
                                }
                            },
                        });
                    },
                },

                fields: [
                    {
                        name: "VIN",
                        title: "VIN",
                        type: "text",
                        width: 20
                    },
                    {
                        name: "Make",
                        title: "Make",
                        @*items: @Html.Raw(Model.VehicleMakesJson),*@
                        valueField: "Id",
                        textField: "Name",
                        type: "text",
                        width: 75,
                        filtering: true
                    },
                    {
                        name: "VehicleModel",
                        title: "Model",
                        items: @Html.Raw(Model.VehicleModelsJson),
                        valueField: "Id",
                        textField: "Name",
                        type: "select",
                        width: 75,
                        filtering: true
                    },
                    {
                        name: "InitialOdometer",
                        title: "Initial Odometer",
                        type: "number",
                        width: 40
                    },
                    {
                        name: "IsActive",
                        title: "Active",
                        width: 20,
                        type: "checkbox",
                        insertTemplate: function () {
                            var $result = jsGrid.fields.checkbox.prototype.insertTemplate.call(this);
                            $result.prop("checked", true);
                            return $result;
                        }
                    },
                    {
                        title: "View",
                        width: 20,
                        itemTemplate: function (value, item) {
                            var $customLink = $("<i>").attr({ class: "jsgrid-custom-button fas fa-external-link-alt" })
                                .click(function (e) {
                                    location = item.Link + item.VehicleId;
                                    e.stopPropagation();
                                });
                            return $("<div>").append($customLink);
                        },
                    },
                    {
                        type: 'control',
                        deleteButton: false,
                        width: 20
                    },
                ]
            });
    });
</script>
</code>```

Controller

```<code>    public ActionResult Index()
    {
        VehicleViewModel model = new VehicleViewModel();
        model.Vehicles = service.GetVehicles();

        model.VehicleMakes.Add(new VehicleTypes
        {
            Id = 0,
            Name = ""
        });

        foreach (var item in model.Vehicles)
        {
            model.VehicleMakes.Add(new VehicleTypes
            {
                Id = item.VehicleId,
                Name = item.Make
            });
        }
        model.VehicleModels.Add(new VehicleTypes
        {
            Id = 0,
            Name = ""
        });

        foreach (var item in model.Vehicles)
        {
            model.VehicleModels.Add(new VehicleTypes
            {
                Id = item.VehicleId,
                Name = item.VehicleModel
            });
        }

        model.VehicleMakesJson = JsonConvert.SerializeObject(model.VehicleMakes);
        model.VehicleModelsJson = JsonConvert.SerializeObject(model.VehicleModels);

        return View(model);
    }

    [HttpGet]
    public string GridJsonGet(string filter)
    {
        VehicleViewModel model = new VehicleViewModel();
        model.Vehicles = service.GetVehicles();
        json = JsonConvert.SerializeObject(model.Vehicles);
        return json;
    }
</code>```

For some reason I can't seem to get one without the other either a select list or data populated in the grid.

On the field named 'Make' I have commented out the items array & set type as text, this gives me results in the grid but then I dont get a select list of makes.

On the field named 'VehicleModel' I am populating items from the viewmodel which gives me a select list but no data in the grid.

Not sure what I need to do differently?

答:
The answer was so simple, I just had the wrong parameter name in my MVC controller method (smh)

updated load data call (view)

```<code>loadData: function (filter) {
  var d = $.Deferred();
  var filterData = JSON.stringify(filter);
  $.ajax({
      type: "GET",
      url: "/Vehicles/GridJsonGet",
      data: {
         data: filterData
      },
       dataType: "json"
   }).done(function (response) {
       d.resolve(response);
       });
       return d.promise();
   },

updated controller method

public string GridJsonGet(string data)
    {
        VehicleViewModel model = new VehicleViewModel();

        var gridData = JsonConvert.DeserializeObject<Vehicle>(data);

        if (!String.IsNullOrEmpty(gridData.Make))
        {
            model.Vehicles = service.GetVehiclesByFilter(gridData.Make);

        }
        if (!string.IsNullOrEmpty(gridData.VehicleModel))
        {
            model.Vehicles = service.GetVehiclesByFilter(gridData.VehicleModel);

        }
        else
        {
            model.Vehicles = service.GetVehicles();
        }
        json = JsonConvert.SerializeObject(model.Vehicles);
        return json;
    }
</code>```

Body:
Successfully performing CRUD operations with jsGrid but unable able to get the filter working

I've searched everywhere (SO, YouTube, js-grid.com). Turning to the SO community for help after being stuck with this problem all day

View

@model MyNamespace.Models.ViewModels.VehicleViewModel

Vehicles

Controller

    public ActionResult Index()
    {
        VehicleViewModel model = new VehicleViewModel();
        model.Vehicles = service.GetVehicles();

        model.VehicleMakes.Add(new VehicleTypes
        {
            Id = 0,
            Name = ""
        });

        foreach (var item in model.Vehicles)
        {
            model.VehicleMakes.Add(new VehicleTypes
            {
                Id = item.VehicleId,
                Name = item.Make
            });
        }
        model.VehicleModels.Add(new VehicleTypes
        {
            Id = 0,
            Name = ""
        });

        foreach (var item in model.Vehicles)
        {
            model.VehicleModels.Add(new VehicleTypes
            {
                Id = item.VehicleId,
                Name = item.VehicleModel
            });
        }

        model.VehicleMakesJson = JsonConvert.SerializeObject(model.VehicleMakes);
        model.VehicleModelsJson = JsonConvert.SerializeObject(model.VehicleModels);

        return View(model);
    }

    [HttpGet]
    public string GridJsonGet(string filter)
    {
        VehicleViewModel model = new VehicleViewModel();
        model.Vehicles = service.GetVehicles();
        json = JsonConvert.SerializeObject(model.Vehicles);
        return json;
    }

For some reason I can't seem to get one without the other either a select list or data populated in the grid.

On the field named 'Make' I have commented out the items array & set type as text, this gives me results in the grid but then I dont get a select list of makes.

On the field named 'VehicleModel' I am populating items from the viewmodel which gives me a select list but no data in the grid.

Not sure what I need to do differently?

Body:
The answer was so simple, I just had the wrong parameter name in my MVC controller method (smh)

updated load data call (view)

loadData: function (filter) {
  var d = $.Deferred();
  var filterData = JSON.stringify(filter);
  $.ajax({
      type: "GET",
      url: "/Vehicles/GridJsonGet",
      data: {
         data: filterData
      },
       dataType: "json"
   }).done(function (response) {
       d.resolve(response);
       });
       return d.promise();
   },

updated controller method

public string GridJsonGet(string data)
    {
        VehicleViewModel model = new VehicleViewModel();

        var gridData = JsonConvert.DeserializeObject<Vehicle>(data);

        if (!String.IsNullOrEmpty(gridData.Make))
        {
            model.Vehicles = service.GetVehiclesByFilter(gridData.Make);

        }
        if (!string.IsNullOrEmpty(gridData.VehicleModel))
        {
            model.Vehicles = service.GetVehiclesByFilter(gridData.VehicleModel);

        }
        else
        {
            model.Vehicles = service.GetVehicles();
        }
        json = JsonConvert.SerializeObject(model.Vehicles);
        return json;
    }


问:
Have a way to just show the last item from my db, in a view with @foreach?
Have a way to just show the last item added on my db, to my home with @foreach?</p>

```<code>@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)
                                    <div class="fs-rp-item">
                                        <div class="entry-image">
                                            <!--<a href="#"><img src="/holy/images/blog/fs-thumb.jpg" alt="recent post"></a>-->
                                            <a href="#"><img src="/uploads/post/{{$post->id}}/image/{{$post->file_1}}" alt="recent post"></a>
                                        </div>
                                        <div class="entry-rp">
                                            <h4>
                                                <a href="#">{{$post->title}}</a>
                                            </h4>
                                            <p class="read-more">
                                                <a href="#">read the article</a>
                                            </p>
                                        </div>
                                    </div>
                                    @endforeach
</code>```

答:
Try this</p>

```<code>App\Models\Post::orderBy('created_at','DESC')->first()
</code>```

Body:
Have a way to just show the last item added on my db, to my home with @foreach?

@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)

                                            id}}/image/{{$post->file_1}}" alt="recent post">

                                                {{$post->title}}

                                                read the article

                                    @endforeach

Body:
Try this

App\Models\Post::orderBy('created_at','DESC')->first()


问:
Querydsl not create Metamodel in Spring Boot
I am trying to use Querydsl in Spring Boot 2.1.4.RELEASE, but fail because Metamodel not generated.

This is error message:

```<code>Caused by: java.lang.ClassNotFoundException: com.example.MyApp.model.QProduct
</code>```

This is my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>MyApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MyApp</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
          <groupId>com.querydsl</groupId>
          <artifactId>querydsl-apt</artifactId>
          <scope>provided</scope>
        </dependency>

        <dependency>
          <groupId>com.querydsl</groupId>
          <artifactId>querydsl-jpa</artifactId>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>com.mysema.maven</groupId>
                    <artifactId>apt-maven-plugin</artifactId>
                    <version>1.1.3</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>process</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>target/generated-sources/java</outputDirectory>
                                <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                            </configuration>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>com.mysema.querydsl</groupId>
                            <artifactId>querydsl-apt</artifactId>
                            <version>${querydsl.version}</version>
                        </dependency>
                        <dependency>
                            <groupId>com.mysema.querydsl</groupId>
                            <artifactId>querydsl-jpa</artifactId>
                            <version>${querydsl.version}</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>

</code>```

I have trying to run project as Maven generate-sources, Maven Build goal:compile, but still not create Metamodel class, even java folder not exist in generated-sources folder.

I am using Spring Tools Suite 3.9.4.RELEASE.

How to solve this problem...?

答:
Remove the pluginmanagement xml tag comment out the dependencies defined in the mysema plugin and your Q-classes will be generated. Your plugins should be as follows:

```<code><build>
    <!--<pluginManagement>--> // Remove pluginManagement
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>maven-apt-plugin</artifactId>
            <version>1.0</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
                        <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
    <!--</pluginManagement>-->
</build>
</code>```

Body:
I am trying to use Querydsl in Spring Boot 2.1.4.RELEASE, but fail because Metamodel not generated.

This is error message:

Caused by: java.lang.ClassNotFoundException: com.example.MyApp.model.QProduct

This is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>MyApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MyApp</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
          <groupId>com.querydsl</groupId>
          <artifactId>querydsl-apt</artifactId>
          <scope>provided</scope>
        </dependency>

        <dependency>
          <groupId>com.querydsl</groupId>
          <artifactId>querydsl-jpa</artifactId>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>com.mysema.maven</groupId>
                    <artifactId>apt-maven-plugin</artifactId>
                    <version>1.1.3</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>process</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>target/generated-sources/java</outputDirectory>
                                <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                            </configuration>
                        </execution>
                    </executions>
                    <dependencies>
                        <dependency>
                            <groupId>com.mysema.querydsl</groupId>
                            <artifactId>querydsl-apt</artifactId>
                            <version>${querydsl.version}</version>
                        </dependency>
                        <dependency>
                            <groupId>com.mysema.querydsl</groupId>
                            <artifactId>querydsl-jpa</artifactId>
                            <version>${querydsl.version}</version>
                        </dependency>
                    </dependencies>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>

I have trying to run project as Maven generate-sources, Maven Build goal:compile, but still not create Metamodel class, even java folder not exist in generated-sources folder.

I am using Spring Tools Suite 3.9.4.RELEASE.

How to solve this problem...?

Body:
Remove the pluginmanagement xml tag comment out the dependencies defined in the mysema plugin and your Q-classes will be generated. Your plugins should be as follows:

<build>
    <!--<pluginManagement>--> // Remove pluginManagement
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>com.mysema.maven</groupId>
            <artifactId>maven-apt-plugin</artifactId>
            <version>1.0</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>process</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
                        <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
    <!--</pluginManagement>-->
</build>