问:
Spinner with an empty default selection
I have a Spinner which gets populate using a SimpleCursorAdapter. My cursor has some values, but i need the Spinner to show an empty option by default.

I don't want to use ArrayAdapter<String>, or CursorWrapper in this app, for some reason.

There should be a simpler way to show an empty option in the Spinner by default.

答:
Create a NullSpinnerItem class and inject it at the start of the list.

```<code>// Class to represent the `null` selection in a List of items in a Spinner.
// There is no easy way to tell Spinner to also include a blank or null value.
// This allows us to inject this as the first item in the List and handle null values easily.
//
public class NullSpinnerItem {

  @Override
  public String toString() {
    return "None";
  }

}
</code>```

Then when you're populating your spinner, just get your items and then add it to the first position:

```<code>items.add( 0, new NullSpinnerItem() ); // items are your items.

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource( R.layout.spinner_list_item);

Spinner spinner = (Spinner) findViewById(spinnerId);
spinner.setAdapter(adapter);
</code>```

The toString() method is what is displayed in the Spinner.

Title: Spinner with an empty default selection

Body:
Create a NullSpinnerItem class and inject it at the start of the list.

// Class to represent the `null` selection in a List of items in a Spinner.
// There is no easy way to tell Spinner to also include a blank or null value.
// This allows us to inject this as the first item in the List and handle null values easily.
//
public class NullSpinnerItem {

  @Override
  public String toString() {
    return "None";
  }

}

Then when you're populating your spinner, just get your items and then add it to the first position:

items.add( 0, new NullSpinnerItem() ); // items are your items.

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource( R.layout.spinner_list_item);

Spinner spinner = (Spinner) findViewById(spinnerId);
spinner.setAdapter(adapter);

The toString() method is what is displayed in the Spinner.


来源: stackexchange

问:
Iterating through a vector and cast enum to integer
I have a vector of enums that I want to cast to an integer value so I can do a numerical comparison.

I keep running into borrowing warnings "cannot move out of borrowed context"

I have tried various permutations of the following:

```<code>enum SomeEnum {
    A,
    B,
    C,
}

let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.iter() {
  let i = *val as i32;
  // if i < X do something
}
</code>```

答:
When you call values.iter(), you take a reference to the Vector as a slice because it impls Deref<Target=[T]>. It returns an Iterator over &T, which is borrowed. Then, you try the following line:

let i = *val as i32;
```

<p>There is a problem with this: <code>val</code> is of type <code>&SomeEnum</code>, and therefore you cannot move the value out of the reference, <em>or</em> copy it, because <code>SomeEnum</code> doesn't impl <code>Copy</code> or <code>Clone</code>. To solve this issue, you can choose from the following, depending on the scenario:</p>

<ul>
<li><code>Copy</code> the value, by making the <code>enum</code> <code>Copy</code>. Making it do this results in allowing rust to implicitly copy the value, bitwise. </li>
</ul>

<pre class="lang-rust prettyprint-override"><code>#[derive(Copy)]
enum SomeEnum {
    A,
    B,
    C,
}
</code>```

Use Iterator::copied extension on the iterator. This copies each value, making it so that the iterator yields T instead of &T. Note too that this is a nightly api currently, so you will have to wait a little longer for it to become stable.

#[derive(Copy)]
enum SomeEnum {
    A,
    B,
    C,
}
let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.iter().copied() {
    let i = val as i32;
}
```

<ul>
<li>Make it clone. <code>Clone</code> is a trait that allows the implementor to <code>impl</code> a way to copy the data, but also perform another operation with it, in the case that simply <code>Copy</code>ing bitwise is unsafe. </li>
</ul>

<pre class="lang-rust prettyprint-override"><code>#[derive(Clone)]
enum SomeEnum {
    A,
    B,
    C,
}
</code>```

Use Iterator::cloned. This is, once again, a similar idea to Iterator::copied, except it Clones the objects and is stable.

