问:
Making a multiple field search in Django
I am trying to make a search page that searches for model objects using three fields corresponding to different pieces of data. Here is my code below:

models.py

```<code>class Schedules(models.Model):
    course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
</code>```

views.py

```<code>def search_Schedule(request):
    context_dict = {}
    if request.method == 'POST':
        query1 = request.POST['course_name_search']
        query2 = request.POST['start_date_search']
        query3 = request.POST['instructor_search']
        if query1:
            results = Schedules.objects.filter(course_name__icontains=query1)
            if query2:
                results = results.filter(start_time=query2)
                if query3:
                    results = results.filter(instructor__icontains=query3)
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
                else:
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + " and " + query2
            elif query3:
                results = results.filter(start_time__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1
        elif query2:
            results = Schedules.objects.filter(start_time=query2)
            if query3:
                results = results.filter(instructor__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2
        elif query3:
            results = Schedules.objects.filter(instructor__icontains=query3)
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query3
    return render(request, "schedule/search_schedule.html", context_dict)
</code>```

search_schedule.html

```<code>{% block main_content %}
    <form method="post" action="">
        {% csrf_token %}
        <label for="course_name_search">Course Name:</label>
        <input type="text" name="course_name_search" id="course_name_search">

        <label for="start_date_search">Start Date:</label>
        <input type="datetime" name="start_date_search" id="start_date_search">

        <label for="instructor_search">Instructor:</label>
        <input type="text" name="instructor_search" id="instructor_search"><br>
        <input type="submit" name="submit">
    </form>
    <div id="result_panel">
        {% if table %}
            {% render_table table %}
        {% else %}
            {% if no_results %}
                No results returned for <q>{{ no_results }}</q>
            {% else %}
                Please enter a search
            {% endif %}
        {% endif %}
{% endblock %}
</code>```

For some reason, the search will work if I type in the course name field OR the instructor field, but won't work if I type in more than one field. And for some reason, the start date field will not work period, no matter how I type the date. Can somebody possibly help me with the correct way to type the code? Thank you.

答:
try this if it works.</p>

```<code>def search_Schedule(request):
context_dict = {}
if request.method == 'POST':
    query1 = request.POST.get('course_name_search',None)
    query2 = request.POST.get('start_date_search',None)
    query3 = request.POST.get('instructor_search',None)
    if query1:
        results = Schedules.objects.filter(course_name__icontains=query1)
        if query2:
            results = results.filter(start_time=datetime.datetime.strptime(query2, "%d%m%Y").date())
            if query3:
                results = results.filter(instructor__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + " and " + query2
        elif query3:
            results = results.filter(instructor__icontains=query3)   #changed this filter condition
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query1 + " and " + query3
        else:
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query1
    elif query2:
        results = Schedules.objects.filter(start_time=datetime.datetime.strptime(query2, "%d%m%Y").date())
        if query3:
            results = results.filter(instructor__icontains=query3)
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query2 + " and " + query3
        else:
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query2
    elif query3:
        results = Schedules.objects.filter(instructor__icontains=query3)
        table = ScheduleTable(results)
        if results.count():
            context_dict['table'] = table
        else:
            context_dict['no_results'] = query3
return render(request, "schedule/search_schedule.html", context_dict)
</code>```

Body:
I am trying to make a search page that searches for model objects using three fields corresponding to different pieces of data. Here is my code below:

models.py

class Schedules(models.Model):
    course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')

views.py

def search_Schedule(request):
    context_dict = {}
    if request.method == 'POST':
        query1 = request.POST['course_name_search']
        query2 = request.POST['start_date_search']
        query3 = request.POST['instructor_search']
        if query1:
            results = Schedules.objects.filter(course_name__icontains=query1)
            if query2:
                results = results.filter(start_time=query2)
                if query3:
                    results = results.filter(instructor__icontains=query3)
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
                else:
                    table = ScheduleTable(results)
                    if results.count():
                        context_dict['table'] = table
                    else:
                        context_dict['no_results'] = query1 + " and " + query2
            elif query3:
                results = results.filter(start_time__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1
        elif query2:
            results = Schedules.objects.filter(start_time=query2)
            if query3:
                results = results.filter(instructor__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2 + " and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query2
        elif query3:
            results = Schedules.objects.filter(instructor__icontains=query3)
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query3
    return render(request, "schedule/search_schedule.html", context_dict)

search_schedule.html

{% block main_content %}
    <form method="post" action="">
        {% csrf_token %}
        Course Name:
        <input type="text" name="course_name_search" id="course_name_search">

        Start Date:
        <input type="datetime" name="start_date_search" id="start_date_search">

        Instructor:
        <input type="text" name="instructor_search" id="instructor_search">

        <input type="submit" name="submit">
    </form>

        {% if table %}
            {% render_table table %}
        {% else %}
            {% if no_results %}
                No results returned for <q>{{ no_results }}</q>
            {% else %}
                Please enter a search
            {% endif %}
        {% endif %}
{% endblock %}

For some reason, the search will work if I type in the course name field OR the instructor field, but won't work if I type in more than one field. And for some reason, the start date field will not work period, no matter how I type the date. Can somebody possibly help me with the correct way to type the code? Thank you.

Body:
try this if it works.

def search_Schedule(request):
context_dict = {}
if request.method == 'POST':
    query1 = request.POST.get('course_name_search',None)
    query2 = request.POST.get('start_date_search',None)
    query3 = request.POST.get('instructor_search',None)
    if query1:
        results = Schedules.objects.filter(course_name__icontains=query1)
        if query2:
            results = results.filter(start_time=datetime.datetime.strptime(query2, "%d%m%Y").date())
            if query3:
                results = results.filter(instructor__icontains=query3)
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + ", " + query2 + ", and " + query3
            else:
                table = ScheduleTable(results)
                if results.count():
                    context_dict['table'] = table
                else:
                    context_dict['no_results'] = query1 + " and " + query2
        elif query3:
            results = results.filter(instructor__icontains=query3)   #changed this filter condition
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query1 + " and " + query3
        else:
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query1
    elif query2:
        results = Schedules.objects.filter(start_time=datetime.datetime.strptime(query2, "%d%m%Y").date())
        if query3:
            results = results.filter(instructor__icontains=query3)
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query2 + " and " + query3
        else:
            table = ScheduleTable(results)
            if results.count():
                context_dict['table'] = table
            else:
                context_dict['no_results'] = query2
    elif query3:
        results = Schedules.objects.filter(instructor__icontains=query3)
        table = ScheduleTable(results)
        if results.count():
            context_dict['table'] = table
        else:
            context_dict['no_results'] = query3
return render(request, "schedule/search_schedule.html", context_dict)


来源: stackexchange

问:
Transformation of the uppercase form of a number into type integer in R
In my dataset, i have variables, where numbers are written in uppercase format.
For example:

```<code>18 123 thousand dollars
19123 millon dollars
</code>```

How using R to transform this format to type integer?
I mean, i need this format.

```<code>18 123 000
19 123 000 000
</code>```

答:
```<code>options(scipen=999)     //it will prevent long numbers conversion in scientific notation
df= data.frame(amount = c("18 123 thousand dollars","19 123 million dollars"))
df$amount <-  gsub("thousand dollars","000",df$amount)
df$amount <-  gsub("million dollars","000 000",df$amount)
df$amount <-  gsub("billion dollars","000 000 000",df$amount)
df$amount <-  gsub("\\s+","",df$amount)
df$amount <-  as.numeric(df$amount)
df
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my dataset, i have variables, where numbers are written in uppercase format.
For example:

18 123 thousand dollars
19123 millon dollars

How using R to transform this format to type integer?
I mean, i need this format.

18 123 000
19 123 000 000

ContentLicense: CC BY-SA 4.0


问:
Best way to check that element is not present using Selenium WebDriver with java
Im trying the code below but it seems it does not work... Can someone show me the best way to do this?</p>

```<code>public void verifyThatCommentDeleted(final String text) throws Exception {
    new WebDriverWait(driver, 5).until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                try {
                    input.findElement(By.xpath(String.format(
                            Locators.CHECK_TEXT_IN_FIRST_STATUS_BOX, text)));
                    return false;
                } catch (NoSuchElementException e) {
                    return true;
                }
            }
        });
    }
