问:
Grouping by Continents in Leaflet.js geoJSON
I have a geoJson data layer of the world from naturalearthdata.com and a working map based on countries (features) with hover colors setup.  I want to group the data on continents, so I'd end up with Europe, Americas, Aftrica and Middle East, Asia & Australia.

There doesn't seem to be any examples of this - I wouldn't think I need to change the data since all countries have the continent property. Whats best practice to achieve this?

答: Just to update, I decided to alter the .shp file in QGIS and merge the individual features to make these larger regions.  Took a load of tidying up stray lines with the Node tool but this produced what I needed.</p>


来源: stackexchange

问:
Building msbuild 15 project programmatically

I'm trying to build a simple C# 7 class library project created with VS2017.

MSBuild from framework assemblies is outdated, so I'm referencing Microsoft.Build, Microsoft.Build.Engine and Microsoft.Build.Framework from MSBuild folder within visual studio (C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin).

Still, when I do this:

using (var collection = new ProjectCollection())
{
    var proj = collection.LoadProject(@"c:\projects\Sample\Sample.csproj"); // <-- exception
    proj.Build(new[] {new ConsoleLogger()});
}
```

I'm getting InvalidProjectFileException: The tools version "15.0" is unrecognized. Available tools versions are "4.0", "2.0".

Is there programmatic way to invoke build using the latest build tools and C# 7 compiler?

答:
I had similar needs for my team and I wrote a Builder library for C# that supports several versions of Visual Studio.
I could not make the Project.Build function work properly, so I went for executing MsBuild.exe directly.

How I built it:

Use Microsoft.Build.Framework from NuGet

Create a new Project object with 1 target called Build

Define the right ToolsVersion

Of the Project according to the Visual Studio version:

2010, 2012 => 4.0

2013 => 12.0

2015 => 14.0

2017 => 15.0

Add a new task of type MsBuild

With Projects property containing all the project I need to build

Define the ToolsVersion

of the MsBuild task with same value as for the Project

Serialize the Project into a temporary file

Find the right MsBuild.exe according to the ToolsVersion

4.0, 12.0, 14.0

Found in the registry:

```<code>Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{msBuildVersion}")
</code>```

15.0

Not anymore in the registry, you need to use the Nuget package Microsoft.VisualStudio.Setup.Configuration.Interop

```<code>        var query = new SetupConfiguration();

        var query2 = (ISetupConfiguration2)query;

        var e = query2.EnumAllInstances();

        var helper = (ISetupHelper)query;

        int fetched;

        var instances = new ISetupInstance[1];

        do
        {
            e.Next(1, instances, out fetched);
            if (fetched > 0)
            {
                var instance = instances[0];

                var instance2 = (ISetupInstance2)instance;

                var state = instance2.GetState();

                // Skip non-complete instance, I guess?
                // Skip non-local instance, I guess?
                // Skip unregistered products?
                if (state != InstanceState.Complete
                    || (state & InstanceState.Local) != InstanceState.Local
                    || (state & InstanceState.Registered) != InstanceState.Registered)
                {
                    continue;
                }

                var msBuildComponent =
                    instance2.GetPackages()
                        .FirstOrDefault(
                            p =>
                                p.GetId()
                                    .Equals("Microsoft.Component.MSBuild",
                                        StringComparison.InvariantCultureIgnoreCase));

                if (msBuildComponent == null)
                {
                    continue;
                }

                var instanceRootDirectory = instance2.GetInstallationPath();

                var msbuildPathInInstance = Path.Combine(instanceRootDirectory, "MSBuild", msBuildVersion, "Bin", "msbuild.exe");

                if (File.Exists(msbuildPathInInstance))
                {
                    return msbuildPathInInstance;
                }
            }
        } while (fetched > 0);
</code>```

Execute MsBuild.exe

And build the serialized Project using a custom XML Logger - you can use the one provided by MsBuildExtensionPack

Read the result summary

Deserialize the result summary from Xml and use it to determine if build failed or not, which errors and warnings occurred etc.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to build a simple C# 7 class library project created with VS2017.

MSBuild from framework assemblies is outdated, so I'm referencing Microsoft.Build, Microsoft.Build.Engine and Microsoft.Build.Framework from MSBuild folder within visual studio (C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin).

Still, when I do this:

using (var collection = new ProjectCollection())
{
    var proj = collection.LoadProject(@"c:\projects\Sample\Sample.csproj"); // <-- exception
    proj.Build(new[] {new ConsoleLogger()});
}

I'm getting InvalidProjectFileException: The tools version "15.0" is unrecognized. Available tools versions are "4.0", "2.0".

Is there programmatic way to invoke build using the latest build tools and C# 7 compiler?

Body:
I had similar needs for my team and I wrote a Builder library for C# that supports several versions of Visual Studio.
I could not make the Project.Build function work properly, so I went for executing MsBuild.exe directly.

How I built it:

Use Microsoft.Build.Framework from NuGet

Create a new Project object with 1 target called Build

Define the right ToolsVersion

Of the Project according to the Visual Studio version:

2010, 2012 => 4.0

2013 => 12.0

2015 => 14.0

2017 => 15.0

Add a new task of type MsBuild

With Projects property containing all the project I need to build

Define the ToolsVersion

of the MsBuild task with same value as for the Project

Serialize the Project into a temporary file

Find the right MsBuild.exe according to the ToolsVersion

4.0, 12.0, 14.0

Found in the registry:

Registry.LocalMachine.OpenSubKey($@"SOFTWARE\Microsoft\MSBuild\ToolsVersions\{msBuildVersion}")

15.0

Not anymore in the registry, you need to use the Nuget package Microsoft.VisualStudio.Setup.Configuration.Interop

        var query = new SetupConfiguration();

        var query2 = (ISetupConfiguration2)query;

        var e = query2.EnumAllInstances();

        var helper = (ISetupHelper)query;

        int fetched;

        var instances = new ISetupInstance[1];

        do
        {
            e.Next(1, instances, out fetched);
            if (fetched > 0)
            {
                var instance = instances[0];

                var instance2 = (ISetupInstance2)instance;

                var state = instance2.GetState();

                // Skip non-complete instance, I guess?
                // Skip non-local instance, I guess?
                // Skip unregistered products?
                if (state != InstanceState.Complete
                    || (state & InstanceState.Local) != InstanceState.Local
                    || (state & InstanceState.Registered) != InstanceState.Registered)
                {
                    continue;
                }

                var msBuildComponent =
                    instance2.GetPackages()
                        .FirstOrDefault(
                            p =>
                                p.GetId()
                                    .Equals("Microsoft.Component.MSBuild",
                                        StringComparison.InvariantCultureIgnoreCase));

                if (msBuildComponent == null)
                {
                    continue;
                }

                var instanceRootDirectory = instance2.GetInstallationPath();

                var msbuildPathInInstance = Path.Combine(instanceRootDirectory, "MSBuild", msBuildVersion, "Bin", "msbuild.exe");

                if (File.Exists(msbuildPathInInstance))
                {
                    return msbuildPathInInstance;
                }
            }
        } while (fetched > 0);

Execute MsBuild.exe

And build the serialized Project using a custom XML Logger - you can use the one provided by MsBuildExtensionPack

Read the result summary

Deserialize the result summary from Xml and use it to determine if build failed or not, which errors and warnings occurred etc.


问:
Pulling username from Database
I'm setting up a login page for a program I'm making for a Uni Degree.

The login page itself works, but I'm having an issue with something else.

The login page itself is just a passcode.
Numeric characters in a text box get verified through an access database.

I set up my own subroutine (LoginProcedure) with the following code:

```<code>SELECT        COUNT(*) AS Result, [Password] AS Pass, Username AS [User]
FROM            users
GROUP BY [Password], Username
HAVING        (COUNT(*) = 1) AND ([Password] = ?)
</code>```

And on the login button, have the following code:

```<code>Dim login = UsersTableAdapter.LoginProcedure(txtPass.Text)
        If login Is Nothing Then
            MsgBox("Passcode Not Recognised!", MsgBoxStyle.Critical)
        Else
            Till.Show()
        End If
</code>```

So if the Text in txtPass matches any of the passwords in the Database, the Till form opens, otherwise they receive an error.

However, I also have a text box which I want a Username to appear in.
Is there anyway for the Username to automatically fill in, from the password provided??

PS.
It's VB2013... Uni has old software.

答:
Weird setup, but I'm not judging.  To answer your question...

DLOOKUP the UserName from the User table (use your passcode as the criteria).

Either put the DLOOKUP formaula in the textbox, or assign the DLOOKUP result to the textbox on whatever action (opening the till form, or after your passcode is entered) you want to trigger it.

Title: Pulling username from Database

Body:
I'm setting up a login page for a program I'm making for a Uni Degree.

The login page itself works, but I'm having an issue with something else.

The login page itself is just a passcode.
Numeric characters in a text box get verified through an access database.

I set up my own subroutine (LoginProcedure) with the following code:

SELECT        COUNT(*) AS Result, [Password] AS Pass, Username AS [User]
FROM            users
GROUP BY [Password], Username
HAVING        (COUNT(*) = 1) AND ([Password] = ?)

And on the login button, have the following code:

Dim login = UsersTableAdapter.LoginProcedure(txtPass.Text)
        If login Is Nothing Then
            MsgBox("Passcode Not Recognised!", MsgBoxStyle.Critical)
        Else
            Till.Show()
        End If

So if the Text in txtPass matches any of the passwords in the Database, the Till form opens, otherwise they receive an error.

However, I also have a text box which I want a Username to appear in.
Is there anyway for the Username to automatically fill in, from the password provided??

PS.
It's VB2013... Uni has old software.


问:
write data in google sheet using a web script app
I am trying to do Something apparently very simple, but I don't get it :
I would like to create a google web app, in wich the user write some text, and when he clicks on a button, the text goes into a Google Sheet.

Then, I would like to do also the contrairy : when the user click on a other button of the google web app, he can see what is written in a cell of the google sheet

My biggest problem is that i just don't know how to do the connexion between the webb app and the sheet, and how to use it.

Can you help me ?
Thanks

答:
Here is a search script I modified to work. Input text press submit and the words goto Spreadsheet.

You need to deploy as web app.

CODE.GS

function doGet(e) { // main function
  var template = HtmlService.createTemplateFromFile('index.html');
  return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

// Process the form
function processForm(searchTerm) {
  var resultToReturn;
  resultToReturn  = TextToSheet(searchTerm);
  return resultToReturn; // return the results
}

function TextToSheet(searchTerm) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.getActiveSheet().getRange('A1').setValue(searchTerm);

}```
</div>
</div>
</p>