#[derive(Clone)]
enum SomeEnum {
    A,
    B,
    C,
}
let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.iter().cloned() {
    let i = val as i32;
}
```

<ul>
<li>Consume the <code>Vec</code>. This makes it so that you can no longer use the <code>Vec</code>, and instead each of the values is consumed in the <code>Vec</code>. This is the least flexible of the approaches, leading to you losing access to <code>values</code> because it is moved into <code>into_iter(self)</code>.</li>
</ul>

```enum SomeEnum {
    A,
    B,
    C,
}
let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.into_iter() {
    let i = val as i32;
}
```

There are a few other ways to tackle this, but these are the simplest.

Other ways of going about this are:

Custom impl of mathematical operations

Implement a From trait, to make it more obvious you're converting.

ContentLicense: CC BY-SA 4.0

Body:
I have a vector of enums that I want to cast to an integer value so I can do a numerical comparison.

I keep running into borrowing warnings "cannot move out of borrowed context"

I have tried various permutations of the following:

enum SomeEnum {
    A,
    B,
    C,
}

let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.iter() {
  let i = *val as i32;
  // if i < X do something
}

Body:
When you call values.iter(), you take a reference to the Vector as a slice because it impls Deref<Target=[T]>. It returns an Iterator over &T, which is borrowed. Then, you try the following line:

let i = *val as i32;

There is a problem with this: val is of type &SomeEnum, and therefore you cannot move the value out of the reference, or copy it, because SomeEnum doesn't impl Copy or Clone. To solve this issue, you can choose from the following, depending on the scenario:

Copy the value, by making the enum Copy. Making it do this results in allowing rust to implicitly copy the value, bitwise.

#[derive(Copy)]
enum SomeEnum {
    A,
    B,
    C,
}

Use Iterator::copied extension on the iterator. This copies each value, making it so that the iterator yields T instead of &T. Note too that this is a nightly api currently, so you will have to wait a little longer for it to become stable.

#[derive(Copy)]
enum SomeEnum {
    A,
    B,
    C,
}
let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.iter().copied() {
    let i = val as i32;
}

Make it clone. Clone is a trait that allows the implementor to impl a way to copy the data, but also perform another operation with it, in the case that simply Copying bitwise is unsafe.

#[derive(Clone)]
enum SomeEnum {
    A,
    B,
    C,
}

Use Iterator::cloned. This is, once again, a similar idea to Iterator::copied, except it Clones the objects and is stable.

#[derive(Clone)]
enum SomeEnum {
    A,
    B,
    C,
}
let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.iter().cloned() {
    let i = val as i32;
}

Consume the Vec. This makes it so that you can no longer use the Vec, and instead each of the values is consumed in the Vec. This is the least flexible of the approaches, leading to you losing access to values because it is moved into into_iter(self).

enum SomeEnum {
    A,
    B,
    C,
}
let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.into_iter() {
    let i = val as i32;
}

There are a few other ways to tackle this, but these are the simplest.

Other ways of going about this are:

Custom impl of mathematical operations

Implement a From trait, to make it more obvious you're converting.


问:
I can't access my Docker container on GCP Compute Engine
I have my Docker container running on GCP Compute Engine. The CE server is running on CentOS 7. My Docker container has the application being served by Nginx with port 80 exposed. For some reason, I can't access it from the external IP address on my browser.
I ran the container with this command:

sudo docker run --name myapp -p 80:80 -d myapp:1.0.0

When I do sudo curl <internal_ip>:80 or sudo curl <localhost>:80 it will show that the application is running and returns back the content, but if I try to access in my browser with <external_ip>:80, it doesn't load anything. What can I do to make this accessible through the external IP address?

答: It seems I had to configure the firewall to open up port 80.</p>


问:
Why is my C++ code wrong to calculate the maximum and minimum of integers?
I am learning the C++ programming language and I am a beginner. I had to write a code so that a user inputs a series of integers and whenever he enters -99, that should signal the end of the series and then my program needs to find the smallest and largest integers. I initially came up with this solution

```<code>#include <iostream>
using namespace std;
int main()
{
    int k=0, number, maximum, minimum;
    do
    {
        cout<<"Enter an integer: ";
        cin>>number;
        if (number==-99)
        {
            break;
        }
        if (k==0)
        {
            maximum=number;
            minimum=number;
        }
        if (number>maximum)
        {
            maximum=number;
        }
        if (number<minimum)
        {
            minimum=number;
        }
        k++;
    }
    while(number!=-99);
    cout<<"The smallest entered integer is "
    <<minimum
    <<" and the largest entered integer is "
    <<maximum
    <<endl;
    return(0);
}
</code>```

and sent it to my lecturer and asked if there is a cleaner way of doing this but he did not reply. Next, I changed this program to find the maximum and minimum using the formulas max(x,y)=(x+y+abs(y-x))/2 and min(x,y)=(x+y-abs(y-x))/2 instead using comparisons.

```<code>#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int k=0, number, maximum, minimum;
    do
    {
        cout<<"Enter an integer: ";
        cin>>number;
        if (number==-99)
        {
            break;
        }
        if (k==0)
        {
            maximum=number;
            minimum=number;
        }
        maximum=(maximum+number+abs(number-maximum))/2;
        minimum=(minimum+number-abs(number-minimum))/2;
        k++;
    }
    while(number!=-99);
    cout<<"The smallest entered integer is "
    <<minimum
    <<" and the largest entered integer is "
    <<maximum
    <<endl;
    return(0);
}
</code>```

but this time my lecturer replied and the only thing he said was that it is wrong. I have tested both of my codes few times and they show me the correct result so I have no clue what my lecturer meant by saying it is wrong. Could someone please let me know why any of the two codes above is wrong and why?

答:
The formulas used in your second code snippet are mathematically correct, but have drawbacks if used in computer programming where variables have limited range.

The first code snippet works across the entire representable set of integers (except -99 for obvious reasons).

The second code snippet will not work for inputs whose absolute value is greater than INT_MIN / -2, because the computations will overflow.

Don't feel bad, this bug is not at all obvious and a lot of programmers have overlooked it.  For a related example, see:

Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken

Unfortunately, if you have this kind of bug in code processing untrusted input, your range checking could fail and lead to a security vulnerability.  So don't go ignoring it just because "I never expect inputs that large".

Body:
I am learning the C++ programming language and I am a beginner. I had to write a code so that a user inputs a series of integers and whenever he enters -99, that should signal the end of the series and then my program needs to find the smallest and largest integers. I initially came up with this solution

#include <iostream>
using namespace std;
int main()
{
    int k=0, number, maximum, minimum;
    do
    {
        cout<<"Enter an integer: ";
        cin>>number;
        if (number==-99)
        {
            break;
        }
        if (k==0)
        {
            maximum=number;
            minimum=number;
        }
        if (number>maximum)
        {
            maximum=number;
        }
        if (number<minimum)
        {
            minimum=number;
        }
        k++;
    }
    while(number!=-99);
    cout<<"The smallest entered integer is "
    <<minimum
    <<" and the largest entered integer is "
    <<maximum
    <<endl;
    return(0);
}

and sent it to my lecturer and asked if there is a cleaner way of doing this but he did not reply. Next, I changed this program to find the maximum and minimum using the formulas max(x,y)=(x+y+abs(y-x))/2 and min(x,y)=(x+y-abs(y-x))/2 instead using comparisons.

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int k=0, number, maximum, minimum;
    do
    {
        cout<<"Enter an integer: ";
        cin>>number;
        if (number==-99)
        {
            break;
        }
        if (k==0)
        {
            maximum=number;
            minimum=number;
        }
        maximum=(maximum+number+abs(number-maximum))/2;
        minimum=(minimum+number-abs(number-minimum))/2;
        k++;
    }
    while(number!=-99);
    cout<<"The smallest entered integer is "
    <<minimum
    <<" and the largest entered integer is "
    <<maximum
    <<endl;
    return(0);
}

but this time my lecturer replied and the only thing he said was that it is wrong. I have tested both of my codes few times and they show me the correct result so I have no clue what my lecturer meant by saying it is wrong. Could someone please let me know why any of the two codes above is wrong and why?


问:
Getting "System.Data.SqlClient is not supported on this platform" when launched as dotnet cli tool
We have a simple netcore 2.2 console application using DbContext from Microsoft.EntityFrameworkCore. When launched from console as is it works as expected.

However we decided to utilize it as a dotnet CLI tool. It's .csproj file contains:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AssemblyName>dotnet-dbupdate</AssemblyName>
    <Title>Db Updater</Title>
    <Version>1.0.1</Version>
    <PackageId>DbUpdater</PackageId>
    <Product>DbUpdater</Product>
    <PackageVersion>1.0.1</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
  </ItemGroup>
</Project>
</code>```

We pack it to our Nuget server with dotnet pack. Then in a target folder we've got the following .csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="DbUpdater" Version="1.0.1" />
  </ItemGroup>
</Project>
</code>```

From this folder we restore it and exec:

```<code>dotnet restore
dotnet dbupdate
</code>```

And suddenly, on DbSet's ToList method invocation we receive:

```<code>System.Data.SqlClient is not supported on this platform
</code>```

Definetely there is an issue with launching it as a dotnet CLI tool. However yet we failed to get what this issue is and how to solve it. Searching on the web did not give us any ideas what to try.

答:
Note that the ToList() method fires the SQL command, say, the first time which he uses the corresponding DLL. So, simply your error says that There's a dependency mismatch for Microsoft.EntityFrameworkCore.SqlServer or System.Data.SqlClient, you know that the second one is a dependency for the first one. There are some dependencies for the second one too, however I think your problem doesn't come from it.

Check out default references (versions) after packing and try to change to a suitable one. Unfortunately, We can't reproduce your problem, so try this solution and let us know the result.

Edit

According to dotnet-pack documentation :

NuGet dependencies of the packed project are added to the .nuspec
  file, so they're properly resolved when the package is installed.
  Project-to-project references aren't packaged inside the project.
  Currently, you must have a package per project if you have
  project-to-project dependencies.

Web projects aren't packable by default. To override the default
  behavior, add the <IsPackable>true</IsPackable> property (inside
  <PropertyGroup>) to your .csproj file.

I think you need to include the following inside your .csproj file :

```<code><ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    <PackageReference Include="System.Data.SqlClient" Version="4.4.0"/>
</ItemGroup>
</code>```

Also, no more need to use dotnet restore based on the following from the dotnet-pack documentation :

Starting with .NET Core 2.0, you don't have to run dotnet restore
  because it's run implicitly by all commands, such as dotnet build and
  dotnet run, that require a restore to occur. It's still a valid
  command in certain scenarios where doing an explicit restore makes
  sense.

Body:
We have a simple netcore 2.2 console application using DbContext from Microsoft.EntityFrameworkCore. When launched from console as is it works as expected.

However we decided to utilize it as a dotnet CLI tool. It's .csproj file contains:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AssemblyName>dotnet-dbupdate</AssemblyName>
    <Title>Db Updater</Title>
    <Version>1.0.1</Version>
    <PackageId>DbUpdater</PackageId>
    <Product>DbUpdater</Product>
    <PackageVersion>1.0.1</PackageVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
  </ItemGroup>
</Project>

We pack it to our Nuget server with dotnet pack. Then in a target folder we've got the following .csproj file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="DbUpdater" Version="1.0.1" />
  </ItemGroup>
</Project>

From this folder we restore it and exec:

dotnet restore
dotnet dbupdate

And suddenly, on DbSet's ToList method invocation we receive:

System.Data.SqlClient is not supported on this platform

Definetely there is an issue with launching it as a dotnet CLI tool. However yet we failed to get what this issue is and how to solve it. Searching on the web did not give us any ideas what to try.

Body:
Note that the ToList() method fires the SQL command, say, the first time which he uses the corresponding DLL. So, simply your error says that There's a dependency mismatch for Microsoft.EntityFrameworkCore.SqlServer or System.Data.SqlClient, you know that the second one is a dependency for the first one. There are some dependencies for the second one too, however I think your problem doesn't come from it.

Check out default references (versions) after packing and try to change to a suitable one. Unfortunately, We can't reproduce your problem, so try this solution and let us know the result.

Edit

According to dotnet-pack documentation :

NuGet dependencies of the packed project are added to the .nuspec
  file, so they're properly resolved when the package is installed.
  Project-to-project references aren't packaged inside the project.
  Currently, you must have a package per project if you have
  project-to-project dependencies.

Web projects aren't packable by default. To override the default
  behavior, add the <IsPackable>true</IsPackable> property (inside
  <PropertyGroup>) to your .csproj file.

I think you need to include the following inside your .csproj file :

<ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="2.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
    <PackageReference Include="System.Data.SqlClient" Version="4.4.0"/>
</ItemGroup>

Also, no more need to use dotnet restore based on the following from the dotnet-pack documentation :

Starting with .NET Core 2.0, you don't have to run dotnet restore
  because it's run implicitly by all commands, such as dotnet build and
  dotnet run, that require a restore to occur. It's still a valid
  command in certain scenarios where doing an explicit restore makes
  sense.


问:
How to get mp4 url on source page?
My page source have this html (js):

```<code><script>
playlist.sources.push({
    label: "480p",
    source: "//zingtv-video-14.zadn.vn/Video480/2016/0418/7c/1f1fd73f7432d7524cb43b57da35d6df.mp4?authen=exp=1559094603~acl=1f1fd73f7432d7524cb43b57da35d6df~hmac=01da84812b2ef7d43e55be79fa3ef56e",
    index: 1
});</script>
</code>```

I want to get:

```<code>//zingtv-video-14.zadn.vn/Video480/2016/0418/7c/1f1fd73f7432d7524cb43b57da35d6df.mp4?authen=exp=1559094603~acl=1f1fd73f7432d7524cb43b57da35d6df~hmac=01da84812b2ef7d43e55be79fa3ef56e
</code>```

My code :

```<code><?php
  // Check if the URL parameter for our proxy is set.
  if (!empty($_GET['url'])) {
    if (filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
      $grabs = file_get_contents("{$_GET['url']}");

      $grab = json_decode($grabs, true);
// I don't know what to do next

      echo "{$video}" />";
    } else {
      echo "Given URL is not valid.";
    }
  } else {
    echo "You need to specify the URL.";
  }