</code>```

答:
Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception. Also, we can make sure that the element is present or not.

Ex:   List elements =   driver.findElements(By.yourlocatorstrategy);

```<code>if(elements.size()>0){
    do this..
 } else {
    do that..
 }
</code>```

Body:
Im trying the code below but it seems it does not work... Can someone show me the best way to do this?

public void verifyThatCommentDeleted(final String text) throws Exception {
    new WebDriverWait(driver, 5).until(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                try {
                    input.findElement(By.xpath(String.format(
                            Locators.CHECK_TEXT_IN_FIRST_STATUS_BOX, text)));
                    return false;
                } catch (NoSuchElementException e) {
                    return true;
                }
            }
        });
    }

Body:
Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception. Also, we can make sure that the element is present or not.

Ex:   List elements =   driver.findElements(By.yourlocatorstrategy);

if(elements.size()>0){
    do this..
 } else {
    do that..
 }


问:
Matlab: Estimating coefficients of nonlinear differential equations
Need to solve the system of nonlinear differential equations:

```<code>x1p = a1*u2*x1^1.3 + a2*u1 + a3*u3
x2p = (a4*u2 + a5)*x1^1.3 + a6*x2
x3p = (a7*u3 + (a8*u2-a9)*x1)/a10
</code>```

x1p, x2p & x3p are time derivatives of x1, x2 & x3, i.e. dx1/dt, dx2/dt & dx3/dt.

we have descrete data of x1, x2 & x3 as well as of u1, u2 & u3. We need to solve the problem in order to get the unknown coefficients, a1, a2, …, a10.

Have checked many posts and can say the solution involves ODE45 (or other ODEX) and probably fsolve or fminsearch (Matlab), but have not managed to setup up the problem correctly, guess we don't understand the coding well. Please, suggestions.

Body:
Need to solve the system of nonlinear differential equations:

x1p = a1*u2*x1^1.3 + a2*u1 + a3*u3
x2p = (a4*u2 + a5)*x1^1.3 + a6*x2
x3p = (a7*u3 + (a8*u2-a9)*x1)/a10

x1p, x2p & x3p are time derivatives of x1, x2 & x3, i.e. dx1/dt, dx2/dt & dx3/dt.

we have descrete data of x1, x2 & x3 as well as of u1, u2 & u3. We need to solve the problem in order to get the unknown coefficients, a1, a2, …, a10.

Have checked many posts and can say the solution involves ODE45 (or other ODEX) and probably fsolve or fminsearch (Matlab), but have not managed to setup up the problem correctly, guess we don't understand the coding well. Please, suggestions.

Body:
you should replace x1p, x2p ,and x3p by using definition of derivative:
    x1p = (x1(i+1) - x(i))/ dt , and like this for the others.
then use folowing algorithm (it is not complete):

descrete data of x1, x2 & x3 as well as of u1, u2 & u3
dt = 0.01
myFun = @(a,x1,x2,x3,u1,u2,u3)
   [ (x1(i+1) - x1(i))/ dt = a(1)*u2(i)*x1(i)^1.3 + a(2)*u1(i) + a(3)*u3(i);
     (x2(i+1) - x2(i))/ dt = (a(4)*u2(i) + a(5)*x1(i)^1.3 + a(6)*x2(i);
     (x3(i+1) - x3(i))/ dt = (a(7)*u3(i) + (a(8)*u2(i)-a(9))*x1(i))/a(10) ]
A=[];
a0 = [0; 0; 0 ;0 ;....   ]
for i= 1:1: lenngth(x1)
a=fsolve(@(a)myFun(a,x1,x2,x3,u1,u2,u3),a0,options);
a0 = [ a(1,1) ; a(2,1); a(3,1) ; .......]
A = cat(1,A,a) ;
end
a1 = mean(A(1,:))
a2 = mean(A(2,:))
.
.
a10 = mean(A(10,:))


问:
C# Project has auto generated classes, but what auto generated them?
I am working on a project that I was the original developer on, but over the last couple of years two other developers have maintained and upgraded the project.

There are now some class files inside with the following at the top:

```<code>//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1433
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=2.0.50727.1432.
//
</code>```

Any idea what could have generated these files? There are some issues inside one of them I want to clean up, but it says the changes might be overwritten.

答:
It's the XML Schema Definition Tool. What do you want to clean up?

Note that one of the operations performed by Xsd.exe is "XSD to classes", which is what generated your class files in question:

XSD to Classes

  Generates runtime classes from an XSD schema file. The generated classes can be used in conjunction with System.Xml.Serialization.XmlSerializer to read and write XML code that follows the schema.

You should be able to change the source XSD files, then re-run Xsd.exe in order to change the output while maintaining compatibility with the exe itself.

ContentLicense: CC BY-SA 2.5

Body:
I am working on a project that I was the original developer on, but over the last couple of years two other developers have maintained and upgraded the project.

There are now some class files inside with the following at the top:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.1433
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

//
// This source code was auto-generated by xsd, Version=2.0.50727.1432.
//

Any idea what could have generated these files? There are some issues inside one of them I want to clean up, but it says the changes might be overwritten.


问:
Compile errors for iOS app from Flutter/IntelliJ editor?
I'm receiving the following errors when attempting to compile my Flutter app and test on an iOS simulator.  I'm intermediate in Swift, but completely new to this type of IDE and log file info.  Please explain what these mean and how to correct them.

```<code>Error launching application on iPhone 6s.
    While building module 'Flutter' imported from /Users/Macbook/my_new_app/ios/Runner/main.m:2:
    In file included from <module-includes>:1:
    In file included from /Users/Macbook/my_new_app/ios/Flutter/Flutter.framework/Headers/Flutter.h:8:
    In file included from /Users/Macbook/my_new_app/ios/Flutter/Flutter.framework/Headers/FlutterAppDelegate.h:11:
    /Users/Macbook/my_new_app/ios/Flutter/Flutter.framework/Headers/FlutterPlugin.h:103:35: error: no type or protocol named 'UIApplicationOpenURLOptionsKey'
                options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options;
                                      ^
    1 error generated.
    /Users/Macbook/my_new_app/ios/Runner/main.m:2:9: fatal error: could not build module 'Flutter'
    #import <Flutter/Flutter.h>
     ~~~~~~~^
    2 errors generated.

    CompileC /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/AppDelegate.o Runner/AppDelegate.m normal arm64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
        cd /Users/Macbook/my_new_app/ios
        export LANG=en_US.US-ASCII
        export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/Users/Macbook/.rvm/gems/ruby-2.3.0/bin:/Users/Macbook/.rvm/gems/ruby-2.3.0@global/bin:/Users/Macbook/.rvm/rubies/ruby-2.3.0/bin:/Users/Macbook/.rbenv/shims:/Users/Macbook/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/mysql/bin:/Users/Macbook/.rvm/bin"
        /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c -arch arm64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu99 -fobjc-arc -fmodules -gmodules -fmodules-cache-path=/Users/Macbook/Library/Developer/Xcode/DerivedData/ModuleCache -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fbuild-session-file=/Users/Macbook/Library/Developer/Xcode/DerivedData/ModuleCache/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -Os -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wunreachable-code -Wno-implicit-atomic-properties -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-arc-repeated-use-of-weak -Wduplicate-method-match -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wno-deprecated-implementations -DNS_BLOCK_ASSERTIONS=1 -DOBJC_OLD_DISPATCH_PROTOTYPES=0 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.2.sdk -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -miphoneos-version-min=8.0 -g -fvisibility=hidden -Wno-sign-conversion -iquote /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Runner-generated-files.hmap -I/Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Runner-own-target-headers.hmap -I/Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Runner-all-target-headers.hmap -iquote /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Runner-project-headers.hmap -I/Users/Macbook/my_new_app/build/ios/Release-iphoneos/include -I/Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/DerivedSources/arm64 -I/Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/DerivedSources -F/Users/Macbook/my_new_app/build/ios/Release-iphoneos -F/Users/Macbook/my_new_app/ios/Flutter -MMD -MT dependencies -MF /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/AppDelegate.d --serialize-diagnostics /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/AppDelegate.dia -c /Users/Macbook/my_new_app/ios/Runner/AppDelegate.m -o /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/AppDelegate.o