<p>INDEX.HTML</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <base target="_top">
    <script>
      function displayMessage() {
        var searchTerm;
        searchTerm = document.getElementById('idSrchTerm').value;
        console.log('searchTerm: ' + searchTerm );
         google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
       }

      function handleResults(results){
         var length=results.length; // total elements of results
       }

    </script>
  </head>
  <body><center><br/>
   Input word to SpreadSheet: <input type="text" id="idSrchTerm" name="search">
    <input type="button" value="Submit" name="submitButton" onclick="displayMessage()"/>
</center>
  </body>
</html></code>```

Body:
Here is a search script I modified to work. Input text press submit and the words goto Spreadsheet.

You need to deploy as web app.

CODE.GS

function doGet(e) { // main function
  var template = HtmlService.createTemplateFromFile('index.html');
  return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}

// Process the form
function processForm(searchTerm) {
  var resultToReturn;
  resultToReturn  = TextToSheet(searchTerm);
  return resultToReturn; // return the results
}

function TextToSheet(searchTerm) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.getActiveSheet().getRange('A1').setValue(searchTerm);

}

INDEX.HTML

<html>
  <head>
    <base target="_top">
    <script>
      function displayMessage() {
        var searchTerm;
        searchTerm = document.getElementById('idSrchTerm').value;
        console.log('searchTerm: ' + searchTerm );
         google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
       }

      function handleResults(results){
         var length=results.length; // total elements of results
       }

    </script>
  </head>
  <body><center><br/>
   Input word to SpreadSheet: <input type="text" id="idSrchTerm" name="search">
    <input type="button" value="Submit" name="submitButton" onclick="displayMessage()"/>
</center>
  </body>
</html>


问:
trying to follow along with simple Java tutorial, NetBeans not compiling code
I'm using NetBeans 6.9.1 on windows and i am following along with a rather simple java tutorial, first it asks me to use notepad but i'd rather just use a IDE for this, anyways i'm asked to create a file and put this code down:

```<code>class HelloWorldApp {
    public static void main(String[ ] args) {
       System.out.println("Hello World!" );
    }
}
</code>```

and i get a lot of compiler errors:

```<code>java.lang.NoClassDefFoundError: javaapplication1/Main
Caused by: java.lang.ClassNotFoundException: javaapplication1.Main
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: javaapplication1.Main.  Program will exit.
Exception in thread "main" Java Result: 1
</code>```

i tried to get the wizard to make as clean a starting project as possible, but it seems that nothing is simple here.

so is the code wrong, and the tutorial thus not worth following, or am i doing something wrong with the IDE?

答:
Is it saying that it's trying to find a class named Main but you've named the class HelloWorldApp?

Is the HelloWorldApp in a file called HelloWorldApp.java?

ContentLicense: CC BY-SA 2.5

Body:
I'm using NetBeans 6.9.1 on windows and i am following along with a rather simple java tutorial, first it asks me to use notepad but i'd rather just use a IDE for this, anyways i'm asked to create a file and put this code down:

class HelloWorldApp {
    public static void main(String[ ] args) {
       System.out.println("Hello World!" );
    }
}

and i get a lot of compiler errors:

java.lang.NoClassDefFoundError: javaapplication1/Main
Caused by: java.lang.ClassNotFoundException: javaapplication1.Main
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: javaapplication1.Main.  Program will exit.
Exception in thread "main" Java Result: 1

i tried to get the wizard to make as clean a starting project as possible, but it seems that nothing is simple here.

so is the code wrong, and the tutorial thus not worth following, or am i doing something wrong with the IDE?


问:
Setting up Log4j2 in NetBeans, basic configuration
As a complete beginner, how do I set up Log4j2 (in Netbeans) to log some messages to the console and others into a file?
(I only found guides for older versions, which got me into trouble because the XML changed. Basically, I’m updating what was done in this thread, because I thought it was a great idea but some tips were missing) </p>

答:
You will need to download this archive of binaries

Add “log4j-api-2.8.1.jar” and “log4j-core-2.8.1.jar” to your project. (in NetBeans: File -> Project Properties -> Libraries. I had to add it to both “compile” and “run”, or else I would get an error at runtime.)

Tell Log4j where the file is. (in NetBeans: File -> Project Properties -> Run. Paste

```<code>-Dlog4j.configurationFile=/path/to/your/file/log4j2.xml
</code>```

into the Textfield “VM-Options”

Create an XML called log4j2.xml at the specified path (I did it in the main folder of my project) with your configuration, e.g.

```<code><?xml version="1.0" encoding="UTF-8"?>

<Configuration status="warn">
  <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%m%n"/>
    </Console>
    <File name="FILE" fileName="logs/myLog.log">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
    </File>
  </Appenders>
  <Loggers>
    <Root level="INFO">
      <AppenderRef ref="FILE" level="INFO"/>
      <AppenderRef ref="STDOUT" level="ERROR"/>
    </Root>
  </Loggers>
</Configuration>
</code>```

This creates two appenders, a ConsoleAppender and a FileAppender, that log into System.out and a file called "myLog.log", respectively. Log messages of level INFO and higher are logged into the file, only errors are printed to the console.

This is some sample code to demonstrate how Log4j2 is used:

```<code>import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Demo {

    private final static Logger log = LogManager.getLogger(Demo.class);

    public static void main(String[] args) throws IOException {
        log.info("starting...");
        try {
            ((Object) null).toString();
        } catch (Exception e) {
            log.error("error message");
        }
        log.info("some info.");
    }
}
</code>```

Running this leads to a console output of

```<code>    error message
</code>```

while the file contains

```<code>    2017-03-29 14:37:20,675 INFO l.Demo [main] starting...
    2017-03-29 14:37:20,676 ERROR l.Demo [main] error message
    2017-03-29 14:37:20,676 INFO l.Demo [main] some info.
</code>```

I hope this saved you some trouble, as it took me quite some time to figure this out. Feel free to edit this post - I have no idea how correct my statements are, these are just the steps that worked for me.

Body:
You will need to download this archive of binaries

Add “log4j-api-2.8.1.jar” and “log4j-core-2.8.1.jar” to your project. (in NetBeans: File -> Project Properties -> Libraries. I had to add it to both “compile” and “run”, or else I would get an error at runtime.)

Tell Log4j where the file is. (in NetBeans: File -> Project Properties -> Run. Paste

-Dlog4j.configurationFile=/path/to/your/file/log4j2.xml

into the Textfield “VM-Options”

Create an XML called log4j2.xml at the specified path (I did it in the main folder of my project) with your configuration, e.g.

<?xml version="1.0" encoding="UTF-8"?>

<Configuration status="warn">
  <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%m%n"/>
    </Console>
    <File name="FILE" fileName="logs/myLog.log">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
    </File>
  </Appenders>
  <Loggers>
    <Root level="INFO">
      <AppenderRef ref="FILE" level="INFO"/>
      <AppenderRef ref="STDOUT" level="ERROR"/>
    </Root>
  </Loggers>
</Configuration>

This creates two appenders, a ConsoleAppender and a FileAppender, that log into System.out and a file called "myLog.log", respectively. Log messages of level INFO and higher are logged into the file, only errors are printed to the console.

This is some sample code to demonstrate how Log4j2 is used:

import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Demo {

    private final static Logger log = LogManager.getLogger(Demo.class);

    public static void main(String[] args) throws IOException {
        log.info("starting...");
        try {
            ((Object) null).toString();
        } catch (Exception e) {
            log.error("error message");
        }
        log.info("some info.");
    }
}

Running this leads to a console output of

    error message

while the file contains

    2017-03-29 14:37:20,675 INFO l.Demo [main] starting...
    2017-03-29 14:37:20,676 ERROR l.Demo [main] error message
    2017-03-29 14:37:20,676 INFO l.Demo [main] some info.

I hope this saved you some trouble, as it took me quite some time to figure this out. Feel free to edit this post - I have no idea how correct my statements are, these are just the steps that worked for me.


问:
Heroku: Prevent worker process from restarting?
I have a Heroku worker setup to do a long running job which iterates over long periods. However whenever I do an update & deploy of other files in the repo this worker restarts, which is annoying, any way to avoid this?</p>

答:
No. This behaviour is part of Heroku's Automatic Dyno Restarting.

You can't work around this. Instead, you need to build all parts of your app to be able to function properly despite the fact that all dynos will restart at least once every 24 hours or so, whether or not you deploy updates in your repo.

Most significantly, you need to build support for Graceful Shutdown into all your processes (e.g. web process and worker processes).


问:
Baidu map integration error in android 6 and above
I have implemented Baidu map in my application and it is working fine in android version below 6 but have problem with above android 6 versions.
I have implemented dynamic WRITE_SETTING permission for android 6. If user give permission to app then also Baidu MapView class not able to access it and it is crashing.
Error log as below

```<code>java.lang.SecurityException: Permission Denial: requires permission android.permission.WRITE_SETTINGS
at com.baidu.android.bbalbs.common.util.a.a(DeviceId.java:206)
at com.baidu.android.bbalbs.common.util.a.a(DeviceId.java:68)
at com.baidu.android.bbalbs.common.util.CommonParam.b(CommonParam.java:72)
at com.baidu.android.bbalbs.common.util.CommonParam.a(CommonParam.java:45)
at com.baidu.platform.comapi.c.c.p(Unknown Source)
at com.baidu.platform.comapi.c.c.c(Unknown Source)
at com.baidu.mapapi.a.b(Unknown Source)
at com.baidu.mapapi.map.MapView.a(Unknown Source)
at com.baidu.mapapi.map.MapView.<init>(Unknown Source)
</code>```

Please help me to solve out this problem.

答:
I had the same problem, due to different permission mechanism approach in Android 6 (as described in https://developer.android.com/training/permissions/index.html).
Solved asking write_settings permission in this way:

```<code>ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.WRITE_SETTINGS,1);
</code>```

where "this" is an Activity containing method:

```<code>@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] results) {
    switch (requestCode) {
        case 1: {
            if (results.length > 0
                    && results[0] == PackageManager.PERMISSION_GRANTED) {
                //You had the permission
                } else {
                    // Permission denied!
                }
                return;
            }
            // With additional 'case' you can handle additional permission check
        }

    }}