?>
</code>```

and show in the content page.

How do I solve this problem?

答:
Here, we can try using preg_match_all with a simple expression:

```<code>source: "(.+)",
</code>```

where our desired output is saved in a capturing group $1.

Test

```<code>$re = '/source: "(.+)",/m';
$str = '<script>
playlist.sources.push({
    label: "480p",
    source: "//zingtv-video-14.zadn.vn/Video480/2016/0418/7c/1f1fd73f7432d7524cb43b57da35d6df.mp4?authen=exp=1559094603~acl=1f1fd73f7432d7524cb43b57da35d6df~hmac=01da84812b2ef7d43e55be79fa3ef56e",
    index: 1
});</script>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches[0][1]);
</code>```

DEMO

I'm not quite sure if this file_get_content would work:

```<code>$str = file_get_contents('https://tv.zing.vn/video/id/IWZBFE8U.html?t=388');
$str = mb_convert_encoding($str, 'HTML-ENTITIES', "UTF-8");
var_dump($str);
</code>```

Title: How to get mp4 url on source page?

Body:
My page source have this html (js):

I want to get:

//zingtv-video-14.zadn.vn/Video480/2016/0418/7c/1f1fd73f7432d7524cb43b57da35d6df.mp4?authen=exp=1559094603~acl=1f1fd73f7432d7524cb43b57da35d6df~hmac=01da84812b2ef7d43e55be79fa3ef56e

My code :

<?php
  // Check if the URL parameter for our proxy is set.
  if (!empty($_GET['url'])) {
    if (filter_var($_GET['url'], FILTER_VALIDATE_URL)) {
      $grabs = file_get_contents("{$_GET['url']}");

      $grab = json_decode($grabs, true);
// I don't know what to do next

      echo "{$video}" />";
    } else {
      echo "Given URL is not valid.";
    }
  } else {
    echo "You need to specify the URL.";
  }
?>

and show in the content page.

How do I solve this problem?

Body:
Here, we can try using preg_match_all with a simple expression:

source: "(.+)",

where our desired output is saved in a capturing group $1.

Test

$re = '/source: "(.+)",/m';
$str = '<script>
playlist.sources.push({
    label: "480p",
    source: "//zingtv-video-14.zadn.vn/Video480/2016/0418/7c/1f1fd73f7432d7524cb43b57da35d6df.mp4?authen=exp=1559094603~acl=1f1fd73f7432d7524cb43b57da35d6df~hmac=01da84812b2ef7d43e55be79fa3ef56e",
    index: 1
});</script>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches[0][1]);

DEMO

I'm not quite sure if this file_get_content would work:

$str = file_get_contents('https://tv.zing.vn/video/id/IWZBFE8U.html?t=388');
$str = mb_convert_encoding($str, 'HTML-ENTITIES', "UTF-8");
var_dump($str);


问:
Checking if file extension is .xlsx before adding in array
I'm created a loop for me to get the files in a specific folder but I'm wondering how can I make sure that the filenames that will be added in the myArray will only contain .xlsx or .xls?</p>

```<code>Function listFiles(ByVal get_Path As String)

Dim myArray As Variant
Dim i As Integer
Dim counter As Integer
Dim xFile As Object
Dim FileServ As Object
Dim the_Folder As Object
Dim the_Files As Object

Set FileServ = CreateObject("Scripting.FileSystemObject")
Set the_Folder = FileServ.GetFolder(get_Path)
Set the_Files = the_Folder.Files

    'Check if folder is empty
    If the_Files.Count = 0 Then
        Exit Function
    End If

    'Declare the size of Array based on the number of Files inside the folder
    ReDim myArray(1 To the_Files.Count)

    'Loop through each file and assign each filename in Array
    i = 1
    For Each xFile In the_Files
        myArray(i) = xFile.Name
        i = i + 1
    Next

    listFiles = myArray

End Function
</code>```

答:
You can do this:</p>

```<code>i = 0
For Each xFile In the_Files
    If xFile.Name Like "*.xls" or xFile.Name Like "*.xlsx" Then
        i = i + 1
        myArray(i) = xFile.Name
    End If
Next

Redim Preserve myArray(1 to i)
</code>```

Body:
I'm created a loop for me to get the files in a specific folder but I'm wondering how can I make sure that the filenames that will be added in the myArray will only contain .xlsx or .xls?

Function listFiles(ByVal get_Path As String)

Dim myArray As Variant
Dim i As Integer
Dim counter As Integer
Dim xFile As Object
Dim FileServ As Object
Dim the_Folder As Object
Dim the_Files As Object

Set FileServ = CreateObject("Scripting.FileSystemObject")
Set the_Folder = FileServ.GetFolder(get_Path)
Set the_Files = the_Folder.Files

    'Check if folder is empty
    If the_Files.Count = 0 Then
        Exit Function
    End If

    'Declare the size of Array based on the number of Files inside the folder
    ReDim myArray(1 To the_Files.Count)

    'Loop through each file and assign each filename in Array
    i = 1
    For Each xFile In the_Files
        myArray(i) = xFile.Name
        i = i + 1
    Next

    listFiles = myArray

End Function

Body:
You can do this:

i = 0
For Each xFile In the_Files
    If xFile.Name Like "*.xls" or xFile.Name Like "*.xlsx" Then
        i = i + 1
        myArray(i) = xFile.Name
    End If
Next

Redim Preserve myArray(1 to i)


问:
Is it compulsory to install add-on in order to deploy Mongo in Heroku?
Is it compulsory to install add-on in order to deploy Mongo in Heroku like MLAB MongoDB, Compose MongoDB, Object Rocket for MongoDB in order to make the apps run? Because right now I'm having issue deploying my nodejs apps</p>

答: As long as there's a way to connect to your MongoDB instance from Heroku, you don't have to install a Heroku add-on. Set an environment variable (using heroku config) that your code can use to make a connection.


问:
Not getting intellisense for express
I installed using

npm install --save @types/express

and imported in ts file like this

import * as express from "express";
  var app = express();

But I am not getting intelisense on app variable. Also when I'm compiling code the red line under express on import line disappear. But as soon as I start typing something in file the red line re-emerges. Why is it happening?

Here is my tsconfig:

```<code>{
"compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "typeRoots" : ["./node_modules/@types"],
    "moduleResolution": "node"
},
"exclude": [
    "node_modules"
]
}
</code>```

and this is server.ts file:

```<code>import * as express from "express";
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})
</code>```

答:
This question helped me solve the same problem. However, I ran npm install @types/express -D and ended up with the following in package.json:

```<code>"devDependencies": {
      "@types/express": "^4.16.1",
      "@types/node": "^8.0.29",
      "ts-node": "3.3.0",
      "typescript": "3.3.3333"
   }