</code>```

EDITED: Here is my flutter doctor output....

```<code>Macbooks-MacBook-Pro:myApp Macbook$ flutter doctor
[✓] Flutter (on Mac OS X 10.10.5 14F2109, locale en, channel alpha)
    • Flutter at /Users/Macbook/flutter
    • Framework revision d36e2f6191 (12 days ago), 2017-06-21 15:09:10 -0700
    • Engine revision b0dee695ec
    • Tools Dart version 1.24.0-dev.6.7

[✓] Android toolchain - develop for Android devices (Android SDK 23.0.1)
    • Android SDK at /Users/Macbook/Library/Android/sdk
    • Platform android-23, build-tools 23.0.1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_112-release-b06)

[✓] iOS toolchain - develop for iOS devices (Xcode 7.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 7.2.1, Build version 7C1002
    • ios-deploy 1.9.1
    • CocoaPods version 1.0.1

[✓] Android Studio (version 2.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Gradle version 3.2
    • Java version OpenJDK Runtime Environment (build 1.8.0_112-release-b06)

[✓] IntelliJ IDEA Community Edition (version 2017.1.4)
    • Flutter plugin version 15.0
    • Dart plugin version 171.4694.29

[✓] Connected devices
    • Apple TV 1080p                            • 7C95B021-841D-48CD-A6DA-2011CF5A6CBA • ios • iOS 9.1
    • iPad 2                                    • AD0A6D3D-98A2-43DA-8E15-9833077B256C • ios • iOS 9.2
    • iPad Air                                  • C3439A2D-7DB3-45A6-B00D-8B46F8CBBA99 • ios • iOS 9.2
    • iPad Air 2                                • 55CA03BB-398D-4029-8CD0-E0707E631F72 • ios • iOS 9.2
    • iPad Pro                                  • 9C658F47-2DBB-4323-B7C9-13502CCA6059 • ios • iOS 9.2
    • iPad Retina                               • E6232812-DD80-4B0D-8065-AD3A813E3344 • ios • iOS 9.2
    • iPhone 4s                                 • 5E59506E-AB09-4157-9375-566898437500 • ios • iOS 9.2
    • iPhone 5                                  • C368E301-AAB2-4A83-B513-8AFE1B9F6DCF • ios • iOS 9.2
    • iPhone 5s                                 • A77EDD0A-8BAC-4AC9-87DC-1D40BF4192A6 • ios • iOS 9.2
    • iPhone 6                                  • 1D4828BC-13D2-44A5-B4B9-74B1D5E7BED2 • ios • iOS 9.2
    • iPhone 6 Plus                             • 7E81F4BA-05F8-4204-BE53-38D19EC42ADF • ios • iOS 9.2
    • iPhone 6s                                 • 55766E4F-1DEB-4F98-B5FA-B3AFE959A73C • ios • iOS 9.2
    • iPhone 6s (9.2) + Apple Watch - 38mm      • 8C33DFE6-E0E3-47A1-AFAC-71820A35CDF5 • ios • iOS 2.1
    • iPhone 6s Plus                            • C10FB8C8-8213-4000-8B9E-C5CB1EA0A206 • ios • iOS 9.2
    • iPhone 6s Plus (9.2) + Apple Watch - 42mm • EBFBB3CF-77C3-4227-9E58-549EF5B3BACF • ios • iOS 2.1
    • iPhone 6s                                 • 55766E4F-1DEB-4F98-B5FA-B3AFE959A73C • ios • iOS 9.2 (simulator)

Macbooks-MacBook-Pro:myApp Macbook$
</code>```

答: I had this same error. I updated OSX to Sierra 10.12.5 and Xcode to 8.3.3 and that resolved.</p>

Body:
I'm receiving the following errors when attempting to compile my Flutter app and test on an iOS simulator.  I'm intermediate in Swift, but completely new to this type of IDE and log file info.  Please explain what these mean and how to correct them.

Error launching application on iPhone 6s.
    While building module 'Flutter' imported from /Users/Macbook/my_new_app/ios/Runner/main.m:2:
    In file included from <module-includes>:1:
    In file included from /Users/Macbook/my_new_app/ios/Flutter/Flutter.framework/Headers/Flutter.h:8:
    In file included from /Users/Macbook/my_new_app/ios/Flutter/Flutter.framework/Headers/FlutterAppDelegate.h:11:
    /Users/Macbook/my_new_app/ios/Flutter/Flutter.framework/Headers/FlutterPlugin.h:103:35: error: no type or protocol named 'UIApplicationOpenURLOptionsKey'
                options:(NSDictionary<UIApplicationOpenURLOptionsKey, id>*)options;
                                      ^
    1 error generated.
    /Users/Macbook/my_new_app/ios/Runner/main.m:2:9: fatal error: could not build module 'Flutter'
    #import <Flutter/Flutter.h>
     ~~~~~~~^
    2 errors generated.

    CompileC /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/AppDelegate.o Runner/AppDelegate.m normal arm64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
        cd /Users/Macbook/my_new_app/ios
        export LANG=en_US.US-ASCII
        export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/Users/Macbook/.rvm/gems/ruby-2.3.0/bin:/Users/Macbook/.rvm/gems/ruby-2.3.0@global/bin:/Users/Macbook/.rvm/rubies/ruby-2.3.0/bin:/Users/Macbook/.rbenv/shims:/Users/Macbook/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/mysql/bin:/Users/Macbook/.rvm/bin"
        /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c -arch arm64 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu99 -fobjc-arc -fmodules -gmodules -fmodules-cache-path=/Users/Macbook/Library/Developer/Xcode/DerivedData/ModuleCache -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fbuild-session-file=/Users/Macbook/Library/Developer/Xcode/DerivedData/ModuleCache/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -Os -fno-common -Wno-missing-field-initializers -Wno-missing-prototypes -Werror=return-type -Wunreachable-code -Wno-implicit-atomic-properties -Werror=deprecated-objc-isa-usage -Werror=objc-root-class -Wno-arc-repeated-use-of-weak -Wduplicate-method-match -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wconditional-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wno-deprecated-implementations -DNS_BLOCK_ASSERTIONS=1 -DOBJC_OLD_DISPATCH_PROTOTYPES=0 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.2.sdk -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -miphoneos-version-min=8.0 -g -fvisibility=hidden -Wno-sign-conversion -iquote /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Runner-generated-files.hmap -I/Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Runner-own-target-headers.hmap -I/Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Runner-all-target-headers.hmap -iquote /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Runner-project-headers.hmap -I/Users/Macbook/my_new_app/build/ios/Release-iphoneos/include -I/Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/DerivedSources/arm64 -I/Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/DerivedSources -F/Users/Macbook/my_new_app/build/ios/Release-iphoneos -F/Users/Macbook/my_new_app/ios/Flutter -MMD -MT dependencies -MF /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/AppDelegate.d --serialize-diagnostics /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/AppDelegate.dia -c /Users/Macbook/my_new_app/ios/Runner/AppDelegate.m -o /Users/Macbook/Library/Developer/Xcode/DerivedData/Runner-hhjpdwyksnzmieabrmcsddedroig/Build/Intermediates/Runner.build/Release-iphoneos/Runner.build/Objects-normal/arm64/AppDelegate.o

EDITED: Here is my flutter doctor output....

Macbooks-MacBook-Pro:myApp Macbook$ flutter doctor
[✓] Flutter (on Mac OS X 10.10.5 14F2109, locale en, channel alpha)
    • Flutter at /Users/Macbook/flutter
    • Framework revision d36e2f6191 (12 days ago), 2017-06-21 15:09:10 -0700
    • Engine revision b0dee695ec
    • Tools Dart version 1.24.0-dev.6.7

[✓] Android toolchain - develop for Android devices (Android SDK 23.0.1)
    • Android SDK at /Users/Macbook/Library/Android/sdk
    • Platform android-23, build-tools 23.0.1
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_112-release-b06)

[✓] iOS toolchain - develop for iOS devices (Xcode 7.2.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 7.2.1, Build version 7C1002
    • ios-deploy 1.9.1
    • CocoaPods version 1.0.1

[✓] Android Studio (version 2.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Gradle version 3.2
    • Java version OpenJDK Runtime Environment (build 1.8.0_112-release-b06)

[✓] IntelliJ IDEA Community Edition (version 2017.1.4)
    • Flutter plugin version 15.0
    • Dart plugin version 171.4694.29

[✓] Connected devices
    • Apple TV 1080p                            • 7C95B021-841D-48CD-A6DA-2011CF5A6CBA • ios • iOS 9.1
    • iPad 2                                    • AD0A6D3D-98A2-43DA-8E15-9833077B256C • ios • iOS 9.2
    • iPad Air                                  • C3439A2D-7DB3-45A6-B00D-8B46F8CBBA99 • ios • iOS 9.2
    • iPad Air 2                                • 55CA03BB-398D-4029-8CD0-E0707E631F72 • ios • iOS 9.2
    • iPad Pro                                  • 9C658F47-2DBB-4323-B7C9-13502CCA6059 • ios • iOS 9.2
    • iPad Retina                               • E6232812-DD80-4B0D-8065-AD3A813E3344 • ios • iOS 9.2
    • iPhone 4s                                 • 5E59506E-AB09-4157-9375-566898437500 • ios • iOS 9.2
    • iPhone 5                                  • C368E301-AAB2-4A83-B513-8AFE1B9F6DCF • ios • iOS 9.2
    • iPhone 5s                                 • A77EDD0A-8BAC-4AC9-87DC-1D40BF4192A6 • ios • iOS 9.2
    • iPhone 6                                  • 1D4828BC-13D2-44A5-B4B9-74B1D5E7BED2 • ios • iOS 9.2
    • iPhone 6 Plus                             • 7E81F4BA-05F8-4204-BE53-38D19EC42ADF • ios • iOS 9.2
    • iPhone 6s                                 • 55766E4F-1DEB-4F98-B5FA-B3AFE959A73C • ios • iOS 9.2
    • iPhone 6s (9.2) + Apple Watch - 38mm      • 8C33DFE6-E0E3-47A1-AFAC-71820A35CDF5 • ios • iOS 2.1
    • iPhone 6s Plus                            • C10FB8C8-8213-4000-8B9E-C5CB1EA0A206 • ios • iOS 9.2
    • iPhone 6s Plus (9.2) + Apple Watch - 42mm • EBFBB3CF-77C3-4227-9E58-549EF5B3BACF • ios • iOS 2.1
    • iPhone 6s                                 • 55766E4F-1DEB-4F98-B5FA-B3AFE959A73C • ios • iOS 9.2 (simulator)

Macbooks-MacBook-Pro:myApp Macbook$


问:
Eliminating IF statement from this code
I have this C function which basically takes the input from the user and saves it in a static char[]. Then it checks whether it is empty. If it is empty then it prints an error, else appends a file extension to it. Here's the piece of code I'm concerned about:

const char* text_entry(){
    char c;
    while((c=getchar())!='\n' && c!=EOF);
    static char input[20];
    fgets(input, sizeof(input),stdin);
    input[strcspn(input,"\n")]=0;
    if(strlen(input)>0){
        strncat(input, ".txt",4);
        return input;
    }
    printf("Error! no text entered!");
    return NULL;
}
```

My concern is that I want to remove the IF statement from it, making it more DRY. How can I do that?

答:
The "DRY" is in the usage of strcspn(), strlen() and strncat().  You can avoid them by

```<code>size_t l = strcspn(input, "\n");
bool ok = false;

if (l == 0) {
    fprintf(stderr, "error: too short\n");
} else if (l > sizeof input - sizeof(".txt")) {
    fprintf(stderr, "error: too long\n");
} else {
    strcpy(input + l, ".txt");
    ok = true;
}

return ok ? input : NULL;
</code>```

Title: Eliminating IF statement from this code

Body:
I have this C function which basically takes the input from the user and saves it in a static char[]. Then it checks whether it is empty. If it is empty then it prints an error, else appends a file extension to it. Here's the piece of code I'm concerned about:

const char* text_entry(){
    char c;
    while((c=getchar())!='\n' && c!=EOF);
    static char input[20];
    fgets(input, sizeof(input),stdin);
    input[strcspn(input,"\n")]=0;
    if(strlen(input)>0){
        strncat(input, ".txt",4);
        return input;
    }
    printf("Error! no text entered!");
    return NULL;
}

My concern is that I want to remove the IF statement from it, making it more DRY. How can I do that?

Body:
The "DRY" is in the usage of strcspn(), strlen() and strncat().  You can avoid them by

size_t l = strcspn(input, "\n");
bool ok = false;

if (l == 0) {
    fprintf(stderr, "error: too short\n");
} else if (l > sizeof input - sizeof(".txt")) {
    fprintf(stderr, "error: too long\n");
} else {
    strcpy(input + l, ".txt");
    ok = true;
}

return ok ? input : NULL;


问:
Tableview.reloadData doesn't work
I have two controllers and I'd like to pass datas between them:
This is the first controller, a tableviewcontroller.

```<code>class BooksVC: UITableViewController {

var books: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Books"

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = books[indexPath.row]

    return cell
}
}
</code>```

And this is the second controller, a viewcontroller

```<code>class AddController: UIViewController {
@IBOutlet weak var inputField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func done(_ sender: Any) {
    let myVC = storyboard?.instantiateViewController(withIdentifier: "BooksVC") as! BooksVC
    myVC.books.append(inputField.text!)
    myVC.tableView.reloadData()

    dismiss(animated: true, completion: nil)
}
</code>```

}

Reloaddata doesn't work, can you help me I would be very glad.

答:
You need to have a reference to the first view controller to do what you need.
You can do something like this:

```<code>class AddController: UIViewController {
....
weak var booksVC: BooksVC?

@IBAction func done(_ sender: Any) {
    booksVC.books.append(inputField.text!)
    booksVC.tableView.reloadData()

    dismiss(animated: true, completion: nil)
}

}
</code>```

And when you instatiate an AddController, you need to pass a reference of your BooksVC. Something like this:

```<code>addController.booksVC = self
</code>```

Title: Tableview.reloadData doesn't work

Body:
I have two controllers and I'd like to pass datas between them:
This is the first controller, a tableviewcontroller.

class BooksVC: UITableViewController {

var books: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Books"

}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = books[indexPath.row]

    return cell
}
}