</code>```

Body:
I have implemented Baidu map in my application and it is working fine in android version below 6 but have problem with above android 6 versions.
I have implemented dynamic WRITE_SETTING permission for android 6. If user give permission to app then also Baidu MapView class not able to access it and it is crashing.
Error log as below

java.lang.SecurityException: Permission Denial: requires permission android.permission.WRITE_SETTINGS
at com.baidu.android.bbalbs.common.util.a.a(DeviceId.java:206)
at com.baidu.android.bbalbs.common.util.a.a(DeviceId.java:68)
at com.baidu.android.bbalbs.common.util.CommonParam.b(CommonParam.java:72)
at com.baidu.android.bbalbs.common.util.CommonParam.a(CommonParam.java:45)
at com.baidu.platform.comapi.c.c.p(Unknown Source)
at com.baidu.platform.comapi.c.c.c(Unknown Source)
at com.baidu.mapapi.a.b(Unknown Source)
at com.baidu.mapapi.map.MapView.a(Unknown Source)
at com.baidu.mapapi.map.MapView.<init>(Unknown Source)

Please help me to solve out this problem.

Body:
I had the same problem, due to different permission mechanism approach in Android 6 (as described in https://developer.android.com/training/permissions/index.html).
Solved asking write_settings permission in this way:

ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.WRITE_SETTINGS,1);

where "this" is an Activity containing method:

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] results) {
    switch (requestCode) {
        case 1: {
            if (results.length > 0
                    && results[0] == PackageManager.PERMISSION_GRANTED) {
                //You had the permission
                } else {
                    // Permission denied!
                }
                return;
            }
            // With additional 'case' you can handle additional permission check
        }

    }}


问:
Caesar Cipher Function in Python
I'm trying to create a simple Caesar Cipher function in Python that shifts letters based on input from the user and creates a final, new string at the end. The only problem is that the final cipher text shows only the last shifted character, not an entire string with all the shifted characters.

Here's my code:

```<code>plainText = raw_input("What is your plaintext? ")
shift = int(raw_input("What is your shift? "))

def caesar(plainText, shift):

    for ch in plainText:
        if ch.isalpha():
            stayInAlphabet = ord(ch) + shift
            if stayInAlphabet > ord('z'):
                stayInAlphabet -= 26
            finalLetter = chr(stayInAlphabet)
        cipherText = ""
        cipherText += finalLetter

    print "Your ciphertext is: ", cipherText

    return cipherText

caesar(plainText, shift)
</code>```

答:
```<code>import string
wrd=raw_input("Enter word").lower()
fwrd=""
for let in wrd:
    fwrd+=string.ascii_lowercase[(string.ascii_lowercase).index(let)+3]