</code>```

The server.ts file looks fine.

ContentLicense: CC BY-SA 3.0

Title: Not getting intellisense for express

Body:
I installed using

npm install --save @types/express

and imported in ts file like this

import * as express from "express";
  var app = express();

But I am not getting intelisense on app variable. Also when I'm compiling code the red line under express on import line disappear. But as soon as I start typing something in file the red line re-emerges. Why is it happening?

Here is my tsconfig:

{
"compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "typeRoots" : ["./node_modules/@types"],
    "moduleResolution": "node"
},
"exclude": [
    "node_modules"
]
}

and this is server.ts file:

import * as express from "express";
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

Body:
This question helped me solve the same problem. However, I ran npm install @types/express -D and ended up with the following in package.json:

"devDependencies": {
      "@types/express": "^4.16.1",
      "@types/node": "^8.0.29",
      "ts-node": "3.3.0",
      "typescript": "3.3.3333"
   }

The server.ts file looks fine.


问:
How to exclude the first 10 sheets from a spreadsheet?
This script here loops through the sheet names and changes the names to match the value in A1. How can I exclude the first 10 sheet names from the execution instead of providing the specific sheet names to be excluded?</p>

```<code>function onEdit() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  // Array holding the names of the sheets to exclude from the execution
  var exclude =["Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var s in allsheets){
var sheet = allsheets[s];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is meet.
if(exclude.indexOf(sheet.getName())==-1) continue;
  }

} // end of loop

} // end of function
</code>```

答:
Instead of using for(var s in allsheets){

user for(var s=10;i<allsheets.length;i++) {

Body:
This script here loops through the sheet names and changes the names to match the value in A1. How can I exclude the first 10 sheet names from the execution instead of providing the specific sheet names to be excluded?

function onEdit() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  // Array holding the names of the sheets to exclude from the execution
  var exclude =["Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var s in allsheets){
var sheet = allsheets[s];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is meet.
if(exclude.indexOf(sheet.getName())==-1) continue;
  }

} // end of loop

} // end of function


问:
Convert Jupyter notebook into MS word document .doc?
In Jupyter Notebook, I am able to convert a notebook to pdf and HTML using nbconvert. However, there is no way to convert it into .doc(Word Document). Is there a way to convert it to MS Word keeping the same text highlights and table structure?</p>

答:
To convert the Jupyter Notebook to Word

Go to File and download as markdown(.md)

Go to https://cloudconvert.com/md-to-docx and download as doc file


问:
Parsing failing on python for nested avro structure
I have an avro structure which is expecting array structure. I have created the avro structure but the parsing my data into that avro schema is failing

Avro schema

```<code>{
  "namespace": "com",
  "type": "record",
  "name": "customers",
  "fields": [
    {
      "name": "customer",
      "type": {
        "type": "array",
        "items": {
          "name": "cust",
          "type": "record",
          "fields": [
            {
              "name": "age",
              "type": ["long","null"]
            },
            {
              "name": "amount",
              "type": [ "long","null"]
            }
          ]
        }
      }
    }
  ]
}
</code>```

Python Code

list= [[34,2000],[53,8000]]

for l in list

```<code>    writer.append({"customer":{ "age": long(l[0]), "amount": long(l[1])}})
</code>```

is my parsing wrong? should I add any datum object to array?

答:
Figured it out . My avro schema was all good.Only thing is I had to change the was the way I add the objects to the writer.    </p>

```<code>list= [[34,2000],[53,8000]]
customer={}
cust ={}
for l in list
    cust['age']  = l[0]
    cust['amount'] = l[1]
customer.append(cust)
writer.append({"customer": customer})
</code>```

Body:
I have an avro structure which is expecting array structure. I have created the avro structure but the parsing my data into that avro schema is failing

Avro schema

{
  "namespace": "com",
  "type": "record",
  "name": "customers",
  "fields": [
    {
      "name": "customer",
      "type": {
        "type": "array",
        "items": {
          "name": "cust",
          "type": "record",
          "fields": [
            {
              "name": "age",
              "type": ["long","null"]
            },
            {
              "name": "amount",
              "type": [ "long","null"]
            }
          ]
        }
      }
    }
  ]
}

Python Code

list= [[34,2000],[53,8000]]

for l in list

    writer.append({"customer":{ "age": long(l[0]), "amount": long(l[1])}})

is my parsing wrong? should I add any datum object to array?

Body:
Figured it out . My avro schema was all good.Only thing is I had to change the was the way I add the objects to the writer.

list= [[34,2000],[53,8000]]
customer={}
cust ={}
for l in list
    cust['age']  = l[0]
    cust['amount'] = l[1]
customer.append(cust)
writer.append({"customer": customer})


问:
setAttribute is not working for 'style' attribute on IE
I'm porting a piece of JS code written for Firefox into Internet Explorer. I faced a problem of changing style of an element using setAttribute method which was working on Firefox.

```<code>button.setAttribute('style', 'float: right;');
</code>```

I tried setting the style member of button and it didn't work either. This was the solution in case of setting onclick event handler.

```<code>button.style = 'float: right;';
</code>```

First I wanna know the solution for the above problem and

Second are there any maintained lists for these differences between browsers ?

答:
Another useful way to mutate a style property is using the square brackets to access the property. This is useful for accessing properties which because of their name would give a syntax error if expressed normally. In JavaScript it is perfectly permissible to have properties with numeric values, numeric first letters and symbols and spaces as characters, but then you must use the square bracket way of accessing properties.</p>

```<code>node.style.z-index = 50;//Firefox says error, invalid assignment left hand side.

node.style["z-index"] = "50";//Works without error
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm porting a piece of JS code written for Firefox into Internet Explorer. I faced a problem of changing style of an element using setAttribute method which was working on Firefox.

button.setAttribute('style', 'float: right;');

I tried setting the style member of button and it didn't work either. This was the solution in case of setting onclick event handler.

button.style = 'float: right;';

First I wanna know the solution for the above problem and

Second are there any maintained lists for these differences between browsers ?

Body:
Another useful way to mutate a style property is using the square brackets to access the property. This is useful for accessing properties which because of their name would give a syntax error if expressed normally. In JavaScript it is perfectly permissible to have properties with numeric values, numeric first letters and symbols and spaces as characters, but then you must use the square bracket way of accessing properties.

node.style.z-index = 50;//Firefox says error, invalid assignment left hand side.

node.style["z-index"] = "50";//Works without error


问:
What exactly triggers main.ts in Angular
By building a basic Angular CLI project, we get the following index.html when we run the application:

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>SimpleCLI</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
  <script type="text/javascript" src="inline.bundle.js"></script>
  <script type="text/javascript" src="polyfills.bundle.js">
  </script><script type="text/javascript" src="styles.bundle.js"></script>
  <script type="text/javascript" src="vendor.bundle.js"></script>
  <script type="text/javascript" src="main.bundle.js"></script></body>
</html>
</code>```

Next step is our entry point main.ts. Of course the name does not matter and is defined in .angular-cli.json. Could someone clarify the following points?

Is it vendor.bundle.js which contains all Angular code and is responsible for starting the bootstrap process?

Once the bootstrap process starts how exactly the application knows where to go, namely how does it trigger main.ts? Is it only the property

```<code> "main": "main.ts"
</code>```

inside .angular-cli.json which defines that?

答:
In Angular 7 (Angular CLI project), angular.json file contains all project information which contains information about complete project assets. In this file, main can be configured to any type script file which can then act as module starter for the configured application , as an example say start.ts.
Now start.ts will act as starting point for the application module which should ideally responsible for bootstrapping the application using platformBrowserDynamic().bootstrapModule(YourModuleStarter)</p>

Body:
By building a basic Angular CLI project, we get the following index.html when we run the application:

<!doctype html>

  <meta charset="utf-8">
  <title>SimpleCLI</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

Next step is our entry point main.ts. Of course the name does not matter and is defined in .angular-cli.json. Could someone clarify the following points?

Is it vendor.bundle.js which contains all Angular code and is responsible for starting the bootstrap process?

Once the bootstrap process starts how exactly the application knows where to go, namely how does it trigger main.ts? Is it only the property

 "main": "main.ts"

inside .angular-cli.json which defines that?


问:
How to I resolve a deprecation issue?
I'm creating Ansible Playbook for IT Automation.

This is the console output, I am getting:

```<code>Apache web server.