And this is the second controller, a viewcontroller

class AddController: UIViewController {
@IBOutlet weak var inputField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

}

@IBAction func done(_ sender: Any) {
    let myVC = storyboard?.instantiateViewController(withIdentifier: "BooksVC") as! BooksVC
    myVC.books.append(inputField.text!)
    myVC.tableView.reloadData()

    dismiss(animated: true, completion: nil)
}

}

Reloaddata doesn't work, can you help me I would be very glad.

Body:
You need to have a reference to the first view controller to do what you need.
You can do something like this:

class AddController: UIViewController {
....
weak var booksVC: BooksVC?

@IBAction func done(_ sender: Any) {
    booksVC.books.append(inputField.text!)
    booksVC.tableView.reloadData()

    dismiss(animated: true, completion: nil)
}

}

And when you instatiate an AddController, you need to pass a reference of your BooksVC. Something like this:

addController.booksVC = self


问:
Pyside / Pyqt Opening new windows from a window (Event loop is already running)
I am trying to create a UI that will act as a hub to launch all the other tools that have been created.  The problem is that if i try to launch the UI from the toolshub UI, it won't let me because the event loop is already running.  I know that I cannot do this APP = QtGui.QApplication(sys.argv) and APP.exec_() when launching the new window because the event loop is already running when I did that for the toolshub UI.  But I can't figure out how to do it another way.