print"Original word",wrd
print"New word",fwrd
</code>```

Title: Caesar Cipher Function in Python

Body:
I'm trying to create a simple Caesar Cipher function in Python that shifts letters based on input from the user and creates a final, new string at the end. The only problem is that the final cipher text shows only the last shifted character, not an entire string with all the shifted characters.

Here's my code:

plainText = raw_input("What is your plaintext? ")
shift = int(raw_input("What is your shift? "))

def caesar(plainText, shift):

    for ch in plainText:
        if ch.isalpha():
            stayInAlphabet = ord(ch) + shift
            if stayInAlphabet > ord('z'):
                stayInAlphabet -= 26
            finalLetter = chr(stayInAlphabet)
        cipherText = ""
        cipherText += finalLetter

    print "Your ciphertext is: ", cipherText

    return cipherText

caesar(plainText, shift)


问:
Connection for android and SOAP api
I am new developer for SOAP , so guide me how can i call soap api in android.
Here is method which i found but dont know how it works. I have downloaded this library </p>

```<code> public static String connectSOAP(String url, String soapNamespace, String soapAction, String soapMethod, Hashtable<String, String> HT) {

        String result = null;

        SoapObject request = new SoapObject(soapNamespace, soapMethod);

        if (HT != null) {
            Enumeration<String> en = HT.keys();
            while (en.hasMoreElements()) {

                Object k = en.nextElement();
                Object v = HT.get(k);
                request.addProperty(k.toString(), v);
                System.out.println("key = " + k.toString() + "; value = " + v);
            }
        }

        SoapSerializationEnvelope envelope =
                new SoapSerializationEnvelope(SoapEnvelope.VER11);

        //envelope.bodyOut = request;
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
        //envelope.getResponse();

        try {

            androidHttpTransport.call(soapAction, envelope);

            if (envelope.bodyIn instanceof SoapFault) {

                result = ((SoapFault) envelope.bodyIn).faultstring;

            } else {

                SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
                result = resultsRequestSOAP.getProperty(0).toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
</code>```

<p>This is method which i want to use as an api call but dont know how can i use this.
so please help me. </p>

答:
In using soap webservice, i would highly recommend you not to use any library to make the soap request. Using the classes provided by android is way more convenient and less prone to errors. This is how you make a soap request without use of libraries: First of all you will need to know how to make use of SOAP Ui which is a windows application. You can import your wsdl file here and if it's syntax us correct, then you will get a screen showing the request body for your webservice. You can enter test values and you will get a response structure. This link will guide you on how to use soap ui https://www.soapui.org/soap-and-wsdl/working-with-wsdls.html

Now on to the androiod code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

```<code> private class runTask extends AsyncTask<String, String, String> {

        private String response;
        String string = "your string parameter"
        String SOAP_ACTION = "your soap action here";

        String stringUrl = "http://your_url_here";
        //if you experience a problem with url remove the '?wsdl' ending

        @Override
        protected String doInBackground(String... params) {

            try {

                        //paste your request structure here as the String body(copy it exactly as it is in soap ui)
                        //assuming that this is your request body

                String body = "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">" +
                                "<soap:Body>"+
                                "<GetCitiesByCountryResponse xmlns="http://www.webserviceX.NET">"+
                                "<GetCitiesByCountryResult>"+string+"</GetCitiesByCountryResult>"+
                                "</GetCitiesByCountryResponse>"+
                                "</soap:Body>"+
                                "</soap:Envelope>";

                try {
                    URL url = new URL(stringUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDefaultUseCaches(false);
                    conn.setRequestProperty("Accept", "text/xml");
                    conn.setRequestProperty("SOAPAction", SOAP_ACTION);

                    //push the request to the server address

                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.write(body);
                    wr.flush();

                    //get the server response

                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder builder = new StringBuilder();
                    String line = null;

                    while ((line = reader.readLine()) != null) {

                        builder.append(line);
                        response = builder.toString();//this is the response, parse it in onPostExecute

                    }

                } catch (Exception e) {

                    e.printStackTrace();
                } finally {

                    try {

                        reader.close();
                    } catch (Exception e) {

                        e.printStackTrace();
                    }
                }

            } catch (Exception e) {

                e.printStackTrace();
            }

            return response;
        }

        /**
         * @see AsyncTask#onPostExecute(Object)
         */
        @Override
        protected void onPostExecute(String result) {

           try {

              Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
</code>```

Now just execute the class and watch the magic happen:

```<code>runTask runner = new runTask();
runner.execute();
</code>```

After getting your response, you can parse it using DOM or SAX parse,some little research and you will understand how to parse. You can create the WSDL webservice using java, and preferable Eclipse Ide. Tutorials are also available on youtube on the WSDL webservices.

Feel free to ask for clarification where the solution is not clear.

Title: Connection for android and SOAP api

Body:
I am new developer for SOAP , so guide me how can i call soap api in android.
Here is method which i found but dont know how it works. I have downloaded this library

 public static String connectSOAP(String url, String soapNamespace, String soapAction, String soapMethod, Hashtable<String, String> HT) {

        String result = null;

        SoapObject request = new SoapObject(soapNamespace, soapMethod);

        if (HT != null) {
            Enumeration<String> en = HT.keys();
            while (en.hasMoreElements()) {

                Object k = en.nextElement();
                Object v = HT.get(k);
                request.addProperty(k.toString(), v);
                System.out.println("key = " + k.toString() + "; value = " + v);
            }
        }

        SoapSerializationEnvelope envelope =
                new SoapSerializationEnvelope(SoapEnvelope.VER11);

        //envelope.bodyOut = request;
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
        //envelope.getResponse();

        try {

            androidHttpTransport.call(soapAction, envelope);

            if (envelope.bodyIn instanceof SoapFault) {

                result = ((SoapFault) envelope.bodyIn).faultstring;

            } else {

                SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
                result = resultsRequestSOAP.getProperty(0).toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

This is method which i want to use as an api call but dont know how can i use this.
so please help me.

Body:
In using soap webservice, i would highly recommend you not to use any library to make the soap request. Using the classes provided by android is way more convenient and less prone to errors. This is how you make a soap request without use of libraries: First of all you will need to know how to make use of SOAP Ui which is a windows application. You can import your wsdl file here and if it's syntax us correct, then you will get a screen showing the request body for your webservice. You can enter test values and you will get a response structure. This link will guide you on how to use soap ui https://www.soapui.org/soap-and-wsdl/working-with-wsdls.html

Now on to the androiod code :

We will create a class named runTask which extends async task and use http to send the request body and get request response :

 private class runTask extends AsyncTask<String, String, String> {

        private String response;
        String string = "your string parameter"
        String SOAP_ACTION = "your soap action here";

        String stringUrl = "http://your_url_here";
        //if you experience a problem with url remove the '?wsdl' ending

        @Override
        protected String doInBackground(String... params) {

            try {

                        //paste your request structure here as the String body(copy it exactly as it is in soap ui)
                        //assuming that this is your request body

                String body = "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">" +
                                "<soap:Body>"+
                                "<GetCitiesByCountryResponse xmlns="http://www.webserviceX.NET">"+
                                "<GetCitiesByCountryResult>"+string+"</GetCitiesByCountryResult>"+
                                "</GetCitiesByCountryResponse>"+
                                "</soap:Body>"+
                                "</soap:Envelope>";

                try {
                    URL url = new URL(stringUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDefaultUseCaches(false);
                    conn.setRequestProperty("Accept", "text/xml");
                    conn.setRequestProperty("SOAPAction", SOAP_ACTION);

                    //push the request to the server address

                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.write(body);
                    wr.flush();

                    //get the server response

                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder builder = new StringBuilder();
                    String line = null;

                    while ((line = reader.readLine()) != null) {

                        builder.append(line);
                        response = builder.toString();//this is the response, parse it in onPostExecute

                    }

                } catch (Exception e) {

                    e.printStackTrace();
                } finally {

                    try {

                        reader.close();
                    } catch (Exception e) {

                        e.printStackTrace();
                    }
                }

            } catch (Exception e) {

                e.printStackTrace();
            }

            return response;
        }

        /**
         * @see AsyncTask#onPostExecute(Object)
         */
        @Override
        protected void onPostExecute(String result) {

           try {

              Toast.makeText(this,"Response "+ result,Toast.LENGTH_LONG).show();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

Now just execute the class and watch the magic happen:

runTask runner = new runTask();
runner.execute();

After getting your response, you can parse it using DOM or SAX parse,some little research and you will understand how to parse. You can create the WSDL webservice using java, and preferable Eclipse Ide. Tutorials are also available on youtube on the WSDL webservices.

Feel free to ask for clarification where the solution is not clear.


问:
Broad crawling - different xpaths - Scrapy
I'm new in Scrapy. I have thousands of url,xpath tuples and values in a database.
These urls are from different domains (not allways, there can be 100 urls from the same domain).

```<code>x.com/a //h1
y.com/a //div[@class='1']
z.com/a //div[@href='...']
x.com/b //h1
x.com/c //h1
...
</code>```

Now I want to get these values every 2 hours as fast as possible but to be sure that I don't overload any of these.

Can't figure out how to do that.

My thoughts:

I could create one Spider for every different domain, set it's parsing rules and run them at once.

Is it a good practice?

EDIT:
I'm not sure how it would work with outputting data into database according to concurrency.

EDIT2:

I can do something like this - for every domain there is a new spider. But this is impossible to do having thousands of different urls and it's xpaths.

```<code>class WikiScraper(scrapy.Spider):
    name = "wiki_headers"

    def start_requests(self):
        urls = [
            'https://en.wikipedia.org/wiki/Spider',
            'https://en.wikipedia.org/wiki/Data_scraping',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//h1/text()').extract()
        print header
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

class CraigslistScraper(scrapy.Spider):
    name = "craigslist_headers"

    def start_requests(self):
        urls = [
            'https://columbusga.craigslist.org/act/6062657418.html',
            'https://columbusga.craigslist.org/acc/6060297390.html',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//span[@id="titletextonly"]/text()').extract()
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)
</code>```

答:
From the example you posted in edit2, it looks like all your classes are easily abstractable by one more level. How about this:?

```<code>from urllib.parse import urlparse

class GenericScraper(scrapy.Spider):
    def __init__(self, urls, xpath):
        super().__init__()
        self.name = self._create_scraper_name_from_url(urls[0])
        self.urls = urls
        self.xpath = xpath

    def _create_scraper_name_from_url(url):
        '''Generate scraper name from url
           www.example.com/foobar/bar -> www_example_com'''
        netloc = urlparse(url).netloc
        return netloc.replace('.','_')

    def start_requests(self):
        for url in self.urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select(self.xpath).extract()
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)
</code>```

Next, you could group the data from database by xpaths

```<code>for urls, xpath in grouped_data:
    scraper = GenericScraper(urls, xpath)
    # do whatever you need with scraper
</code>```

AD concurency: your database should handle concurent writes so I do not see a problem there

Edit:
Related to the timeouts: I Do not know how scrapy works under the hood i.e. if it uses some sort of paralelization and whether it runs asynchronously in the background. But from what you wrote I guess it does and when you fire up 1k scrapers each firing multiple requests at time your hardware cant handle that much traffic (disclaimer, this is just a guess!).

There might be a native way to do this, but a possible workaround is to use multiprocessing + Queue:

```<code>from multiprocessing import JoinableQueue, Process
NUMBER_OF_CPU = 4 # change this to your number.
SENTINEL = None

class Worker(Process):
    def __init__(self, queue):
        super().__init__()
        self.queue = queue
    def run(self):
        # blocking wait !You have to use sentinels if you use blocking waits!
        item = self.queue.get():
        if item is SENTINEL:
            # we got sentinel, there are no more scrapers to process
            self.queue.task_done()
            return
        else:
            # item is scraper, run it
            item.run_spider() # or however you run your scrapers
            # This assumes that each scraper is **not** running in background!

            # Tell the JoinableQueue we have processed one more item
            # In the main thread the queue.join() waits untill for
            # each item taken from queue a queue.task_done() is called
            self.queue.task_done()

def run():
    queue = JoinableQueue()
    # if putting that many things in the queue gets slow (I imagine
    # it can) You can fire up a separate Thread/Process to fill the
    # queue in the background while workers are already consuming it.
    for urls, xpath in grouped_data:
        scraper = GenericScraper(urls, xpath)
        queue.put(scraper)
    for sentinel in range(NUMBER_OF_CPU):
        # None or sentinel of your choice to tell the workers there are
        # no more scrapers to process
        queue.put(SENTINEL)
    workers = []
    for _ in range(NUMBER_OF_CPU):
        worker = Worker(queue)
        workers.append(worker)
        worker.start()

    # We have to wait until the queue is processed
    queue.join()
</code>```

But please bear in mind that this is a vanilla approach for paralell execution completely ignoring Scrapy abilities. I have found This blogpost which uses twisted to achieve (what I think is) the same thing. But since I've never used twisted I can't comment on that

Body:
I'm new in Scrapy. I have thousands of url,xpath tuples and values in a database.
These urls are from different domains (not allways, there can be 100 urls from the same domain).

x.com/a //h1
y.com/a //div[@class='1']
z.com/a //div[@href='...']
x.com/b //h1
x.com/c //h1
...

Now I want to get these values every 2 hours as fast as possible but to be sure that I don't overload any of these.

Can't figure out how to do that.

My thoughts:

I could create one Spider for every different domain, set it's parsing rules and run them at once.

Is it a good practice?

EDIT:
I'm not sure how it would work with outputting data into database according to concurrency.

EDIT2:

I can do something like this - for every domain there is a new spider. But this is impossible to do having thousands of different urls and it's xpaths.

class WikiScraper(scrapy.Spider):
    name = "wiki_headers"

    def start_requests(self):
        urls = [
            'https://en.wikipedia.org/wiki/Spider',
            'https://en.wikipedia.org/wiki/Data_scraping',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//h1/text()').extract()
        print header
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

class CraigslistScraper(scrapy.Spider):
    name = "craigslist_headers"

    def start_requests(self):
        urls = [
            'https://columbusga.craigslist.org/act/6062657418.html',
            'https://columbusga.craigslist.org/acc/6060297390.html',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select('//span[@id="titletextonly"]/text()').extract()
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

Body:
From the example you posted in edit2, it looks like all your classes are easily abstractable by one more level. How about this:?

from urllib.parse import urlparse

class GenericScraper(scrapy.Spider):
    def __init__(self, urls, xpath):
        super().__init__()
        self.name = self._create_scraper_name_from_url(urls[0])
        self.urls = urls
        self.xpath = xpath

    def _create_scraper_name_from_url(url):
        '''Generate scraper name from url
           www.example.com/foobar/bar -> www_example_com'''
        netloc = urlparse(url).netloc
        return netloc.replace('.','_')

    def start_requests(self):
        for url in self.urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        header = hxs.select(self.xpath).extract()
        filename = 'result.txt'
        with open(filename, 'a') as f:
            f.write(header[0])
        self.log('Saved file %s' % filename)

Next, you could group the data from database by xpaths

for urls, xpath in grouped_data:
    scraper = GenericScraper(urls, xpath)
    # do whatever you need with scraper

AD concurency: your database should handle concurent writes so I do not see a problem there

Edit:
Related to the timeouts: I Do not know how scrapy works under the hood i.e. if it uses some sort of paralelization and whether it runs asynchronously in the background. But from what you wrote I guess it does and when you fire up 1k scrapers each firing multiple requests at time your hardware cant handle that much traffic (disclaimer, this is just a guess!).

There might be a native way to do this, but a possible workaround is to use multiprocessing + Queue:

from multiprocessing import JoinableQueue, Process
NUMBER_OF_CPU = 4 # change this to your number.
SENTINEL = None

class Worker(Process):
    def __init__(self, queue):
        super().__init__()
        self.queue = queue
    def run(self):
        # blocking wait !You have to use sentinels if you use blocking waits!
        item = self.queue.get():
        if item is SENTINEL:
            # we got sentinel, there are no more scrapers to process
            self.queue.task_done()
            return
        else:
            # item is scraper, run it
            item.run_spider() # or however you run your scrapers
            # This assumes that each scraper is **not** running in background!

            # Tell the JoinableQueue we have processed one more item
            # In the main thread the queue.join() waits untill for
            # each item taken from queue a queue.task_done() is called
            self.queue.task_done()

def run():
    queue = JoinableQueue()
    # if putting that many things in the queue gets slow (I imagine
    # it can) You can fire up a separate Thread/Process to fill the
    # queue in the background while workers are already consuming it.
    for urls, xpath in grouped_data:
        scraper = GenericScraper(urls, xpath)
        queue.put(scraper)
    for sentinel in range(NUMBER_OF_CPU):
        # None or sentinel of your choice to tell the workers there are
        # no more scrapers to process
        queue.put(SENTINEL)
    workers = []
    for _ in range(NUMBER_OF_CPU):
        worker = Worker(queue)
        workers.append(worker)
        worker.start()

    # We have to wait until the queue is processed
    queue.join()

But please bear in mind that this is a vanilla approach for paralell execution completely ignoring Scrapy abilities. I have found This blogpost which uses twisted to achieve (what I think is) the same thing. But since I've never used twisted I can't comment on that


答: Is your file named HelloWorldApp.java?</p>

Title: trying to follow along with simple Java tutorial, NetBeans not compiling code

Body: Is your file named HelloWorldApp.java?


问:
TYPO3 ods ajaxmail with directmail
I need to change the newsletter scubscription status by a checkbox. I need to activate newsletter subscrpition of logged in user with a checkbox. How can it is possible? </p>

答:
depending on your intention two options come to mind:
build a form (or only checkbox) with an eventhandler which acts on click:

the page could reload:
just send the form, change the mode of subscription, redisplay the page with changed status

the page should stay: do an AJAX call to change the status, return new status (form) to display

the user could be accessed from the session data.

Title: TYPO3 ods ajaxmail with directmail


问:
Check if string is in array or not including wildcards with Excel VBA
I found this function to identify whether a string is in a given array, however it does not seem to be able to handle wildcards (or atleast not the way i do it).

```<code>Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
</code>```

My use of the function:

```<code>Dim BannedWildcards() As Variant

BannedWildcards = Array("", "-", "?", 0, "na", "n/a", _
"*account*", "*hse*", "*defined*", "*applicable*", "*operation*", "*action*", "*manager*")

            Select Case True
            Case IsInArray(LCase(Sht_Tracker.Cells(RowCounter_CRCT, 17)), BannedWildcards) = True
                Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = "#N/A"
            Case Else: Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = Sht_Tracker.Cells(RowCounter_CRCT, 17)
            End Select
</code>```

答:
Thank you SLWS. I modified the code you referenced to a bit in order to fit my need.

This works for me:

```<code>Function IsInArray(stringToBeFound As String, MyArray As Variant) As Boolean

    Dim i As Long
    Dim WildCard As String
    WildCard = "*"

    IsInArray = False

    For i = LBound(MyArray) To UBound(MyArray)
        If InStr(MyArray(i), WildCard) > 0 Then
            If LCase(stringToBeFound) Like LCase("*" & Replace(MyArray(i), " ", "*") & "*") Then
                IsInArray = True
                Exit Function
            End If
        Else
            If LCase(stringToBeFound) = LCase(MyArray(i)) Then
                IsInArray = True
                Exit Function
            End If
        End If
    Next
End Function
</code>```

Body:
I found this function to identify whether a string is in a given array, however it does not seem to be able to handle wildcards (or atleast not the way i do it).

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

My use of the function:

Dim BannedWildcards() As Variant

BannedWildcards = Array("", "-", "?", 0, "na", "n/a", _
"*account*", "*hse*", "*defined*", "*applicable*", "*operation*", "*action*", "*manager*")

            Select Case True
            Case IsInArray(LCase(Sht_Tracker.Cells(RowCounter_CRCT, 17)), BannedWildcards) = True
                Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = "#N/A"
            Case Else: Arr_Dashboard_Current(10, ArrC_Dashboard_Current) = Sht_Tracker.Cells(RowCounter_CRCT, 17)
            End Select

Body:
Thank you SLWS. I modified the code you referenced to a bit in order to fit my need.

This works for me:

Function IsInArray(stringToBeFound As String, MyArray As Variant) As Boolean

    Dim i As Long
    Dim WildCard As String
    WildCard = "*"

    IsInArray = False

    For i = LBound(MyArray) To UBound(MyArray)
        If InStr(MyArray(i), WildCard) > 0 Then
            If LCase(stringToBeFound) Like LCase("*" & Replace(MyArray(i), " ", "*") & "*") Then
                IsInArray = True
                Exit Function
            End If
        Else
            If LCase(stringToBeFound) = LCase(MyArray(i)) Then
                IsInArray = True
                Exit Function
            End If
        End If
    Next
End Function


问:
Login Validation of an imageview in android
validation: Login Form :
I am able validate the email :if there is error, it should not go to next page.

But,There is one field. Imageview.  i picked  an image from the gallery and set it to imageview.  there is also no probem.

When there is no  image in Imageview,  it should rise the error because of no image which is like email validation.
How validate Imageview like login validation

it should not move to next page ...

..How is it possible. any help? thank's in advance.
I can validate successfully with below code like that Imageview which i want.

```<code>enter code here

public class MainActivity extends AppCompatActivity
  implements View.OnClickListener {

//The view objects
private EditText editTextName, editTextEmail, editTextMobile,
        editTextDob, editTextAge;

private Button buttonSubmit;

//defining AwesomeValidation object
private AwesomeValidation awesomeValidation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //initializing awesomevalidation object
    /*        awesomeValidation.addValidation(this, R.id.editTextName, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);

    * The library provides 3 types of validation
    * BASIC
    * COLORATION
    * UNDERLABEL
    * */
    awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);

    //initializing view objects
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextMobile = (EditText) findViewById(R.id.editTextMobile);
    editTextDob = (EditText) findViewById(R.id.editTextDob);
    editTextAge = (EditText) findViewById(R.id.editTextAge);

    buttonSubmit = (Button) findViewById(R.id.buttonSubmit);

    //adding validation to edittexts
    awesomeValidation.addValidation(this, R.id.editTextEmail, Patterns.EMAIL_ADDRESS, R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextMobile, "^[2-9]{2}[0-9]{8}$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextDob, "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextAge, Range.closed(13, 60), R.string.ageerror);

    buttonSubmit.setOnClickListener(this);
}

private void submitForm() {
    //first validate the form then move ahead
    //if this becomes true that means validation is successfull
    if (awesomeValidation.validate()) {
        Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
        //process the data further
    }
}

@Override
public void onClick(View view) {
    if (view == buttonSubmit) {
        submitForm();
    }
}
}
</code>```

答:
1. You can check image is selected or not in onActivityResult()

2. so just override the onActivityResult()

3. In data, if you selected the image then it will have the path of image otherwise it will be null

Note: I have used Glide library for display image. (This part is optional )    So just add it in build.gradle(Module App)

compile 'com.github.bumptech.glide:glide:3.7.0'

```<code>   Uri filePath;// class variable

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            // set selected image in image view
            filePath = data.getData();
            Glide.with(MainActivity.this).load(filePath).into(imafeView);
        } else {
            // set default or any error image in image view
            Glide.with(MainActivity.this).load(R.drawable.err_image_name).into(imafeView);
            Log.e(TAG, "nothing Selected: ");
        }
    }
</code>```

Body:
validation: Login Form :
I am able validate the email :if there is error, it should not go to next page.

But,There is one field. Imageview.  i picked  an image from the gallery and set it to imageview.  there is also no probem.

When there is no  image in Imageview,  it should rise the error because of no image which is like email validation.
How validate Imageview like login validation

it should not move to next page ...

..How is it possible. any help? thank's in advance.
I can validate successfully with below code like that Imageview which i want.

enter code here

public class MainActivity extends AppCompatActivity
  implements View.OnClickListener {

//The view objects
private EditText editTextName, editTextEmail, editTextMobile,
        editTextDob, editTextAge;

private Button buttonSubmit;

//defining AwesomeValidation object
private AwesomeValidation awesomeValidation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //initializing awesomevalidation object
    /*        awesomeValidation.addValidation(this, R.id.editTextName, "^[A-Za-z\\s]{1,}[\\.]{0,1}[A-Za-z\\s]{0,}$", R.string.nameerror);

    * The library provides 3 types of validation
    * BASIC
    * COLORATION
    * UNDERLABEL
    * */
    awesomeValidation = new AwesomeValidation(ValidationStyle.BASIC);

    //initializing view objects
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextMobile = (EditText) findViewById(R.id.editTextMobile);
    editTextDob = (EditText) findViewById(R.id.editTextDob);
    editTextAge = (EditText) findViewById(R.id.editTextAge);

    buttonSubmit = (Button) findViewById(R.id.buttonSubmit);

    //adding validation to edittexts
    awesomeValidation.addValidation(this, R.id.editTextEmail, Patterns.EMAIL_ADDRESS, R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextMobile, "^[2-9]{2}[0-9]{8}$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextDob, "^(?:(?:31(\\/|-|\\.)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)(\\/|-|\\.)(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29(\\/|-|\\.)0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])(\\/|-|\\.)(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$", R.string.nameerror);
    awesomeValidation.addValidation(this, R.id.editTextAge, Range.closed(13, 60), R.string.ageerror);

    buttonSubmit.setOnClickListener(this);
}

private void submitForm() {
    //first validate the form then move ahead
    //if this becomes true that means validation is successfull
    if (awesomeValidation.validate()) {
        Toast.makeText(this, "Validation Successfull", Toast.LENGTH_LONG).show();
        //process the data further
    }
}

@Override
public void onClick(View view) {
    if (view == buttonSubmit) {
        submitForm();
    }
}
}

Body:
1. You can check image is selected or not in onActivityResult()

2. so just override the onActivityResult()

3. In data, if you selected the image then it will have the path of image otherwise it will be null

Note: I have used Glide library for display image. (This part is optional )    So just add it in build.gradle(Module App)

compile 'com.github.bumptech.glide:glide:3.7.0'

   Uri filePath;// class variable

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            // set selected image in image view
            filePath = data.getData();
            Glide.with(MainActivity.this).load(filePath).into(imafeView);
        } else {
            // set default or any error image in image view
            Glide.with(MainActivity.this).load(R.drawable.err_image_name).into(imafeView);
            Log.e(TAG, "nothing Selected: ");
        }
    }


问:
Angular.js animations
I have a block with ng-repeat that is defined like this:

```<code><div ng-show="isPageSelected(item.page)" class="block" ng-repeat="item in data">
  ...
</div>
</code>```

Currently I can switch between those blocks, by clicking certain elements. It works via ng-show="isPageSelected(item.page)" as you might have guessed. It all works fine, but they are switching instantly and I want to add an animation, a simple fade in/fade out will do.

So, the block that is no longer selected should fade out and when it's gone a new block should fade in. When I'm using ngAnimate they fade in and fade out simultaneously. I need the first block to disappear completely and be hidden with display: none; and when it's done the next block should appear and fade in. It's a rather straightforward task when using jQuery, but how do I do that elegantly with Angular.js?

I have a strong suspicion that Angular.js isn't exactly a good choice for a site with complex animations.

EDIT: To simplify my question, all I need to do is

On a button click start an animation;

When an animation has been finished, change model;

Run another animation.

Since I need to change the model after an animation, it's probably not possible to do it via pure CSS. The only way I know of triggering animations on specific elements in angular is to create a directive, pass a scope variable into the directive, create watcher for that variable in the directive and then change the variable from the controller:

```<code><div animation="page"></div>
</code>```

```<code>app.directive('animation', function(){
    return {
        scope: { page: '=animation' },
        link: function(scope, element){
            scope.$watch('page', function(newVal){
                ...
            });
        }
    };
});
</code>```

I guess it would work, but it seems really bloated to create a directive just for that. Also, how would I change $scope.page with this approach only when the animation has been finished? Add another scope variable just to trigger an animation and somehow change $scope.page when an animation has been finished? It's possible to do it with ngFx module, but the amount of code it takes is just ridiculous. At this point I think adding jQuery animations to the controller would be a prettier way to solve it.

EDIT: That's how it looks like with jQuery animations:

```<code>$scope.changePage = function(page) {
  $('.block').animate({opacity: 0}, 500, function(){
    $scope.page.id = page;
    $scope.$apply();
    $(this).animate({opacity: 1}, 500);
  });
};
</code>```

It works fine and it's not quite as verbose as the way with directives, but I have to use CSS selectors and that's just feels very "unangular". Do you guys use something similar when dealing with animations?

EDIT: Somewhat similar approach using ngFx:

```<code>    <div ng-hide="switchPageAnimation"
             class="block fx-fade-normal fx-speed-300 fx-trigger">
</code>```

In the controller:

```<code>  $scope.switchPageAnimation = false;

  $scope.changePage = function(page) {
    if($scope.page.id === page || $scope.switchPageAnimation) return;
    $scope.switchPageAnimation = true;
    $scope.$on('fade-normal:enter', function(){
      $scope.page.id = page;
      $scope.switchPageAnimation = false;
    });
  };
</code>```

I'm not using CSS selectors, but still it looks awful. I have to define a scope variable for the animation and then check if the animation is already running. I feel like I am missing something really obvious.

答: Effectively you have to use CSS for showing and hiding elements from your ng-repeat; when you use ngAnimate, do not forget to inject it in your module.</p>

Title: Angular.js animations

Body:
I have a block with ng-repeat that is defined like this:

  ...

Currently I can switch between those blocks, by clicking certain elements. It works via ng-show="isPageSelected(item.page)" as you might have guessed. It all works fine, but they are switching instantly and I want to add an animation, a simple fade in/fade out will do.

So, the block that is no longer selected should fade out and when it's gone a new block should fade in. When I'm using ngAnimate they fade in and fade out simultaneously. I need the first block to disappear completely and be hidden with display: none; and when it's done the next block should appear and fade in. It's a rather straightforward task when using jQuery, but how do I do that elegantly with Angular.js?

I have a strong suspicion that Angular.js isn't exactly a good choice for a site with complex animations.

EDIT: To simplify my question, all I need to do is

On a button click start an animation;

When an animation has been finished, change model;

Run another animation.

Since I need to change the model after an animation, it's probably not possible to do it via pure CSS. The only way I know of triggering animations on specific elements in angular is to create a directive, pass a scope variable into the directive, create watcher for that variable in the directive and then change the variable from the controller:

app.directive('animation', function(){
    return {
        scope: { page: '=animation' },
        link: function(scope, element){
            scope.$watch('page', function(newVal){
                ...
            });
        }
    };
});

I guess it would work, but it seems really bloated to create a directive just for that. Also, how would I change $scope.page with this approach only when the animation has been finished? Add another scope variable just to trigger an animation and somehow change $scope.page when an animation has been finished? It's possible to do it with ngFx module, but the amount of code it takes is just ridiculous. At this point I think adding jQuery animations to the controller would be a prettier way to solve it.

EDIT: That's how it looks like with jQuery animations:

$scope.changePage = function(page) {
  $('.block').animate({opacity: 0}, 500, function(){
    $scope.page.id = page;
    $scope.$apply();
    $(this).animate({opacity: 1}, 500);
  });
};

It works fine and it's not quite as verbose as the way with directives, but I have to use CSS selectors and that's just feels very "unangular". Do you guys use something similar when dealing with animations?

EDIT: Somewhat similar approach using ngFx:

In the controller:

  $scope.switchPageAnimation = false;

  $scope.changePage = function(page) {
    if($scope.page.id === page || $scope.switchPageAnimation) return;
    $scope.switchPageAnimation = true;
    $scope.$on('fade-normal:enter', function(){
      $scope.page.id = page;
      $scope.switchPageAnimation = false;
    });
  };

I'm not using CSS selectors, but still it looks awful. I have to define a scope variable for the animation and then check if the animation is already running. I feel like I am missing something really obvious.


问:
Django migrations not detecting all changes
I have the following models.
BaseClass1 and BaseClass2 are abstract models used by models.

In this case, the model AdBreak is used by a viewset and a serializer.
When I run python manage.py makemigrations, the changes on AdBreak model is detected. The model AdBreakStatus is not getting created.

Since, AdBreakStatus is linked to AdBreak, I am expecting a migration for AdBreakStatus also. Is my understanding wrong?

Edit

In the initial state, there was only AdBreak and BaseClass1 model. The new state, AdBreakStatus and BaseClass2 models were added. Some of the fields from AdBreak were moved to AdBreakStatus.

Thanks in advance for the help.

```<code>class BaseClass1(models.Model):
    class Meta:
        abstract=True
    timestamp = models.DateTimeField(auto_now_add=True)

class BaseClass2(models.Model):
    class Meta:
        abstract=True
    other_field = models.IntegerField()

class AdBreak(BaseClass1):
    class Meta:
        db_table = "ad_break"
    ad_break_id = models.AutoField(primary_key=True)
    ... # Other fields

class AdBreakStatus(BaseClass2):
    class Meta:
        db_table = "ad_break_status"
    ad_break = models.ForeignKey(AdBreak)
    ... # Other Fields
</code>```

答:
delete the migrations folder and sqlite file.  then run </p>

```<code>python manage.py makemigrations 'app_name'
python manage.py migrate
</code>```

Body:
I have the following models.
BaseClass1 and BaseClass2 are abstract models used by models.

In this case, the model AdBreak is used by a viewset and a serializer.
When I run python manage.py makemigrations, the changes on AdBreak model is detected. The model AdBreakStatus is not getting created.

Since, AdBreakStatus is linked to AdBreak, I am expecting a migration for AdBreakStatus also. Is my understanding wrong?

Edit

In the initial state, there was only AdBreak and BaseClass1 model. The new state, AdBreakStatus and BaseClass2 models were added. Some of the fields from AdBreak were moved to AdBreakStatus.

Thanks in advance for the help.

class BaseClass1(models.Model):
    class Meta:
        abstract=True
    timestamp = models.DateTimeField(auto_now_add=True)

class BaseClass2(models.Model):
    class Meta:
        abstract=True
    other_field = models.IntegerField()

class AdBreak(BaseClass1):
    class Meta:
        db_table = "ad_break"
    ad_break_id = models.AutoField(primary_key=True)
    ... # Other fields

class AdBreakStatus(BaseClass2):
    class Meta:
        db_table = "ad_break_status"
    ad_break = models.ForeignKey(AdBreak)
    ... # Other Fields

Body:
delete the migrations folder and sqlite file.  then run

python manage.py makemigrations 'app_name'
python manage.py migrate


答:
your compiler is looking for a Class called Main in a package called javaapplication1.

What you posted doesn't fit this at all.

Classes must be in a file with the name of the class.java.

Thus your class should be in a file called HelloWorldApp.java in the default package.
From your stack trace this is not the case and appears to be in a file called Main.java in a package called javaaplication1


问:
Trying to create astro data over a specific region using Python
Suppose there is a geo region X. The celestial bodies move over that region over the year and, of course, the bodies do not remain the same or in the same position. I am trying to build a 2/3-D chart that maps the movement of the bodies over X (and given a certain time and place within X, show the bodies and their location at that time and place). I plan to do this using Python but at the same time lack knowledge of astronomy - Can I do it? Any pointers/modules/tutorials would help. Thanks.  </p>

答: I would suggest you to have a glance at the opensource astronomy package stellarium with which you could simulate the sky for a given location for a given body. There should also be a documentation that accompanies that which could be helpful in getting yourself familiarised with the adopted algorithms. </p>


问:
How do I use adb grant or adb revoke?
The Android documentation contains the following description of the adb grant and adb revoke commands.

```<code>grant <PACKAGE_PERMISSION>
</code>```

Grant permissions to applications. Only optional permissions the application has declared can be granted.

```<code>revoke <PACKAGE_PERMISSION>
</code>```

Revoke permissions to applications. Only optional permissions the application has declared can be revoked.

Can anybody please give an example of the correct syntax to use them?

I assume that  would be a permission like android.permission.WRITE_EXTERNAL_STORAGE, or perhaps just WRITE_EXTERNAL_STORAGE.  Well I tried those, and several others and I cannot get it to work.

I also tried (to no avail) several combinations of package and permission, which makes more sense to me (this sounds like a command that would modify a permission on one package, not all)

答:
If you happen to not know the name of permission or want to clear all permissions you can use

```<code>adb shell pm reset-permissions
</code>```

WARNING: This will reset run-time permissions for all the apps on your phone. You cannot reset for a specific package.

Title: How do I use adb grant or adb revoke?

Body:
The Android documentation contains the following description of the adb grant and adb revoke commands.

grant <PACKAGE_PERMISSION>

Grant permissions to applications. Only optional permissions the application has declared can be granted.

revoke <PACKAGE_PERMISSION>

Revoke permissions to applications. Only optional permissions the application has declared can be revoked.

Can anybody please give an example of the correct syntax to use them?

I assume that  would be a permission like android.permission.WRITE_EXTERNAL_STORAGE, or perhaps just WRITE_EXTERNAL_STORAGE.  Well I tried those, and several others and I cannot get it to work.

I also tried (to no avail) several combinations of package and permission, which makes more sense to me (this sounds like a command that would modify a permission on one package, not all)

Body:
If you happen to not know the name of permission or want to clear all permissions you can use

adb shell pm reset-permissions

WARNING: This will reset run-time permissions for all the apps on your phone. You cannot reset for a specific package.

ContentLicense: CC BY-SA 4.0


问:
Is there a better way to do these mySql updates?
```<code>    executeSQL("UPDATE records SET played = played + 1 WHERE player IN " + generateClause(all));
    executeSQL("UPDATE records SET wins = wins + 1 WHERE player IN " + generateClause(r.getWinners()));
    executeSQL("UPDATE records SET winrate = ((wins/played) * 1000) WHERE player IN " + generateClause(all));
</code>```

Basically i'm trying to update the records of the players after a match. My program works as expected but it seems to require 3 queries, i'd want to do just one if possible since i've figured out that less queries drastically reduces the runtime of the app, even if the modifications to the db are the same.

My queries are as follows...
1) increase the "played" count for all the players that have played
2) add a win for the players that have won
3) calculate the winrate for all players that have just played

any advice would be appreciated

答:
You could use a CASE statement to manage the wins incrementing players and the WHERE statement to increment everyone else:

```<code>executeSQL = "UPDATE records SET played = played + 1, wins = wins + CASE WHEN player in " + generateClause(r.getWinners) + " THEN 1 ELSE 0 END, winrate = ((wins/played) * 1000) WHERE  player in " + generateClause(all))
</code>```

Body:
    executeSQL("UPDATE records SET played = played + 1 WHERE player IN " + generateClause(all));
    executeSQL("UPDATE records SET wins = wins + 1 WHERE player IN " + generateClause(r.getWinners()));
    executeSQL("UPDATE records SET winrate = ((wins/played) * 1000) WHERE player IN " + generateClause(all));

Basically i'm trying to update the records of the players after a match. My program works as expected but it seems to require 3 queries, i'd want to do just one if possible since i've figured out that less queries drastically reduces the runtime of the app, even if the modifications to the db are the same.

My queries are as follows...
1) increase the "played" count for all the players that have played
2) add a win for the players that have won
3) calculate the winrate for all players that have just played

any advice would be appreciated

Body:
You could use a CASE statement to manage the wins incrementing players and the WHERE statement to increment everyone else:

executeSQL = "UPDATE records SET played = played + 1, wins = wins + CASE WHEN player in " + generateClause(r.getWinners) + " THEN 1 ELSE 0 END, winrate = ((wins/played) * 1000) WHERE  player in " + generateClause(all))


问:
`display: none` vs conditional render in React
I'm having trouble deciding the difference between these two patterns of rendering in React. Hopefully someone can shed some light on this matter.

Pattern 1: React's Conditional Render

https://facebook.github.io/react/docs/conditional-rendering.html

class List extends React.Component {
  state = {
    menu: false,
  }
  handleMouseOver = () => {
    this.setState({
      menu: true
    });
  }
  handleMouseLeave = () => {
    this.setState({
      menu: false
    });
  }
  render() {
    const { menu } = this.state;

    return (

        {menu && <Menu />}

    );
  }
}
```

<p><strong>Pattern 2:</strong> <code>display: none</code></p>

<pre class="lang-css prettyprint-override"><code>.menu {
  display: none;
}

.li:hover .menu {
  display: block;
}
</code>```

const List = () => (

<Menu className="menu"/>

);
```

Question:

If I need to render 100 of these items in a single page, which pattern should I go for?

How can I determine which pattern is better?

Are there any performance benefit of using one over the other?

答:
I tend to use display: none in situations where there's a simple condition to show something (e.g hover, etc).
If it's a bit more complex (e.g. click a checkbox to hide an element) then I go with conditional rendering.
The reason behind this is that I don't want to cause state changes and trigger an update for something as trivial as a hover state, and don't want to fiddle around with obscure css classes for things that will have to involve code anyway.

Again, this is my personal preference.

TL;DR: CSS if super simple (e.g. hover), conditional render if more logic involved

Body:
I'm having trouble deciding the difference between these two patterns of rendering in React. Hopefully someone can shed some light on this matter.

Pattern 1: React's Conditional Render

https://facebook.github.io/react/docs/conditional-rendering.html

class List extends React.Component {
  state = {
    menu: false,
  }
  handleMouseOver = () => {
    this.setState({
      menu: true
    });
  }
  handleMouseLeave = () => {
    this.setState({
      menu: false
    });
  }
  render() {
    const { menu } = this.state;

    return (

        {menu && <Menu />}

    );
  }
}

Pattern 2: display: none

.menu {
  display: none;
}

.li:hover .menu {
  display: block;
}

const List = () => (

<Menu className="menu"/>

);

Question:

If I need to render 100 of these items in a single page, which pattern should I go for?

How can I determine which pattern is better?

Are there any performance benefit of using one over the other?


问:
QTableWidget having multiples lines in cell
I'm using a QTableWidget for a simple table. Now each cell should contain two numbers, but I don't want them to be left to right, but for readability on top of each other. I'm using Qt 5.8.

Hence, I tried something like this:

```<code>QTableWidget* table=new QTableWidget;
auto item = new QTableWidgetItem(QString("%1\n%2").arg(1).arg(2));
table->setItem(0, 0, item);
</code>```

Interestingly, the outcome was that the newline \n was completely ignored. I obtain a cell containing 12. Replacing \n by
 didn't helped.

Any idea, what I'm doing wrong/missing?

答: This should work, just try to resize the height of your row to give the item enough space.</p>

Body:
I'm using a QTableWidget for a simple table. Now each cell should contain two numbers, but I don't want them to be left to right, but for readability on top of each other. I'm using Qt 5.8.

Hence, I tried something like this:

QTableWidget* table=new QTableWidget;
auto item = new QTableWidgetItem(QString("%1\n%2").arg(1).arg(2));
table->setItem(0, 0, item);

Interestingly, the outcome was that the newline \n was completely ignored. I obtain a cell containing 12. Replacing \n by
 didn't helped.

Any idea, what I'm doing wrong/missing?


问:
fetching data and show in view page

when i execute while loop in view page this below error show
  Message: mysql_fetch_array() expects parameter 1 to be resource, array given

my model

```<code>function get_row($id) {
    $this->db->select("*");
    $this->db->from('pending_list');
    $this->db->where('id',$id);
    $query = $this->db->get();
    return $query->result_array();
}
</code>```

my controller

```<code>public function pass_print() {
    $id = $this->uri->segment(3);

    $data['h'] = $this->admin_model->get_row($id);
    $this->load->view('header');
    $this->load->view('sidebar');
    $this->load->view('print_pass',$data);
    $this->load->view('footer');
}
</code>```

my view

```<code><?php while($rows= mysql_fetch_array($h)){?>
                                        <div class="form-group">
                                            <label for="inputEmail3" class="col-sm-3 control-label">
                                                Visitors Name</label>
                                            <div class="col-sm-9">
                                                <input type="text" class="form-control" id="inputEmail3" value="<?php $rows['visitor_name']?>" name="visitor" placeholder="Visitors Name">
                                            </div>
                                        </div>
<?php}?>
</code>```

答:
In Model: You are defining "select" function in Model which is not calling in the controller

```<code>function select() {
$this->db->select("emp_name,department");
$this->db->from('employee');
$query = $this->db->get();
return $query->result_array();
}
</code>```

In Controller: You need to put all the get rows information into a variable named "$h". replace $data['h'] with $h.

```<code>public function pass_print() {
$id = $this->uri->segment(3);
$h = $this->admin_model->get_row($id);
$this->load->view('header');
$this->load->view('sidebar');
$this->load->view('print_pass',$data);
$this->load->view('footer');
}
</code>```

In View: Used the foreach loop in place of while loop which gives the right result.

```<code><?php foreach($h as $data){?>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Visitors Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputEmail3" value="<?php $data['visitor_name']?>" name="visitor" placeholder="Visitors Name">
</div>
</div>
<?php}?>
</code>```

Title: fetching data and show in view page

Body:
when i execute while loop in view page this below error show
  Message: mysql_fetch_array() expects parameter 1 to be resource, array given

my model

function get_row($id) {
    $this->db->select("*");
    $this->db->from('pending_list');
    $this->db->where('id',$id);
    $query = $this->db->get();
    return $query->result_array();
}

my controller

public function pass_print() {
    $id = $this->uri->segment(3);

    $data['h'] = $this->admin_model->get_row($id);
    $this->load->view('header');
    $this->load->view('sidebar');
    $this->load->view('print_pass',$data);
    $this->load->view('footer');
}

my view

<?php while($rows= mysql_fetch_array($h)){?>

                                                Visitors Name

                                                <input type="text" class="form-control" id="inputEmail3" value="<?php $rows['visitor_name']?>" name="visitor" placeholder="Visitors Name">

<?php}?>

Body:
In Model: You are defining "select" function in Model which is not calling in the controller

function select() {
$this->db->select("emp_name,department");
$this->db->from('employee');
$query = $this->db->get();
return $query->result_array();
}

In Controller: You need to put all the get rows information into a variable named "$h". replace $data['h'] with $h.

public function pass_print() {
$id = $this->uri->segment(3);
$h = $this->admin_model->get_row($id);
$this->load->view('header');
$this->load->view('sidebar');
$this->load->view('print_pass',$data);
$this->load->view('footer');
}

In View: Used the foreach loop in place of while loop which gives the right result.

<?php foreach($h as $data){?>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Visitors Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="inputEmail3" value="<?php $data['visitor_name']?>" name="visitor" placeholder="Visitors Name">
</div>
</div>
<?php}?>


问:
ruby - delete all files with names matching a pattern
I have multiple files (in a folder containing thousands of files), ex:

```<code>...
page_bonus.txt
page_code1.txt
page_code2.txt
page_text1.txt
page_text2.txt
page_text3.txt
...
</code>```

How do I delete all page_code* files?

Note: I do not wish to use FileUtils or shell

答:
To delete files with a wildcard.

```<code>Dir.glob("/tmp/files/*").select{ |file| /MY STRING/.match file }.each { |file| File.delete(file)}
</code>```

The regular expression within the select is used to grab the files you want.

Body:
I have multiple files (in a folder containing thousands of files), ex:

...
page_bonus.txt
page_code1.txt
page_code2.txt
page_text1.txt
page_text2.txt
page_text3.txt
...

How do I delete all page_code* files?

Note: I do not wish to use FileUtils or shell

Body:
To delete files with a wildcard.

Dir.glob("/tmp/files/*").select{ |file| /MY STRING/.match file }.each { |file| File.delete(file)}

The regular expression within the select is used to grab the files you want.


问:
Create "x" number of new tabs. Then in main tab, sum all E13s from sheet1:sheetX
We need a macro that will create "X" number of tabs that will be titled "batch 1" to "batch "X"".  An integer is entered in cell "A15" that will say how many tabs will be made.  Then in a cell in the first tab we need to take the sum of all of the E13 cells created from the number inputted in "A15."  The code below creates "X" number of tabs but we're stuck on how to add the E13 values together.  =SUM("Batch 1":"Batch X"!E13) is my best guess but I am trying to figure out how to define a variable "X" to be equal to the integer in cell "A15."  Thanks in advance!

```<code>Dim i As Integer
For i = 1 To Sheet1.Range("A15").Value
    Sheets("Resource Estimator").Copy After:=Sheets(Sheets.Count)
    ActiveSheet.Name = "Batch" & " " & i
Next i
</code>```

答:
You will need to create the SUM formula with VBA within the loop.

```<code>Sub Create()
    Dim i As Integer, SumFormula As String
    For i = 1 To Sheet1.Range("A15").Value
        Sheets("Resource Estimator").Copy After:=Sheets(Sheets.Count)
        ActiveSheet.Name = "Batch " & i

        If i = 1 Then
            SumFormula = "=SUM('" & ActiveSheet.Name & "'!E13" 'begin sum formula
        Else
            SumFormula = SumFormula & ",'" & ActiveSheet.Name & "'!E13" 'iterate sum formula
        End If
    Next i

    SumFormula = SumFormula & ")" 'end sum formula
    Sheet1.Range("A16").Formula = SumFormula 'write sum formula to cell A16
End Sub
</code>```

Here in the first iteration (i = 1) of the for loop the creation of the sum formula begins with =SUM('Batch 1'!E13 for all other sheets the sum formula is extended by ,'Batch i'!E13 where i is the sheet number. And in the end the formula is ended with a bracket ) and written into range A16.

Body:
We need a macro that will create "X" number of tabs that will be titled "batch 1" to "batch "X"".  An integer is entered in cell "A15" that will say how many tabs will be made.  Then in a cell in the first tab we need to take the sum of all of the E13 cells created from the number inputted in "A15."  The code below creates "X" number of tabs but we're stuck on how to add the E13 values together.  =SUM("Batch 1":"Batch X"!E13) is my best guess but I am trying to figure out how to define a variable "X" to be equal to the integer in cell "A15."  Thanks in advance!

Dim i As Integer
For i = 1 To Sheet1.Range("A15").Value
    Sheets("Resource Estimator").Copy After:=Sheets(Sheets.Count)
    ActiveSheet.Name = "Batch" & " " & i
Next i

Body:
You will need to create the SUM formula with VBA within the loop.

Sub Create()
    Dim i As Integer, SumFormula As String
    For i = 1 To Sheet1.Range("A15").Value
        Sheets("Resource Estimator").Copy After:=Sheets(Sheets.Count)
        ActiveSheet.Name = "Batch " & i

        If i = 1 Then
            SumFormula = "=SUM('" & ActiveSheet.Name & "'!E13" 'begin sum formula
        Else
            SumFormula = SumFormula & ",'" & ActiveSheet.Name & "'!E13" 'iterate sum formula
        End If
    Next i

    SumFormula = SumFormula & ")" 'end sum formula
    Sheet1.Range("A16").Formula = SumFormula 'write sum formula to cell A16
End Sub

Here in the first iteration (i = 1) of the for loop the creation of the sum formula begins with =SUM('Batch 1'!E13 for all other sheets the sum formula is extended by ,'Batch i'!E13 where i is the sheet number. And in the end the formula is ended with a bracket ) and written into range A16.