web.yml
- hosts: 192.168.1.80
  remote_user: ksouthall
  become: yes
  become_method: sudo

  tasks:
  - name: Install Apache
    apt:
      name: apache2
      update_cache: yes
  - name: Copying the demo file
    template: src=/etc/ansible/index.html dest=/var/www/html
              owner=www-data group=www-data mode=0644

ansible-playbook web.yml -f 1 --ask-become-pass
BECOME password:
[DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters
in group names by default, this will change, but still be user configurable on deprecation. This
feature will be removed in version 2.10. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
 [WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see
details

 [WARNING]: Could not match supplied host pattern, ignoring: 192.168.1.80

PLAY [192.168.1.80] ******************************************************************************
skipping: no hosts matched

PLAY RECAP ******************************************************************************
</code>```

Question: Is the BECOME password my system password?

答: For --ask-become-pass you need to enter the password for your user on the remote box (assuming you have root-level privilege on that box).

Title: How to I resolve a deprecation issue?

Body:
I'm creating Ansible Playbook for IT Automation.

This is the console output, I am getting:

Apache web server.

web.yml
- hosts: 192.168.1.80
  remote_user: ksouthall
  become: yes
  become_method: sudo

  tasks:
  - name: Install Apache
    apt:
      name: apache2
      update_cache: yes
  - name: Copying the demo file
    template: src=/etc/ansible/index.html dest=/var/www/html
              owner=www-data group=www-data mode=0644

ansible-playbook web.yml -f 1 --ask-become-pass
BECOME password:
[DEPRECATION WARNING]: The TRANSFORM_INVALID_GROUP_CHARS settings is set to allow bad characters
in group names by default, this will change, but still be user configurable on deprecation. This
feature will be removed in version 2.10. Deprecation warnings can be disabled by setting
deprecation_warnings=False in ansible.cfg.
 [WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see
details

 [WARNING]: Could not match supplied host pattern, ignoring: 192.168.1.80

PLAY [192.168.1.80] ******************************************************************************
skipping: no hosts matched

PLAY RECAP ******************************************************************************

Question: Is the BECOME password my system password?


问:
How to measure view or view group inflating time in android?
I am looking for utility or any way how can I measure the time required for inflater to inflate some portion (view or viewgroup or whole screen) in Android.

I know there is default feature in debug mode that shows overdraw, but I need to have measure the time taken to inflate view.

What is the best way to do this.
Thx.

答:
In 2019, you can use android x benchmark library easy for benchmark inflate time.
android doc write-benchmark

```<code>@RunWith(AndroidJUnit4::class)
class ViewBenchmark {
    @get:Rule
    val benchmarkRule = BenchmarkRule()

    @Test
    fun simpleViewInflate() {
        val context = ApplicationProvider.getApplicationContext()
        val inflater = LayoutInflater.from(context)
        val root = FrameLayout(context)

        benchmarkRule.keepRunning {
            inflater.inflate(R.layout.test_simple_view, root, false)
        }
    }
}
</code>```

or you can use system trace to benchmark only inflate layout code

Body:
In 2019, you can use android x benchmark library easy for benchmark inflate time.
android doc write-benchmark

@RunWith(AndroidJUnit4::class)
class ViewBenchmark {
    @get:Rule
    val benchmarkRule = BenchmarkRule()

    @Test
    fun simpleViewInflate() {
        val context = ApplicationProvider.getApplicationContext()
        val inflater = LayoutInflater.from(context)
        val root = FrameLayout(context)

        benchmarkRule.keepRunning {
            inflater.inflate(R.layout.test_simple_view, root, false)
        }
    }
}

or you can use system trace to benchmark only inflate layout code


问:
Instead of using a hard coded values in JavaScript, is it possible to use a cron to do it?
It's probably easiest to understand by looking at this fiddle:

http://jsfiddle.net/TdBdW/1/ - apologies for the lack of css.

As you can see, for my dynamically generated dropdowns and textboxes I have a big list of hardcoded values. I would have liked to have pulled these straight from a database but the queries take too long to run for them to be used in real-time - i.e. when the user clicks on a drop-down or tries to type in the auto-complete box.

Instead what I would like to do is have the relevant queries run nightly using a cron job but the question is how to take the results of the query and put them into my javascript file.

Anyone have any ideas how to implement this?

Any help is greatly appreciated.

Martin

答:
You probably do not want your javascript file to be static. Why not have it dynamically generated by a php script in the same way that html is generated? If it's easier you could just inline the javascript in your html as opposed to loading it as a separate asset.

If you're worried about hitting the db each time for the tag list, you could instead keep your tags in some global object, which is periodically updated.


问:
App will terminate Notification
I'm working on SDK and try to catch app termination Notification. It's easy to get this as closure for (ex) NSNotification.Name.UIApplicationWillResignActive

```<code>self.resignActiveNotification = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillResignActive,
                                                                       object: nil,
                                                                       queue: nil) { _ in
//something goes here and it works like a charm.
}
</code>```

So I want to have similar behavior for termination:

```<code>self.terminateNotification = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillTerminate,
                                                                    object: nil,
                                                                    queue: nil) { _ in
        NSLog("%@",#function)
    }
</code>```

And this one never gets called!

Of course if I put in AppDelegate:

```<code>func applicationWillTerminate(_ application: UIApplication) {
    //termination
}
</code>```

It will work, but since I'm building an SDK I cannot have AppDelegate methods. There is a way to get termination closure call? Or any other way to know that application is about to terminate?

In Apple documentation you can find:

After calling this method, the app also posts a
  UIApplicationWillTerminate notification to give interested objects a
  chance to respond to the transition.

However this seems to be broken

答:
This seems working for me:</p>

```<code>init() {
  NotificationCenter.default.addObserver(self,
      selector: #selector(applicationWillTerminate(notification:)),
      name: UIApplication.willTerminateNotification,
      object: nil)
}

@objc func applicationWillTerminate(notification: Notification) {
  // Notification received.
}

deinit {
  NotificationCenter.default.removeObserver(self)
}
</code>```

Title: App will terminate Notification

Body:
I'm working on SDK and try to catch app termination Notification. It's easy to get this as closure for (ex) NSNotification.Name.UIApplicationWillResignActive

self.resignActiveNotification = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillResignActive,
                                                                       object: nil,
                                                                       queue: nil) { _ in
//something goes here and it works like a charm.
}

So I want to have similar behavior for termination:

self.terminateNotification = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillTerminate,
                                                                    object: nil,
                                                                    queue: nil) { _ in
        NSLog("%@",#function)
    }

And this one never gets called!

Of course if I put in AppDelegate:

func applicationWillTerminate(_ application: UIApplication) {
    //termination
}

It will work, but since I'm building an SDK I cannot have AppDelegate methods. There is a way to get termination closure call? Or any other way to know that application is about to terminate?

In Apple documentation you can find:

After calling this method, the app also posts a
  UIApplicationWillTerminate notification to give interested objects a
  chance to respond to the transition.

However this seems to be broken

Body:
This seems working for me:

init() {
  NotificationCenter.default.addObserver(self,
      selector: #selector(applicationWillTerminate(notification:)),
      name: UIApplication.willTerminateNotification,
      object: nil)
}

@objc func applicationWillTerminate(notification: Notification) {
  // Notification received.
}

deinit {
  NotificationCenter.default.removeObserver(self)
}


问:
Adding blur effect to background in swift
I am setting a background image to view controller. But also i want to add blur effect to this background. How can I do this?

I am setting background with following code:

```<code>self.view.backgroundColor = UIColor(patternImage: UIImage(named: "testBg")!)
</code>```

I found on internet for blur imageview how can i implement this to my background?

```<code>var darkBlur = UIBlurEffect(style: UIBlurEffectStyle.Dark)
// 2
var blurView = UIVisualEffectView(effect: darkBlur)
blurView.frame = imageView.bounds
// 3
imageView.addSubview(blurView)
</code>```

答:
This worked for me on Swift 5

```<code>let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)
</code>```

Body:
I am setting a background image to view controller. But also i want to add blur effect to this background. How can I do this?

I am setting background with following code:

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "testBg")!)

I found on internet for blur imageview how can i implement this to my background?

var darkBlur = UIBlurEffect(style: UIBlurEffectStyle.Dark)
// 2
var blurView = UIVisualEffectView(effect: darkBlur)
blurView.frame = imageView.bounds
// 3
imageView.addSubview(blurView)

Body:
This worked for me on Swift 5

let blurredView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
blurredView.frame = self.view.bounds
backgroundimage.addSubview(blurredView)


问:
Converting day of week to number in R
I'm having trouble converting a .csv column of data with weekdays to a number (so that 1 = Monday, 2 = Tuesday, 3 = Wednesday, etc). I'm trying to use the strptime feature as shown here: http://www.inside-r.org/r-doc/base/strftime

Since I want to convert the weekday to a number, I used the "%u" formatting option. Here's my code below:

```<code>> newweekdaynum <- strptime(SFCrimeData$DayOfWeek, "%u")
</code>```

where SFCrimeData is a data set I have that has a bunch of crime information. No errors come up after I run the statement, but when I want to print "newweekdaynum" all that comes is a huge table of values that all say "NA".

What am I doing wrong?

答:
```<code>df$Date <- as.Date(df$Date)
df$wkdaynum <- format(df$Date,"%u")
df$wkdaynum <- as.numeric(df$wkdaynum)
</code>```

So, your mistake was to use strptime() instead of format().

Title: Converting day of week to number in R

Body:
I'm having trouble converting a .csv column of data with weekdays to a number (so that 1 = Monday, 2 = Tuesday, 3 = Wednesday, etc). I'm trying to use the strptime feature as shown here: http://www.inside-r.org/r-doc/base/strftime

Since I want to convert the weekday to a number, I used the "%u" formatting option. Here's my code below:

> newweekdaynum <- strptime(SFCrimeData$DayOfWeek, "%u")

where SFCrimeData is a data set I have that has a bunch of crime information. No errors come up after I run the statement, but when I want to print "newweekdaynum" all that comes is a huge table of values that all say "NA".

What am I doing wrong?

Body:
df$Date <- as.Date(df$Date)
df$wkdaynum <- format(df$Date,"%u")
df$wkdaynum <- as.numeric(df$wkdaynum)

So, your mistake was to use strptime() instead of format().


问:
Cannot find module 'expo/tools/LogReporter'
I want to run NativeBase's KitchenSink in my device.

So I clone it from git, here is the link: https://github.com/GeekyAnts/NativeBase-KitchenSink

After clone I run npm install and after that npm start. It works fine and tells me to open it on my local host but there I find only this:

The link goes to React Native's main page, nothing special. But I want to see whats going on in my app, so I run npm install -g expo-cli , after that expo start and I got this error:

[13:51:33] Error: Missing app.json. See https://docs.expo.io/

[13:51:33] No Expo configuration found. Are you sure this is a project
  directory?

After that I change my app.json from this:

```<code>{
  "name": "NativebaseKitchenSink",
  "displayName": "NativebaseKitchenSink"
}
</code>```

To this:

```<code>{
  "expo": {
    "name": "My Project Name",
    "slug": "myProjectName",
    "privacy": "public",
    "sdkVersion": "32.0.0",
    "platforms": [
      "ios",
      "android"
    ],
    "version": "1.0.0",
    "orientation": "default",
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],

    "androidStatusBar": {},

    "ios": {
      "supportsTablet": true
    }
  }
}
</code>```

And running expo start gives me this error:

[14:03:28] Cannot find module 'expo/tools/LogReporter'

After that I find some solutions and all they are similar with each other, here is the one of them: https://forums.expo.io/t/solved-cannot-find-module-expo-tools-logreporter/16833

And here: Expo : cannot find a module LogReporter

Even I find the question with exactly the same problem in russian community, and I try the solution from there and it was helpless too, here it is (its in russian): http://qaru.site/questions/2455460/expo-cannot-find-a-module-logreporter

So I will be grateful for the help))

答:
You'r app.json don't look like app.json of expo.
Do you tried react-native run-ios instead of expo start?

You cann't use expo-cli to vanilla react native app.

Body:
I want to run NativeBase's KitchenSink in my device.

So I clone it from git, here is the link: https://github.com/GeekyAnts/NativeBase-KitchenSink

After clone I run npm install and after that npm start. It works fine and tells me to open it on my local host but there I find only this:

The link goes to React Native's main page, nothing special. But I want to see whats going on in my app, so I run npm install -g expo-cli , after that expo start and I got this error:

[13:51:33] Error: Missing app.json. See https://docs.expo.io/

[13:51:33] No Expo configuration found. Are you sure this is a project
  directory?

After that I change my app.json from this:

{
  "name": "NativebaseKitchenSink",
  "displayName": "NativebaseKitchenSink"
}

To this:

{
  "expo": {
    "name": "My Project Name",
    "slug": "myProjectName",
    "privacy": "public",
    "sdkVersion": "32.0.0",
    "platforms": [
      "ios",
      "android"
    ],
    "version": "1.0.0",
    "orientation": "default",
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],

    "androidStatusBar": {},

    "ios": {
      "supportsTablet": true
    }
  }
}

And running expo start gives me this error:

[14:03:28] Cannot find module 'expo/tools/LogReporter'

After that I find some solutions and all they are similar with each other, here is the one of them: https://forums.expo.io/t/solved-cannot-find-module-expo-tools-logreporter/16833

And here: Expo : cannot find a module LogReporter

Even I find the question with exactly the same problem in russian community, and I try the solution from there and it was helpless too, here it is (its in russian): http://qaru.site/questions/2455460/expo-cannot-find-a-module-logreporter

So I will be grateful for the help))


问:
What does "dominant query" mean when related to database tables?
When reading about how to get the most out of Azure Tables, they mention "Avoid scans for dominant queries" as part of their conclusion.

What does it mean by "dominant queries"?

I've seen it mentioned in a few other questions but I do not have enough reputation to comment on other's answers yet so am asking as new question. Feel free to give feedback on that rather than downvoting this question.

答:
"Select the dominant queries and updates based on such criteria as high frequency of execution, high volume of data accessed, response time contraints, or explicit high priority. Remember this rule of thumb: Any process whose frequency of execution or data volume accessed is 10 times that of another process is considered to be dominant."

Quote from book: Database Design: Know It All

Authors: Toby J. Teorey, Stephen Buxton, Lowell Fryman, Ralf Hartmut Güting, Terry Halpin, Jan L. Harrington, W.H. Inmon, Sam S. Lightstone, Jim Melton, Tony Morgan, Thomas P. Nadeau, Bonnie O'Neil, Elizabeth O'Neil, Patrick O'Neil, Markus Schneider, Graeme Simsion, Graham Witt

Publisher: Morgan Kaufmann, 23/10/2008


问:
Tomcat class not found & there is the class in the path WEB-INF\lib
I copied an app from server, then deployed on Tomcat6 (same as the server), but I always get the error! I tried to reinstall Tomcat, but the error is still the same.

error1:

```<code>            2011-4-12 21:36:16 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextInitialized()
2011-4-12 21:36:16 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextInitialized()
2011-4-12 21:36:21 org.apache.catalina.core.ApplicationContext log
信息: Marking servlet AdminServlet as unavailable
2011-4-12 21:36:21 org.apache.catalina.core.ApplicationContext log