Here is an example code for one of the tools, works launching on its own.

```<code>global APP
APP = None

class toolwindow(QtGui.QDialog):

    def __init__(self, parent=None):
        init_app()
        super(toolwindow, self).__init__(parent)
        self.setWindowTitle('tool')
        self.setMinimumSize(QtCore.QSize(500, 600))
        self.setMaximumSize(QtCore.QSize(500, 600))
        self.create_ui()

    def create_ui(self):
        code goes here

    def closeEvent(self, event):
        QtGui.QDialog.closeEvent(self, event)
        return

def init_app():
    global APP
    APP = QtGui.QApplication.instance()
    if not APP:
        APP = QtGui.QApplication(sys.argv)
    return

def start_ui():
    win= toolwindow()
    win.show()
    APP.exec_()

if __name__ == '__main__':
    start_ui()
global APP
APP = None
</code>```

Now here is the code for the toolshub ui.  These are both separate scripts.  In toolshub i am importing the tool above.

```<code>import tool
LOGGER = logging.getLogger(__name__)
global APP
APP = None

class toolsHub(QtGui.QDialog):

    def __init__(self, parent=None):
        init_app()
        super(toolsHub, self).__init__(parent)
        self.setWindowTitle('Tools Launcher')
        self.setSizeGripEnabled(False)
        self.setMinimumSize(QtCore.QSize(300, 200))
        self.setMaximumSize(QtCore.QSize(300, 200))
        self.create_layouts()

    def create_layouts(self):
        master_layout = QtGui.QVBoxLayout()
        self.setLayout(master_layout)
        self.input_widgets()
        grid_layout = QtGui.QGridLayout()
        grid_layout.addWidget(self.env_creator, 0, 0)
        grid_layout.addWidget(self.p4dl, 1, 0)
        master_layout.addLayout(grid_layout)

    def input_widgets(self):
        self.tool_button= QtGui.QPushButton('launch tool')
        self.tool_button.clicked.connect(self.launch_tool)

    def launch_tool(self):
        tool.start_ui()

    def closeEvent(self, event):
        QtGui.QDialog.closeEvent(self, event)
        return

def init_app():
    global APP
    APP = QtGui.QApplication.instance()
    if not APP:
        APP = QtGui.QApplication(sys.argv)
    return

def start_ui():
    toolui = toolsHub()
    toolui.show()
    APP.exec_()

if __name__ == '__main__':
    start_ui()
</code>```

So how do write and structure these so that I can open the tool UI from the toolshub UI?  I am guessing the code i have to change is the tool UI, I know i have to take out APP = QtGui.QApplication(sys.argv) and APP.exec_(), but not sure what to do to launch it.

Thanks

答:
There should only be one instance of QApplication and this should be created before creating any widget, so it is unnecessary to instantiate it in each module.

In order for the QDialog to be displayed properly you must execute its exec_()

tool.py:

```<code>[...]
def start_ui():
    win= toolwindow()
    win.exec_()
</code>```

complete code:

tool.py

```<code>from PySide import QtGui, QtCore

APP = None

class toolwindow(QtGui.QDialog):

    def __init__(self, parent=None):
        init_app()
        super(toolwindow, self).__init__(parent)
        self.setWindowTitle('tool')
        self.setMinimumSize(QtCore.QSize(500, 600))
        self.setMaximumSize(QtCore.QSize(500, 600))
        self.create_ui()

    def create_ui(self):
        pass
    def closeEvent(self, event):
        QtGui.QDialog.closeEvent(self, event)
        return

def init_app():
    global APP
    APP = QtGui.QApplication.instance()
    if not APP:
        APP = QtGui.QApplication(sys.argv)
    return

def start_ui():
    win= toolwindow()
    win.exec_()

if __name__ == '__main__':
    start_ui()
</code>```

main.py

```<code>from PySide import QtGui, QtCore
import tool
import logging
import sys

LOGGER = logging.getLogger(__name__)
APP = None

class toolsHub(QtGui.QDialog):

    def __init__(self, parent=None):
        init_app()
        super(toolsHub, self).__init__(parent)
        self.setWindowTitle('Tools Launcher')
        self.setSizeGripEnabled(False)
        self.setMinimumSize(QtCore.QSize(300, 200))
        self.setMaximumSize(QtCore.QSize(300, 200))
        self.create_layouts()

    def create_layouts(self):
        master_layout = QtGui.QVBoxLayout()
        self.setLayout(master_layout)
        self.input_widgets()
        grid_layout = QtGui.QGridLayout()
        grid_layout.addWidget(QtGui.QPushButton(), 0, 0)
        grid_layout.addWidget(QtGui.QPushButton(), 1, 0)
        master_layout.addLayout(grid_layout)

    def input_widgets(self):
        self.tool_button= QtGui.QPushButton('launch tool')
        self.tool_button.clicked.connect(self.launch_tool)
        self.layout().addWidget(self.tool_button)

    def launch_tool(self):
        tool.start_ui()

    def closeEvent(self, event):
        QtGui.QDialog.closeEvent(self, event)

def init_app():
    global APP
    APP = QtGui.QApplication.instance()
    if not APP:
        APP = QtGui.QApplication(sys.argv)
    return

def start_ui():
    toolui = toolsHub()
    toolui.show()
    APP.exec_()

if __name__ == '__main__':
    start_ui()
</code>```

Body:
I am trying to create a UI that will act as a hub to launch all the other tools that have been created.  The problem is that if i try to launch the UI from the toolshub UI, it won't let me because the event loop is already running.  I know that I cannot do this APP = QtGui.QApplication(sys.argv) and APP.exec_() when launching the new window because the event loop is already running when I did that for the toolshub UI.  But I can't figure out how to do it another way.