严重: Error loading WebappClassLoader
  context: /portal
  delegate: false
  repositories:
    /WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader@1eed786
 org.apache.axis.transport.http.AdminServlet
java.lang.ClassNotFoundException: org.apache.axis.transport.http.AdminServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1493)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1095)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4387)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4700)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1041)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:964)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1061)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:701)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:585)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
2011-4-12 21:36:21 org.apache.catalina.core.StandardContext loadOnStartup

严重: Servlet /portal threw load() exception
java.lang.ClassNotFoundException: org.apache.axis.transport.http.AdminServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1493)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1095)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4387)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4700)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1041)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:964)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1061)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:701)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:585)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
2011-4-12 21:36:54 org.apache.catalina.core.StandardWrapperValve invoke

严重: Servlet.service() for servlet jsp threw exception
java.lang.ClassNotFoundException: org.jdom.input.SAXBuilder
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1493)
    at pde.ams.AmsGlobals.loadProperties(AmsGlobals.java:82)
    at pde.ams.AmsGlobals.getAmsPropertys(AmsGlobals.java:47)
    at pde.ams.AmsEngine.initialize(AmsEngine.java:77)
    at pde.ams.AmsEngine.<init>(AmsEngine.java:61)
    at pde.ams.AmsEngine.getInstance(AmsEngine.java:45)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:90)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at pde.ams.filters.AmsFilter.doFilter(AmsFilter.java:77)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:619)
2011-4-12 21:37:07 org.apache.catalina.core.StandardContext listenerStop
</code>```

error2:

```<code>    严重: Exception sending context destroyed event to listener instance of class pde.ams.ContextListener
java.lang.NullPointerException
    at pde.ams.ContextListener.contextDestroyed(ContextListener.java:15)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4211)
    at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4846)
    at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:932)
    at org.apache.catalina.startup.HostConfig.undeployApps(HostConfig.java:1319)
    at org.apache.catalina.startup.HostConfig.stop(HostConfig.java:1290)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:323)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.stop(ContainerBase.java:1094)
    at org.apache.catalina.core.ContainerBase.stop(ContainerBase.java:1106)
    at org.apache.catalina.core.StandardEngine.stop(StandardEngine.java:468)
    at org.apache.catalina.core.StandardService.stop(StandardService.java:604)
    at org.apache.catalina.core.StandardServer.stop(StandardServer.java:735)
    at org.apache.catalina.startup.Catalina.stop(Catalina.java:652)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:619)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
2011-4-12 21:37:07 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextDestroyed()
2011-4-12 21:37:07 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextDestroyed()

   desc:there are  the classes that could not found by tomcat still in the path /web_inf/lib
</code>```

Question1: What's wrong with it?

Question2: Is there any relation between the error1  and error2?

ok this is compete stack trace

答:
Question1: What's wrong with it?

The first error looks like a bug in the webapp or its configuration.  Tomcat is reporting that something (e.g. one of the servlets) is not tidying up correctly when the webapp is shutdown.  If this is left unfixed, your webserver is liable to run out of memory after a few webapp restarts.

The second error is complaining that some class can't be found.  This is probably a web server or webapp configuration error of some kind.

In both cases, it would help if you showed us the complete stack traces.

Question2: Is there any relation between the error1 and error2?

Probably not.

A little bit of digging tells me that you are likely to find org.apache.axis.transport.http.AdminServlet in a JAR file called axis-x.y.jar or something like that (see http://findjar.com/class/org/apache/axis/transport/http/AdminServlet.html for a complete list)

For org.jdom.input.SAXBuilder look for a file like jdom-x.y.jar (see http://findjar.com/class/org/jdom/input/SAXBuilder.html for a complete list)

The second error is different to the error you originally reported, but it is still a bug in the webapp.  This one could be a consequence of your first error; i.e. it is assuming that the servlet started up properly.

You need to take a look at you webapp as installed on Tomcat and see if the Axis and JDOM JARs are in WEB-INF/lib.  If not, go back to the server you copied the webapp from and look the webapp there ... and in the server's common library area.  (You don't say what kind of server you are copying from ...)

Body:
I copied an app from server, then deployed on Tomcat6 (same as the server), but I always get the error! I tried to reinstall Tomcat, but the error is still the same.

error1:

            2011-4-12 21:36:16 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextInitialized()
2011-4-12 21:36:16 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextInitialized()
2011-4-12 21:36:21 org.apache.catalina.core.ApplicationContext log
信息: Marking servlet AdminServlet as unavailable
2011-4-12 21:36:21 org.apache.catalina.core.ApplicationContext log

严重: Error loading WebappClassLoader
  context: /portal
  delegate: false
  repositories:
    /WEB-INF/classes/
----------> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader@1eed786
 org.apache.axis.transport.http.AdminServlet
java.lang.ClassNotFoundException: org.apache.axis.transport.http.AdminServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1493)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1095)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4387)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4700)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1041)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:964)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1061)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:701)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:585)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
2011-4-12 21:36:21 org.apache.catalina.core.StandardContext loadOnStartup

严重: Servlet /portal threw load() exception
java.lang.ClassNotFoundException: org.apache.axis.transport.http.AdminServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1493)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1095)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:993)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4387)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4700)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1041)
    at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:964)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1061)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:701)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:585)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
2011-4-12 21:36:54 org.apache.catalina.core.StandardWrapperValve invoke

严重: Servlet.service() for servlet jsp threw exception
java.lang.ClassNotFoundException: org.jdom.input.SAXBuilder
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1647)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1493)
    at pde.ams.AmsGlobals.loadProperties(AmsGlobals.java:82)
    at pde.ams.AmsGlobals.getAmsPropertys(AmsGlobals.java:47)
    at pde.ams.AmsEngine.initialize(AmsEngine.java:77)
    at pde.ams.AmsEngine.<init>(AmsEngine.java:61)
    at pde.ams.AmsEngine.getInstance(AmsEngine.java:45)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:90)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at pde.ams.filters.AmsFilter.doFilter(AmsFilter.java:77)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:619)
2011-4-12 21:37:07 org.apache.catalina.core.StandardContext listenerStop

error2:

    严重: Exception sending context destroyed event to listener instance of class pde.ams.ContextListener
java.lang.NullPointerException
    at pde.ams.ContextListener.contextDestroyed(ContextListener.java:15)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4211)
    at org.apache.catalina.core.StandardContext.stop(StandardContext.java:4846)
    at org.apache.catalina.core.ContainerBase.removeChild(ContainerBase.java:932)
    at org.apache.catalina.startup.HostConfig.undeployApps(HostConfig.java:1319)
    at org.apache.catalina.startup.HostConfig.stop(HostConfig.java:1290)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:323)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
    at org.apache.catalina.core.ContainerBase.stop(ContainerBase.java:1094)
    at org.apache.catalina.core.ContainerBase.stop(ContainerBase.java:1106)
    at org.apache.catalina.core.StandardEngine.stop(StandardEngine.java:468)
    at org.apache.catalina.core.StandardService.stop(StandardService.java:604)
    at org.apache.catalina.core.StandardServer.stop(StandardServer.java:735)
    at org.apache.catalina.startup.Catalina.stop(Catalina.java:652)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:619)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
2011-4-12 21:37:07 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextDestroyed()
2011-4-12 21:37:07 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextDestroyed()

   desc:there are  the classes that could not found by tomcat still in the path /web_inf/lib

Question1: What's wrong with it?

Question2: Is there any relation between the error1  and error2?

ok this is compete stack trace


问:
Expose a base class function in qml
I am trying to invoke a function declared in a base class but I am unable to invoke from QML, Here's an example of my code

R.cpp

class R
{

public:
    virtual void startGui() = 0;
    void  toggleCameraView();

};

void R::toggleCameraView(){
  //do stuff
}
```

<p><strong>G.cpp</strong></p>

<pre class="lang-cpp prettyprint-override"><code>class G : public R
{
    Q_OBJECT
public:
  void startGui();
};