Here is an example code for one of the tools, works launching on its own.

global APP
APP = None

class toolwindow(QtGui.QDialog):

    def __init__(self, parent=None):
        init_app()
        super(toolwindow, self).__init__(parent)
        self.setWindowTitle('tool')
        self.setMinimumSize(QtCore.QSize(500, 600))
        self.setMaximumSize(QtCore.QSize(500, 600))
        self.create_ui()

    def create_ui(self):
        code goes here

    def closeEvent(self, event):
        QtGui.QDialog.closeEvent(self, event)
        return

def init_app():
    global APP
    APP = QtGui.QApplication.instance()
    if not APP:
        APP = QtGui.QApplication(sys.argv)
    return

def start_ui():
    win= toolwindow()
    win.show()
    APP.exec_()

if __name__ == '__main__':
    start_ui()
global APP
APP = None

Now here is the code for the toolshub ui.  These are both separate scripts.  In toolshub i am importing the tool above.

import tool
LOGGER = logging.getLogger(__name__)
global APP
APP = None

class toolsHub(QtGui.QDialog):

    def __init__(self, parent=None):
        init_app()
        super(toolsHub, self).__init__(parent)
        self.setWindowTitle('Tools Launcher')
        self.setSizeGripEnabled(False)
        self.setMinimumSize(QtCore.QSize(300, 200))
        self.setMaximumSize(QtCore.QSize(300, 200))
        self.create_layouts()

    def create_layouts(self):
        master_layout = QtGui.QVBoxLayout()
        self.setLayout(master_layout)
        self.input_widgets()
        grid_layout = QtGui.QGridLayout()
        grid_layout.addWidget(self.env_creator, 0, 0)
        grid_layout.addWidget(self.p4dl, 1, 0)
        master_layout.addLayout(grid_layout)

    def input_widgets(self):
        self.tool_button= QtGui.QPushButton('launch tool')
        self.tool_button.clicked.connect(self.launch_tool)

    def launch_tool(self):
        tool.start_ui()

    def closeEvent(self, event):
        QtGui.QDialog.closeEvent(self, event)
        return

def init_app():
    global APP
    APP = QtGui.QApplication.instance()
    if not APP:
        APP = QtGui.QApplication(sys.argv)
    return

def start_ui():
    toolui = toolsHub()
    toolui.show()
    APP.exec_()

if __name__ == '__main__':
    start_ui()

So how do write and structure these so that I can open the tool UI from the toolshub UI?  I am guessing the code i have to change is the tool UI, I know i have to take out APP = QtGui.QApplication(sys.argv) and APP.exec_(), but not sure what to do to launch it.

Thanks

Body:
There should only be one instance of QApplication and this should be created before creating any widget, so it is unnecessary to instantiate it in each module.

In order for the QDialog to be displayed properly you must execute its exec_()

tool.py:

[...]
def start_ui():
    win= toolwindow()
    win.exec_()

complete code:

tool.py

from PySide import QtGui, QtCore

APP = None

class toolwindow(QtGui.QDialog):

    def __init__(self, parent=None):
        init_app()
        super(toolwindow, self).__init__(parent)
        self.setWindowTitle('tool')
        self.setMinimumSize(QtCore.QSize(500, 600))
        self.setMaximumSize(QtCore.QSize(500, 600))
        self.create_ui()

    def create_ui(self):
        pass
    def closeEvent(self, event):
        QtGui.QDialog.closeEvent(self, event)
        return

def init_app():
    global APP
    APP = QtGui.QApplication.instance()
    if not APP:
        APP = QtGui.QApplication(sys.argv)
    return

def start_ui():
    win= toolwindow()
    win.exec_()

if __name__ == '__main__':
    start_ui()

main.py

from PySide import QtGui, QtCore
import tool
import logging
import sys

LOGGER = logging.getLogger(__name__)
APP = None

class toolsHub(QtGui.QDialog):

    def __init__(self, parent=None):
        init_app()
        super(toolsHub, self).__init__(parent)
        self.setWindowTitle('Tools Launcher')
        self.setSizeGripEnabled(False)
        self.setMinimumSize(QtCore.QSize(300, 200))
        self.setMaximumSize(QtCore.QSize(300, 200))
        self.create_layouts()

    def create_layouts(self):
        master_layout = QtGui.QVBoxLayout()
        self.setLayout(master_layout)
        self.input_widgets()
        grid_layout = QtGui.QGridLayout()
        grid_layout.addWidget(QtGui.QPushButton(), 0, 0)
        grid_layout.addWidget(QtGui.QPushButton(), 1, 0)
        master_layout.addLayout(grid_layout)

    def input_widgets(self):
        self.tool_button= QtGui.QPushButton('launch tool')
        self.tool_button.clicked.connect(self.launch_tool)
        self.layout().addWidget(self.tool_button)

    def launch_tool(self):
        tool.start_ui()

    def closeEvent(self, event):
        QtGui.QDialog.closeEvent(self, event)

def init_app():
    global APP
    APP = QtGui.QApplication.instance()
    if not APP:
        APP = QtGui.QApplication(sys.argv)
    return

def start_ui():
    toolui = toolsHub()
    toolui.show()
    APP.exec_()

if __name__ == '__main__':
    start_ui()


问:
zsh : Testing the existence of a variable via indirect reference
If I want to know, whether variable v exists in zsh, I can use ${+v}. Example:

```<code>u=xxx
v=
print ${+u} ${+v} ${+w}
</code>```

outputs 1 1 0.

If I want to access the content of a variable, where I have the NAME of it stored in variable v, I can do it with ${(P)v}. Example:

```<code>a=xxx
b=a
print ${(P)b}
</code>```

outputs xxx.

Now I would like to combine the two: Testing whether a variable exists, but the name of the variable is stored in another variable. How can I do this? Example:

```<code>r=XXX
p=r
q=s
</code>```

Here is my approach which does NOT work:

```<code>print ${+${(P)p}}  # Expect 1, because $p is r and r exists.
print ${+${(P)q}}  # Expect 0, because $q is s and s does not exist
</code>```

However, I get the error message zsh: bad substitution.

Is there a way I can achieve my goal without reverting to eval?

答:
```<code>print ${(P)+p}
print ${(P)+q}
</code>```

The opening parenthesis of of a Parameter Expansion Flag needs to follow immediately after the opening brace. Also, it is not necessary to explicitly substitute p or q as (P) takes care of that. Nevertheless, ${(P)+${p}} and ${(P)+${q}} would also work.

Body:
If I want to know, whether variable v exists in zsh, I can use ${+v}. Example:

u=xxx
v=
print ${+u} ${+v} ${+w}

outputs 1 1 0.

If I want to access the content of a variable, where I have the NAME of it stored in variable v, I can do it with ${(P)v}. Example:

a=xxx
b=a
print ${(P)b}

outputs xxx.

Now I would like to combine the two: Testing whether a variable exists, but the name of the variable is stored in another variable. How can I do this? Example:

r=XXX
p=r
q=s

Here is my approach which does NOT work:

print ${+${(P)p}}  # Expect 1, because $p is r and r exists.
print ${+${(P)q}}  # Expect 0, because $q is s and s does not exist

However, I get the error message zsh: bad substitution.

Is there a way I can achieve my goal without reverting to eval?

Body:
print ${(P)+p}
print ${(P)+q}

The opening parenthesis of of a Parameter Expansion Flag needs to follow immediately after the opening brace. Also, it is not necessary to explicitly substitute p or q as (P) takes care of that. Nevertheless, ${(P)+${p}} and ${(P)+${q}} would also work.