void G::startGui(){

  QQmlContext *ctxt = engine.rootContext();
  ctxt->setContextProperty("g", this);
}
</code>```

main.qml

```<code>function toggleCameraView(){
    g.toggleCameraView()
}
</code>```

This is giving me the error:

```<code>TypeError: Property 'toggleCameraView' of object G(0x2838a8) is not a function
</code>```

答:
```<code>function toggleCameraView(){
    g3.toggleCameraView()
}
</code>```

why is "g3" ? it should be "g", the same name in ctxt->setContextProperty("g", this);

Title: Expose a base class function in qml

Body:
I am trying to invoke a function declared in a base class but I am unable to invoke from QML, Here's an example of my code

R.cpp

class R
{

public:
    virtual void startGui() = 0;
    void  toggleCameraView();

};

void R::toggleCameraView(){
  //do stuff
}

G.cpp

class G : public R
{
    Q_OBJECT
public:
  void startGui();
};

void G::startGui(){

  QQmlContext *ctxt = engine.rootContext();
  ctxt->setContextProperty("g", this);
}

main.qml

function toggleCameraView(){
    g.toggleCameraView()
}

This is giving me the error:

TypeError: Property 'toggleCameraView' of object G(0x2838a8) is not a function

Body:
function toggleCameraView(){
    g3.toggleCameraView()
}

why is "g3" ? it should be "g", the same name in ctxt->setContextProperty("g", this);


问:
Not getting connection string in Other classes in asp.net core
In Connection class

public Connection(IConfiguration _Configuration)
{
    dbConnectionString = _Configuration.GetConnectionString("DefaultConnection");
}
```

<p>In Startup class on Configure  Method</p>

<pre class="lang-cs prettyprint-override"><code>services.AddDbContext<Models.AwardContext>(option =>
option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
</code>```

答:
You should firstly add Configuration as a Singleton in ConfigureServices:

```<code> services.AddSingleton(_ => Configuration);
</code>```

Body:
In Connection class

public Connection(IConfiguration _Configuration)
{
    dbConnectionString = _Configuration.GetConnectionString("DefaultConnection");
}

In Startup class on Configure  Method

services.AddDbContext<Models.AwardContext>(option =>
option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Body:
You should firstly add Configuration as a Singleton in ConfigureServices:

 services.AddSingleton(_ => Configuration);


问:
Python: List Comprehension invalid syntax error
I'm trying to recreate this loop in one line:

```<code>results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2]

for x in results:
  total = x + total

print(total)
</code>```

But when I do this:

```<code> y = [total = total + x for x in results]
</code>```

I get an error:

```<code>y = [total = total + x for x in results]
                   ^
SyntaxError: invalid syntax
</code>```

What am I missing? Thank you.

答:
What you only need is using a function:

```<code>results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2]
res = sum(results)
print(res)
</code>```

Or

```<code>from functools import reduce
results = reduce(lambda x, y: x + y, results)
print(results)
</code>```

If you insist to use list comprehension, I would say it troublesome and unnecessary since it will create another list which ultimately leads to the same approach to using functions to get the summation anyway.

Body:
I'm trying to recreate this loop in one line:

results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2]

for x in results:
  total = x + total

print(total)

But when I do this:

 y = [total = total + x for x in results]

I get an error:

y = [total = total + x for x in results]
                   ^
SyntaxError: invalid syntax

What am I missing? Thank you.

Body:
What you only need is using a function:

results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2]
res = sum(results)
print(res)

Or

from functools import reduce
results = reduce(lambda x, y: x + y, results)
print(results)

If you insist to use list comprehension, I would say it troublesome and unnecessary since it will create another list which ultimately leads to the same approach to using functions to get the summation anyway.


问:
Configuration for SSL redirect on Heroku causing error 403 (Forbidden) when accessing root domain
I have a PHP website that was working properly, hosted on Heroku (apache). I have just configured SSL and I would like to force users using https. Then I've found some instructions to do that on Heroku, using 'Procfile' approach, a file where I can indicate a new file so-called "apache_app.conf" with mod_rewrite directives and execute what I need.

Code for Procfile:

```<code>web: vendor/bin/heroku-php-apache2 -C apache_app.conf /
</code>```

You can see the code for the file apache_app.conf below:

```<code>RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

This code worked fine, in respect of redirect funcionality, but the problem is that I am receiving the following message when I am accessing the root domain (https://example.com):

Forbidden

You don't have permission to access / on this server.

When I explicitly type "https://example.com/index.php", it works fine.

Can someone help me?

答:
As per heroku it doesn't allow the default file to be executed from root, please move index.php to folder like app and update your Procfile as below </p>

```<code>web: vendor/bin/heroku-php-apache2 app/ -C apache_app.conf
</code>```

Body:
I have a PHP website that was working properly, hosted on Heroku (apache). I have just configured SSL and I would like to force users using https. Then I've found some instructions to do that on Heroku, using 'Procfile' approach, a file where I can indicate a new file so-called "apache_app.conf" with mod_rewrite directives and execute what I need.

Code for Procfile:

web: vendor/bin/heroku-php-apache2 -C apache_app.conf /

You can see the code for the file apache_app.conf below:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This code worked fine, in respect of redirect funcionality, but the problem is that I am receiving the following message when I am accessing the root domain (https://example.com):

Forbidden

You don't have permission to access / on this server.

When I explicitly type "https://example.com/index.php", it works fine.

Can someone help me?

Body:
As per heroku it doesn't allow the default file to be executed from root, please move index.php to folder like app and update your Procfile as below

web: vendor/bin/heroku-php-apache2 app/ -C apache_app.conf


问:
Chain of promises in javascript with ajax calls
I have a function (f1) which I want to get called only after two ajax calls (say a1 and a2) are done. a2 should be called only after a1 is done. Following is the sequence of operation =

```<code>$.when(a1 and a2) {
   f1
}
</code>```

I tried the following code snippet -

```<code>$.when(a1a2()).done(function(){
  f1();
}

var a1a2 = function(){
  return $.when(a1()).done(function() {
    if (<check for a few variables a1 sets>) {
      // another ajax call for which f1 should wait
      return a2();
    } else {
      // random function for which f1 shouldn't wait
      f2();
    }
  });
}
</code>```

In the above code, f1 is waiting for a1 to finish but it is not waiting for a2 to finish.

I tried the following code snippet as well (but this also just waits for a1 to finish) -

```<code>var a1a2 = function(){
  var retVal = new Promise(function(){
    a1().then(function(){
      if (<check for a few variables a1 sets>) {
        return a2();
      } else {
        // random function for which f1 shouldn't wait
        f2();
      }
    });
  });
}
</code>```

I have looked at other similar questions but an not able to devise a solution. Can someone please help?

答:
```<code>function a1() {
  return new Promise(resolve => {
     resolve();
  });
}

function a2() {
  return new Promise(resolve => {
    resolve();
  });
}

function f1() {
  // this runs when the a1 and a2 is resolved.
}

// this is the call method. there are so many approach in your question first is chaining of promise.
function CallMethod(){
   a1().then(function () { // you can optionally pass data here via the resolve in the promise
      return a2();
   }).then(function () { // same here you can pass optional data here.
      // here the a1 and a2 is resolved you can call the f1() now.
      f1();
   });
}
// second one is called Promise.all()
function CallMethod() {
  Promise.all([a1(), a2()]).then(data => { // this is the optional data passed in the resolve base on the index of the function promises.
     var firstResolve = data[0]; // resolved data of a1();
     var secondResolve = data[1]; // resolved data of a2();
  })
}
</code>```

Body:
I have a function (f1) which I want to get called only after two ajax calls (say a1 and a2) are done. a2 should be called only after a1 is done. Following is the sequence of operation =

$.when(a1 and a2) {
   f1
}

I tried the following code snippet -

$.when(a1a2()).done(function(){
  f1();
}

var a1a2 = function(){
  return $.when(a1()).done(function() {
    if (<check for a few variables a1 sets>) {
      // another ajax call for which f1 should wait
      return a2();
    } else {
      // random function for which f1 shouldn't wait
      f2();
    }
  });
}

In the above code, f1 is waiting for a1 to finish but it is not waiting for a2 to finish.

I tried the following code snippet as well (but this also just waits for a1 to finish) -

var a1a2 = function(){
  var retVal = new Promise(function(){
    a1().then(function(){
      if (<check for a few variables a1 sets>) {
        return a2();
      } else {
        // random function for which f1 shouldn't wait
        f2();
      }
    });
  });
}

I have looked at other similar questions but an not able to devise a solution. Can someone please help?