问:
Java : "xx".equals(variable) better than variable.equals("xx") , TRUE?
I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.

Recomendation:

```<code>String variable;

"xx".equals(variable) // OK

variable.equals("xx") //Not recomended
</code>```

Because prevents appearance of NullPointerException that are not controlled

Is this true?

答:
As a side note, here is a design pattern where this code recommendation might not make any difference, since the String (i.e. Optional<String>) is never null because of the .isPresent() call from the design pattern:

```<code>Optional<String> gender = Optional.of("MALE");
if (gender.isPresent()) {
    System.out.println("Value available.");
} else {
    System.out.println("Value not available.");
}
gender.ifPresent(g -> System.out.println("Consumer: equals: " + g.equals("whatever")));
</code>```

Body:
I'm reviewing a manual of best practices and recommendation coding java I think is doubtful.

Recomendation:

String variable;

"xx".equals(variable) // OK

variable.equals("xx") //Not recomended

Because prevents appearance of NullPointerException that are not controlled

Is this true?

Body:
As a side note, here is a design pattern where this code recommendation might not make any difference, since the String (i.e. Optional<String>) is never null because of the .isPresent() call from the design pattern:

Optional<String> gender = Optional.of("MALE");
if (gender.isPresent()) {
    System.out.println("Value available.");
} else {
    System.out.println("Value not available.");
}
gender.ifPresent(g -> System.out.println("Consumer: equals: " + g.equals("whatever")));


问:
Swift Real-Time Multiplayer Online Game
everyone!

I'm in the process of making a real-time multiplayer game. Picture a castle game with two players, where each player has a castle to defend. The idea is that each player has their own iPad, and can shore up defenses, send out soldiers, and shoot projectiles using their own device.

Obviously, these changes should be reflected on both devices simultaneously (e.g. if player 1 shoots a projectile, it's motion should be animated on both screens at once).

My question is, what is the best way to accomplish that? Assume I am proficient at making single-player apps in Swift with SpriteKit, but know nothing whatsoever about multiplayer online programming. Thank you very much for your time!

P.S. Would it be useful to learn server-side swift?

P.P.S. I have been researching this topic for the past week, and haven't found what I need. Any help would be appreciated! Everyone who asks a question online seems to already know certain things that I do not.

答:
You have a lot of learning to do about multiplayer before you dive into making your own game

The idea is that you have a server, hosted on either a machine that you own or some web service like AWS

In that server, you have some sort of database, and some sort of game server running on a port.

There are 2 types of transport protocols, TCP and UDP. You can look those up, but for your proposed game TCP seems like what you need

You swift application connects to the server and sends all data do it about what the player does. The server sends a response with the current state of the game.

The server simulates all game logic. Think of it as the code you would actually write to make the game work in a single player game, except on a server so players can't hack the client and cheat

Think of the client as a dumb terminal just sending button clicks to the server and receiving updates about the game state. It should not handle any game logic other than rendering and prediction for fluidity

Go to the game development stack exchange for more info, or just do a google search on multiplayer video game programming

Swift probably isn't the best choice for your server. I personally use Netty in Java for my server side game code.

Title: Swift Real-Time Multiplayer Online Game


问:
How can I convert a column vector to the diagonal of a matrix?
I have a column vector that I would like to convert to a diagonal matrix.

That is I have the vector v = (1,2,3) and want to turn it into:

[1, 0, 0]

[0, 2, 0]

[0, 0, 3]

How can I do this in Excel?  in R?

I don't care how I do it, I just need to get it done.  I know this is a simple question but I've been trying to figure this out for hours now.

(note: my vector is currently in a csv file)

Body:
In R you simply have to do:

> v<- c(1, 2, 3)
> diag(v)
     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    2    0
[3,]    0    0    3


问:
leaflet.draw not showing distance markup

Chrome V58

Windows 10

Leaflet 1.0.3

Leaflet-draw 0.4.9

As shown below, with leaflet 1.0 and leaflet draw 0.2.4 I was getting text distance for lines, and area for rectangles.

Now I only get the area for circles, but the others do not show anything. Is this just me, and why does the below no longer work?

(I.e. I no longer see the 1425.65 km as shown below).

```<code>function addDrawLayer() {
    var options = null
    var map = MAP.map
    var drawings = new L.FeatureGroup()
    MAP.drawLayer = drawings
    map.addLayer(drawings)

    options = {
        shapeOptions: {
            showArea: true,
            clickable: true
        },
        metric: true,
        edit: {
            featureGroup: drawings
        }
    }
    var drawControl = new L.Control.Draw(options)
    map.addControl(drawControl)
    map.on('draw:created', function (e) {
        var type = e.layerType
        var layer = e.layer
        if (type === 'marker') {
            layer.bindPopup('A popup!')
        }
        drawings.addLayer(layer)
    });
}
</code>```

答:
Leaflet.Draw Issue

There was a bug for 0.4.9 that has been patched to 0.4.10 - However, Leaflet.Draw does not work with Leaflet 1.1.0 yet and it appears there are still some issues with the distance markup.

Whilst, your options object is the improper schema. ShapeOptions are part of each draw item may have a shapeOption for that draw tool.

```<code>draw: polygon: {shapeOptions: {showArea: true} }
</code>```

JSFiddle

Body:
Chrome V58

Windows 10

Leaflet 1.0.3

Leaflet-draw 0.4.9

As shown below, with leaflet 1.0 and leaflet draw 0.2.4 I was getting text distance for lines, and area for rectangles.

Now I only get the area for circles, but the others do not show anything. Is this just me, and why does the below no longer work?

(I.e. I no longer see the 1425.65 km as shown below).

function addDrawLayer() {
    var options = null
    var map = MAP.map
    var drawings = new L.FeatureGroup()
    MAP.drawLayer = drawings
    map.addLayer(drawings)

    options = {
        shapeOptions: {
            showArea: true,
            clickable: true
        },
        metric: true,
        edit: {
            featureGroup: drawings
        }
    }
    var drawControl = new L.Control.Draw(options)
    map.addControl(drawControl)
    map.on('draw:created', function (e) {
        var type = e.layerType
        var layer = e.layer
        if (type === 'marker') {
            layer.bindPopup('A popup!')
        }
        drawings.addLayer(layer)
    });
}

Body:
Leaflet.Draw Issue

There was a bug for 0.4.9 that has been patched to 0.4.10 - However, Leaflet.Draw does not work with Leaflet 1.1.0 yet and it appears there are still some issues with the distance markup.

Whilst, your options object is the improper schema. ShapeOptions are part of each draw item may have a shapeOption for that draw tool.

draw: polygon: {shapeOptions: {showArea: true} }

JSFiddle


问:
Run an Android App
Can anyone kindly help me, please with this error?</p>

```<code>07-06 21:22:04.794 8489-8489/? D/dalvikvm: Late-enabling CheckJNI
07-06 21:22:04.944 8489-8489/? I/dalvikvm: Could not find method android.view.Window$Callback.onProvideKeyboardShortcuts, referenced from method android.support.v7.view.WindowCallbackWrapper.onProvideKeyboardShortcuts
07-06 21:22:04.944 8489-8489/? W/dalvikvm: VFY: unable to resolve interface method 15403: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
07-06 21:22:04.944 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
07-06 21:22:04.944 8489-8489/? W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
07-06 21:22:04.944 8489-8489/? I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
07-06 21:22:04.944 8489-8489/? W/dalvikvm: VFY: unable to resolve interface method 15405: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
07-06 21:22:04.944 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
07-06 21:22:04.944 8489-8489/? I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
07-06 21:22:04.944 8489-8489/? W/dalvikvm: VFY: unable to resolve interface method 15409: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
07-06 21:22:04.944 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
07-06 21:22:04.954 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 477: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
07-06 21:22:04.954 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
07-06 21:22:04.954 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 499: Landroid/content/res/TypedArray;.getType (I)I
07-06 21:22:04.954 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0008
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.Context.createDeviceProtectedStorageContext, referenced from method android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext
07-06 21:22:04.954 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 268: Landroid/content/Context;.createDeviceProtectedStorageContext ()Landroid/content/Context;
07-06 21:22:04.954 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getCodeCacheDir, referenced from method android.support.v4.content.ContextCompat.getCodeCacheDir
07-06 21:22:04.954 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 273: Landroid/content/Context;.getCodeCacheDir ()Ljava/io/File;
07-06 21:22:04.954 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getColor, referenced from method android.support.v4.content.ContextCompat.getColor
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 274: Landroid/content/Context;.getColor (I)I
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getColorStateList, referenced from method android.support.v4.content.ContextCompat.getColorStateList
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 275: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getDataDir, referenced from method android.support.v4.content.ContextCompat.getDataDir
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 277: Landroid/content/Context;.getDataDir ()Ljava/io/File;
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getDrawable, referenced from method android.support.v4.content.ContextCompat.getDrawable
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 278: Landroid/content/Context;.getDrawable (I)Landroid/graphics/drawable/Drawable;
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getNoBackupFilesDir, referenced from method android.support.v4.content.ContextCompat.getNoBackupFilesDir
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 285: Landroid/content/Context;.getNoBackupFilesDir ()Ljava/io/File;
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.isDeviceProtectedStorage, referenced from method android.support.v4.content.ContextCompat.isDeviceProtectedStorage
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 298: Landroid/content/Context;.isDeviceProtectedStorage ()Z
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.984 8489-8489/? D/AndroidRuntime: Shutting down VM
07-06 21:22:04.984 8489-8489/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692c08)
07-06 21:22:04.994 8489-8489/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.lenovo.app, PID: 8489
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lenovo.app/com.example.lenovo.app.MainActivity}: java.lang.IllegalStateException: This app has been built with an incorrect configuration. Please configure your build for VectorDrawableCompat.
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                     at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:146)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                     at dalvik.system.NativeStart.main(Native Method)
                                                  Caused by: java.lang.IllegalStateException: This app has been built with an incorrect configuration. Please configure your build for VectorDrawableCompat.
                                                     at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:713)
                                                     at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:194)
                                                     at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:81)
                                                     at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:129)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:152)
                                                     at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
                                                     at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
                                                     at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518)
                                                     at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:70)
                                                     at com.example.lenovo.app.MainActivity.onCreate(MainActivity.java:10)
                                                     at android.app.Activity.performCreate(Activity.java:5322)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2303)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                     at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:146)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                     at dalvik.system.NativeStart.main(Native Method)
07-06 21:22:07.814 8489-8489/? I/Process: Sending signal. PID: 8489 SIG: 9
</code>```

答:
add this code to your app.gradle :</p>

```<code>android {
//....something

defaultConfig {
    generatedDensities = []
}

aaptOptions {
    additionalParameters "--no-version-vectors"
}
</code>```

Title: Run an Android App

Body:
Can anyone kindly help me, please with this error?

07-06 21:22:04.794 8489-8489/? D/dalvikvm: Late-enabling CheckJNI
07-06 21:22:04.944 8489-8489/? I/dalvikvm: Could not find method android.view.Window$Callback.onProvideKeyboardShortcuts, referenced from method android.support.v7.view.WindowCallbackWrapper.onProvideKeyboardShortcuts
07-06 21:22:04.944 8489-8489/? W/dalvikvm: VFY: unable to resolve interface method 15403: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
07-06 21:22:04.944 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
07-06 21:22:04.944 8489-8489/? W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
07-06 21:22:04.944 8489-8489/? I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
07-06 21:22:04.944 8489-8489/? W/dalvikvm: VFY: unable to resolve interface method 15405: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
07-06 21:22:04.944 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
07-06 21:22:04.944 8489-8489/? I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
07-06 21:22:04.944 8489-8489/? W/dalvikvm: VFY: unable to resolve interface method 15409: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
07-06 21:22:04.944 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
07-06 21:22:04.954 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 477: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
07-06 21:22:04.954 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
07-06 21:22:04.954 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 499: Landroid/content/res/TypedArray;.getType (I)I
07-06 21:22:04.954 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0008
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.Context.createDeviceProtectedStorageContext, referenced from method android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext
07-06 21:22:04.954 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 268: Landroid/content/Context;.createDeviceProtectedStorageContext ()Landroid/content/Context;
07-06 21:22:04.954 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getCodeCacheDir, referenced from method android.support.v4.content.ContextCompat.getCodeCacheDir
07-06 21:22:04.954 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 273: Landroid/content/Context;.getCodeCacheDir ()Ljava/io/File;
07-06 21:22:04.954 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.954 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getColor, referenced from method android.support.v4.content.ContextCompat.getColor
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 274: Landroid/content/Context;.getColor (I)I
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getColorStateList, referenced from method android.support.v4.content.ContextCompat.getColorStateList
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 275: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getDataDir, referenced from method android.support.v4.content.ContextCompat.getDataDir
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 277: Landroid/content/Context;.getDataDir ()Ljava/io/File;
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getDrawable, referenced from method android.support.v4.content.ContextCompat.getDrawable
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 278: Landroid/content/Context;.getDrawable (I)Landroid/graphics/drawable/Drawable;
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.getNoBackupFilesDir, referenced from method android.support.v4.content.ContextCompat.getNoBackupFilesDir
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 285: Landroid/content/Context;.getNoBackupFilesDir ()Ljava/io/File;
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.964 8489-8489/? I/dalvikvm: Could not find method android.content.Context.isDeviceProtectedStorage, referenced from method android.support.v4.content.ContextCompat.isDeviceProtectedStorage
07-06 21:22:04.964 8489-8489/? W/dalvikvm: VFY: unable to resolve virtual method 298: Landroid/content/Context;.isDeviceProtectedStorage ()Z
07-06 21:22:04.964 8489-8489/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
07-06 21:22:04.984 8489-8489/? D/AndroidRuntime: Shutting down VM
07-06 21:22:04.984 8489-8489/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692c08)
07-06 21:22:04.994 8489-8489/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.lenovo.app, PID: 8489
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lenovo.app/com.example.lenovo.app.MainActivity}: java.lang.IllegalStateException: This app has been built with an incorrect configuration. Please configure your build for VectorDrawableCompat.
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                     at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:146)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                     at dalvik.system.NativeStart.main(Native Method)
                                                  Caused by: java.lang.IllegalStateException: This app has been built with an incorrect configuration. Please configure your build for VectorDrawableCompat.
                                                     at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:713)
                                                     at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:194)
                                                     at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:81)
                                                     at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:129)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:152)
                                                     at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
                                                     at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
                                                     at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518)
                                                     at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:70)
                                                     at com.example.lenovo.app.MainActivity.onCreate(MainActivity.java:10)
                                                     at android.app.Activity.performCreate(Activity.java:5322)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2303)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                     at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:146)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                     at java.lang.reflect.Method.invokeNative(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:515)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                     at dalvik.system.NativeStart.main(Native Method)
07-06 21:22:07.814 8489-8489/? I/Process: Sending signal. PID: 8489 SIG: 9

Body:
add this code to your app.gradle :

android {
//....something

defaultConfig {
    generatedDensities = []
}

aaptOptions {
    additionalParameters "--no-version-vectors"
}