问:
Can I rely on the using statement to close my MySQL connections?
I have an ASP.NET website that uses mysql as it's database. I notice there are a lot of connections "sleeping" when I show a full process list. Today we had some errors "The timeout period elapsed prior to obtaining a connection from the pool.". If the processes are "sleeping" then are they still open from the code? All MySQL connections in the code are in using statements. Can I rely on the using statement to properly close connections?

Edit Code:
I am using this class to create my connection:

```<code>public class DbAccess
{
    public static MySqlConnection OpenConnection(string connectionStringName)
    {
        string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new ArgumentException("Connection string " + connectionStringName + " does not exist.");
        }
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}
</code>```

Then I am calling it like this:

```<code>using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}
</code>```

Some additional info: Resetting MySql did not make the errors go away, but resetting my app pool did..

答:
C# using blocks are guaranteed to call the .Dispose() method of the object, even if an exception is thrown. That means it's safe, as long as your provider uses the .Dispose() method to close the connection. Looking in the documentation for that type, I see this excerpt (down in section 25.2.3.3.5):

From Open to Closed, using either the Close method or the Dispose method of the connection object.

This tells me you can close the connection via the Dispose method, and so a using block should be all you need.

Body:
I have an ASP.NET website that uses mysql as it's database. I notice there are a lot of connections "sleeping" when I show a full process list. Today we had some errors "The timeout period elapsed prior to obtaining a connection from the pool.". If the processes are "sleeping" then are they still open from the code? All MySQL connections in the code are in using statements. Can I rely on the using statement to properly close connections?

Edit Code:
I am using this class to create my connection:

public class DbAccess
{
    public static MySqlConnection OpenConnection(string connectionStringName)
    {
        string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        if (string.IsNullOrEmpty(connectionString))
        {
            throw new ArgumentException("Connection string " + connectionStringName + " does not exist.");
        }
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        return connection;
    }
}

Then I am calling it like this:

using (MySqlConnection connection = DbAccess.OpenConnection(connectionString))
{
    //Code Here
}

Some additional info: Resetting MySql did not make the errors go away, but resetting my app pool did..


来源: stackexchange

问:
Using plotly with zeppellin in scala
I want to display my results in the form of a histogram in Zeppelin. I came across plotly. My code is in scala and I would like to know the steps to incorporate plotly into zeppelin using scala. Or is there any better way(libraries) that can be used to draw a histogram in Zeppelin(Scala)?</p>

答:
After trying basically every available solution I eventually settled for vegas-viz. If you look at their project's page on GitHub, they claim to be "The Missing MatPlotLib for Scala + Spark". Although that sounds a little bit exaggerated to me at the moment, the library does its work and does it well.

This is the procedure I suggest for drawing a Bar Chart (that's what you need for histograms, basically) in the Zeppelin's Spark Interpreter:

import dependencies (please check the vegas maven repository for the latest versions)

```<code>%dep
z.load("org.vegas-viz:vegas_2.11:0.3.11")
z.load("org.vegas-viz:vegas-spark_2.11:0.3.11")
</code>```

Note that vegas-spark is needed only if you want to draw directly from a DataFrame, see below.

import packages

```<code>import vegas._
import vegas.render.WindowRenderer._
</code>```

draw chart

```<code>val plot = Vegas("Sample Column Chart")
  .withData(
    Seq(
      Map("country" -> "USA", "population" -> 314),
      Map("country" -> "UK", "population" -> 64),
      Map("country" -> "DK", "population" -> 80)
    )
  )
  .encodeX("country", Nom)
  .encodeY("population", Quant)
  .mark(Bar)
plot.show
</code>```

The result should be similar to the image below:

you can even draw an image directly from a DataFrame if you have added vegas-spark among the dependencies (see point 1.) but you also need an extra import for this to work:

```<code>import vegas.sparkExt._

val df = Seq(
  ("USA", 314),
  ("UK", 64),
  ("DK", 80)
).toDF("country", "population")

val plot = Vegas("Sample Column Chart", width=600, height=320)
  .withDataFrame(df)
  .encodeX("country", Nom)
  .encodeY("population", Quant)
  .mark(Bar)
plot.show
</code>```

The result should be the same as above.

ContentLicense: CC BY-SA 3.0

Title: Using plotly with zeppellin in scala

Body:
After trying basically every available solution I eventually settled for vegas-viz. If you look at their project's page on GitHub, they claim to be "The Missing MatPlotLib for Scala + Spark". Although that sounds a little bit exaggerated to me at the moment, the library does its work and does it well.

This is the procedure I suggest for drawing a Bar Chart (that's what you need for histograms, basically) in the Zeppelin's Spark Interpreter:

import dependencies (please check the vegas maven repository for the latest versions)

%dep
z.load("org.vegas-viz:vegas_2.11:0.3.11")
z.load("org.vegas-viz:vegas-spark_2.11:0.3.11")

Note that vegas-spark is needed only if you want to draw directly from a DataFrame, see below.

import packages

import vegas._
import vegas.render.WindowRenderer._

draw chart

val plot = Vegas("Sample Column Chart")
  .withData(
    Seq(
      Map("country" -> "USA", "population" -> 314),
      Map("country" -> "UK", "population" -> 64),
      Map("country" -> "DK", "population" -> 80)
    )
  )
  .encodeX("country", Nom)
  .encodeY("population", Quant)
  .mark(Bar)
plot.show

The result should be similar to the image below:

you can even draw an image directly from a DataFrame if you have added vegas-spark among the dependencies (see point 1.) but you also need an extra import for this to work:

import vegas.sparkExt._

val df = Seq(
  ("USA", 314),
  ("UK", 64),
  ("DK", 80)
).toDF("country", "population")

val plot = Vegas("Sample Column Chart", width=600, height=320)
  .withDataFrame(df)
  .encodeX("country", Nom)
  .encodeY("population", Quant)
  .mark(Bar)
plot.show

The result should be the same as above.

ContentLicense: CC BY-SA 4.0


问:
How to download a nupkg package from nuget programmatically in .NET Core?
In past with .NET Framework I used this example for working with nuget programmatically

Play with Packages, programmatically!

Is there any equivalent source for .NET Core?

```<code>//ID of the package to be looked up
string packageID = "EntityFramework";

//Connect to the official package repository
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");

//Get the list of all NuGet packages with ID 'EntityFramework'
List<IPackage> packages = repo.FindPackagesById(packageID).ToList();

//Filter the list of packages that are not Release (Stable) versions
packages = packages.Where (item => (item.IsReleaseVersion() == false)).ToList();

//Iterate through the list and print the full name of the pre-release packages to console
foreach (IPackage p in packages)
{
    Console.WriteLine(p.GetFullName());
}

//---------------------------------------------------------------------------

//ID of the package to be looked up
string packageID = "EntityFramework";

//Connect to the official package repository
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");

//Initialize the package manager
string path = <PATH_TO_WHERE_THE_PACKAGES_SHOULD_BE_INSTALLED>
PackageManager packageManager = new PackageManager(repo, path);

//Download and unzip the package
packageManager.InstallPackage(packageID, SemanticVersion.Parse("5.0.0"));
</code>```

I want to download and install any package programmatically.

```<code>https://api.nuget.org/v3/index.json
</code>```

答:
Best way to achieve it is by referring NugetDownloader Nuget package  in your Project and use it to download any other package programmatically

Install-Package NugetDownloader

Source code and help guide on the same is available at :
https://github.com/paraspatidar/NugetDownloader

Here is a quick sample on how to achieve it :

string packageName="Newtonsoft.json";
string version="10.2.1.0"; \\optional

\\initilize NugetEngine from NugetDownloader namespaces

NugetEngine nugetEngine = new NugetEngine();
nugetEngine.GetPackage(packageName, version).Wait();
```

sample client is also available at https://github.com/paraspatidar/NugetDownloader/tree/master/NugetDownloaderTestConsole

Alternately In case if you want to build your Nugetdownloader engine from scratch , then you might also refer https://github.com/Azure/azure-functions-host/blob/dev/src/WebJobs.Script/Description/DotNet/PackageManager.cs as it has something similar implementation , but that too much of code understanding and extraction.

Body:
In past with .NET Framework I used this example for working with nuget programmatically

Play with Packages, programmatically!

Is there any equivalent source for .NET Core?

//ID of the package to be looked up
string packageID = "EntityFramework";

//Connect to the official package repository
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");

//Get the list of all NuGet packages with ID 'EntityFramework'
List<IPackage> packages = repo.FindPackagesById(packageID).ToList();

//Filter the list of packages that are not Release (Stable) versions
packages = packages.Where (item => (item.IsReleaseVersion() == false)).ToList();

//Iterate through the list and print the full name of the pre-release packages to console
foreach (IPackage p in packages)
{
    Console.WriteLine(p.GetFullName());
}

//---------------------------------------------------------------------------

//ID of the package to be looked up
string packageID = "EntityFramework";

//Connect to the official package repository
IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");

//Initialize the package manager
string path = <PATH_TO_WHERE_THE_PACKAGES_SHOULD_BE_INSTALLED>
PackageManager packageManager = new PackageManager(repo, path);

//Download and unzip the package
packageManager.InstallPackage(packageID, SemanticVersion.Parse("5.0.0"));

I want to download and install any package programmatically.

https://api.nuget.org/v3/index.json

Body:
Best way to achieve it is by referring NugetDownloader Nuget package  in your Project and use it to download any other package programmatically

Install-Package NugetDownloader

Source code and help guide on the same is available at :
https://github.com/paraspatidar/NugetDownloader

Here is a quick sample on how to achieve it :

string packageName="Newtonsoft.json";
string version="10.2.1.0"; \\optional

\\initilize NugetEngine from NugetDownloader namespaces

NugetEngine nugetEngine = new NugetEngine();
nugetEngine.GetPackage(packageName, version).Wait();

sample client is also available at https://github.com/paraspatidar/NugetDownloader/tree/master/NugetDownloaderTestConsole

Alternately In case if you want to build your Nugetdownloader engine from scratch , then you might also refer https://github.com/Azure/azure-functions-host/blob/dev/src/WebJobs.Script/Description/DotNet/PackageManager.cs as it has something similar implementation , but that too much of code understanding and extraction.


问:
Best data structure for an N-ary tree
I need to represent a tree with multiple branches per node. What structure should I use? It's for computing chess game states. It explodes exponentially so memory will be a concern. I'm using C++11 but am open to other standards. Also, pruning should be O(1).

EDIT1
To expand, I am going to be holding a Chess AI competition. The main PvP game is complete already, and I am programming the AI API next. Contestants will write their own AI, and then we will have them compete in a tournament. The winner's AI will be used in Player vs Computer games. I am just thinking about the best structure to store my game states and AI thoughts.

I was reading up on Deep Blue, and it thinks from 5 to ~25 moves ahead. I can imagine most computers capable of handling 5 moves deep with BFS, but anything deeper and I believe I will have to use DFS.

AI's will be timed, and competing AI's will only be played locally, so as not to introduce advantages in CPU power.

I am reading up on Monte Carlo and Alpha Beta searches now.

My initial thoughts on a data structure are as follows :

```<code>union CHESS_MOVE {
   unsigned short m;
   ChessPosT pos[2];
   ///...
};

class ChessMoveNode {
   CHESS_MOVE move;
   std::set<ChessMoveNode> nextmoves;
};

class ChessMoveTree {
   std::set<ChessMoveNode> next;
};
</code>```

The board can be calculated at any time by concatenating the path from the root to the leaf. Although recalculating the board could get very expensive over time. Ideas? Should I store the board? The board is stored as an array of 64 char indices holding a piece number. So it's 16 bytes, compared to 2, but the memory use would save a lot of re-calculation of the board state.

For my own personal AI, I will be implementing a board scoring function that will rank the game states, and then all non maximal game states will be discarded, as well as pruning game states that are invalidated by choosing a move.

答:
One simple approach to do this that works well for Monte-Carlo Tree Search (MCTS) is to use a vector of some custom class. Inside the class you have whatever state information you need in addition to child information -- the number of the children and their index in the vector. This avoids storing a separate pointer for each child, which can introduce significant overhead.

So, the root is at index 0. Inside that index there would be two integers indicating that the children start at index 1 and that there are k children. (From index 1 to k.) At index 1 the children would start at index k+1 with l total children, and so on throughout the tree.

This works really well based on the assumptions that (1) the number of children is fixed, (2) that they are all added at once, and (3) that states are not removed from the tree.

If you are trying to prune states from the tree, this doesn't work as well, because you will leave gaps in tree if you remove them. Using explicit pointers for storing each child is expensive, so something else is done in practice.

First, with alpha-beta search you typically search the tree with a DFS and don't store branches. But, you use a hash table to store states and check for duplicates. The branches of the tree can be implicitly computed from the state, so you can reconstruct the tree without storing everything explicitly.

Note, however, that hash tables (called transposition tables in the context of game tree search) are not typically used deep in the tree because there are many states and the cost of storing grows while the benefit of removing duplicates shrinks.

To summarize, based on the assumption that you are doing something alpha-beta like and you have a good reason to store the tree explicitly, I suggest store the states in a hash table and leave the edges to be implicitly computed from a move-generation function. (Which would apply moves and take the hash of the resulting state to find them in the hash table. If they aren't there they have been pruned.)

Title: Best data structure for an N-ary tree

Body:
I need to represent a tree with multiple branches per node. What structure should I use? It's for computing chess game states. It explodes exponentially so memory will be a concern. I'm using C++11 but am open to other standards. Also, pruning should be O(1).

EDIT1
To expand, I am going to be holding a Chess AI competition. The main PvP game is complete already, and I am programming the AI API next. Contestants will write their own AI, and then we will have them compete in a tournament. The winner's AI will be used in Player vs Computer games. I am just thinking about the best structure to store my game states and AI thoughts.

I was reading up on Deep Blue, and it thinks from 5 to ~25 moves ahead. I can imagine most computers capable of handling 5 moves deep with BFS, but anything deeper and I believe I will have to use DFS.

AI's will be timed, and competing AI's will only be played locally, so as not to introduce advantages in CPU power.

I am reading up on Monte Carlo and Alpha Beta searches now.

My initial thoughts on a data structure are as follows :

union CHESS_MOVE {
   unsigned short m;
   ChessPosT pos[2];
   ///...
};

class ChessMoveNode {
   CHESS_MOVE move;
   std::set<ChessMoveNode> nextmoves;
};

class ChessMoveTree {
   std::set<ChessMoveNode> next;
};

The board can be calculated at any time by concatenating the path from the root to the leaf. Although recalculating the board could get very expensive over time. Ideas? Should I store the board? The board is stored as an array of 64 char indices holding a piece number. So it's 16 bytes, compared to 2, but the memory use would save a lot of re-calculation of the board state.

For my own personal AI, I will be implementing a board scoring function that will rank the game states, and then all non maximal game states will be discarded, as well as pruning game states that are invalidated by choosing a move.


问:
Collate language codes into one combined locale code using CASE WHEN, and count the number of times the combined locale code occurs on a date
Learning about CASE WHEN, and I've come across a use case when I see multiple locale codes in Analytics. This is a much simpler question that is much easier to answer and read, than my prior question that was posted.

Examples are:
en-us (english US)
en-au (english australia)
en-br (english brazil)
es-es (spanish spain)
es-419 (spanish-latam)
pt-br (portuguese brazil)
pt-pt (portugal)

How do I aggregate these in BigQuery so that instead of counting distinct values, I can count the number of times where only the first two characters of the locale are found?

The second part of this question is: How do I structure my table in such a way so that I am able to plot these counts by date?

Currently, the output is:
date:language_code:CombinedLocale

Link to example data table: https://docs.google.com/spreadsheets/d/1XZp1nhNZySWI39kKhb3ydYYIImmrfAMcGJDS6ASThqg/edit?usp=sharing

I've tried:

```<code>SELECT date, COUNT(language_code),
CASE
    WHEN language_code like '%af%' THEN 'AF'
    WHEN language_code like '%en%' THEN 'EN'
    WHEN language_code like '%ar%' THEN 'AR'
    WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END AS CombinedLocale
FROM date_locales
</code>```

And:

```<code>Select date, COUNT(language_code)
FROM date_locales
WHERE CASE
WHEN language_code like '%af%' THEN 'AF'
WHEN language_code like '%en%' THEN 'EN'
WHEN language_code like '%ar%' THEN 'AR'
WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END
</code>```

This is the working code I have:

```<code>SELECT date, language_code,
CASE
    WHEN language_code like '%af%' THEN 'AF'
    WHEN language_code like '%en%' THEN 'EN'
    WHEN language_code like '%ar%' THEN 'AR'
    WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END AS CombinedLocale
FROM date_locales
</code>```

I expected the results to display a count of CombinedLocale table over time as such:
    ```
    Jan AF 3
    JAN EN 5
    FEB AF 5
    FEB EN 6
    MAR EN 2
    MAR EN 3```

but I get an error message stating:
SELECT list expression references column date which is neither grouped nor aggregated (Line: 1, Column: 8)

I believe I will need to aggregate the dates into Months first? I am under the impression BigQuery integration w/ DataStudio will automatically aggregate the date column.

答:
Below is for BigQuery Standard SQL and answers both items in your question

```<code>#standardSQL
SELECT
  FORMAT_DATE('%b %Y', PARSE_DATE('%m/%d/%Y', dt)) month_year,
  REGEXP_EXTRACT(code, r'(.*?)-') code,
  COUNT(1) cnt
FROM `project.dataset.date_locales`
GROUP BY month_year, code
</code>```

You can test, play with above using some dummy data as in below example

```<code>#standardSQL
WITH `project.dataset.date_locales` AS (
  SELECT '3/14/2019' dt, 'af-ZA' code UNION ALL
  SELECT '3/14/2019', 'am-ET' UNION ALL
  SELECT '5/7/2019', 'ar-AE' UNION ALL
  SELECT '5/19/2019', 'ar-BH' UNION ALL
  SELECT '3/5/2019', 'ar-DZ' UNION ALL
  SELECT '1/1/2019', 'ar-EG' UNION ALL
  SELECT '3/31/2019', 'ar-IQ' UNION ALL
  SELECT '4/20/2019', 'ar-JO' UNION ALL
  SELECT '3/17/2019', 'ar-KW' UNION ALL
  SELECT '1/8/2019', 'ar-LB' UNION ALL
  SELECT '3/26/2019', 'ar-LY' UNION ALL
  SELECT '5/7/2019', 'ar-MA' UNION ALL
  SELECT '3/12/2019', 'arn-CL' UNION ALL
  SELECT '5/19/2019', 'ar-OM' UNION ALL
  SELECT '4/19/2019', 'ar-QA' UNION ALL
  SELECT '4/20/2019', 'ar-SA' UNION ALL
  SELECT '5/22/2019', 'ar-SY' UNION ALL
  SELECT '5/23/2019', 'ar-TN' UNION ALL
  SELECT '3/10/2019', 'ar-YE' UNION ALL
  SELECT '4/6/2019', 'as-IN' UNION ALL
  SELECT '2/5/2019', 'az-Cyrl' UNION ALL
  SELECT '3/1/2019', 'az-Latn' UNION ALL
  SELECT '3/25/2019', 'ba-RU' UNION ALL
  SELECT '1/1/2019', 'be-BY' UNION ALL
  SELECT '2/1/2019', 'bg-BG' UNION ALL
  SELECT '5/3/2019', 'bn-BD' UNION ALL
  SELECT '5/2/2019', 'bn-IN' UNION ALL
  SELECT '3/19/2019', 'bo-CN' UNION ALL
  SELECT '1/19/2019', 'br-FR'
)
SELECT
  FORMAT_DATE('%b %Y', PARSE_DATE('%m/%d/%Y', dt)) month_year,
  REGEXP_EXTRACT(code, r'(.*?)-') code,
  COUNT(1) cnt
FROM `project.dataset.date_locales`
GROUP BY month_year, code
</code>```

with result as

```<code>Row month_year  code    cnt
1   Jan 2019    ar      2
2   Mar 2019    ar      5
3   Mar 2019    af      1
4   Feb 2019    az      1
5   Mar 2019    am      1
6   Apr 2019    as      1
7   May 2019    ar      6
8   Mar 2019    ba      1
9   May 2019    bn      2
10  Feb 2019    bg      1
11  Mar 2019    arn     1
12  Mar 2019    bo      1
13  Mar 2019    az      1
14  Jan 2019    br      1
15  Apr 2019    ar      3
16  Jan 2019    be      1
</code>```

Body:
Learning about CASE WHEN, and I've come across a use case when I see multiple locale codes in Analytics. This is a much simpler question that is much easier to answer and read, than my prior question that was posted.

Examples are:
en-us (english US)
en-au (english australia)
en-br (english brazil)
es-es (spanish spain)
es-419 (spanish-latam)
pt-br (portuguese brazil)
pt-pt (portugal)

How do I aggregate these in BigQuery so that instead of counting distinct values, I can count the number of times where only the first two characters of the locale are found?

The second part of this question is: How do I structure my table in such a way so that I am able to plot these counts by date?

Currently, the output is:
date:language_code:CombinedLocale

Link to example data table: https://docs.google.com/spreadsheets/d/1XZp1nhNZySWI39kKhb3ydYYIImmrfAMcGJDS6ASThqg/edit?usp=sharing

I've tried:

SELECT date, COUNT(language_code),
CASE
    WHEN language_code like '%af%' THEN 'AF'
    WHEN language_code like '%en%' THEN 'EN'
    WHEN language_code like '%ar%' THEN 'AR'
    WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END AS CombinedLocale
FROM date_locales

And:

Select date, COUNT(language_code)
FROM date_locales
WHERE CASE
WHEN language_code like '%af%' THEN 'AF'
WHEN language_code like '%en%' THEN 'EN'
WHEN language_code like '%ar%' THEN 'AR'
WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END

This is the working code I have:

SELECT date, language_code,
CASE
    WHEN language_code like '%af%' THEN 'AF'
    WHEN language_code like '%en%' THEN 'EN'
    WHEN language_code like '%ar%' THEN 'AR'
    WHEN language_code like '%ba%' THEN 'BA'
ELSE "Others"
END AS CombinedLocale
FROM date_locales

I expected the results to display a count of CombinedLocale table over time as such:

    Jan AF 3
    JAN EN 5
    FEB AF 5
    FEB EN 6
    MAR EN 2
    MAR EN 3

but I get an error message stating:
SELECT list expression references column date which is neither grouped nor aggregated (Line: 1, Column: 8)

I believe I will need to aggregate the dates into Months first? I am under the impression BigQuery integration w/ DataStudio will automatically aggregate the date column.

Body:
Below is for BigQuery Standard SQL and answers both items in your question

#standardSQL
SELECT
  FORMAT_DATE('%b %Y', PARSE_DATE('%m/%d/%Y', dt)) month_year,
  REGEXP_EXTRACT(code, r'(.*?)-') code,
  COUNT(1) cnt
FROM `project.dataset.date_locales`
GROUP BY month_year, code

You can test, play with above using some dummy data as in below example

#standardSQL
WITH `project.dataset.date_locales` AS (
  SELECT '3/14/2019' dt, 'af-ZA' code UNION ALL
  SELECT '3/14/2019', 'am-ET' UNION ALL
  SELECT '5/7/2019', 'ar-AE' UNION ALL
  SELECT '5/19/2019', 'ar-BH' UNION ALL
  SELECT '3/5/2019', 'ar-DZ' UNION ALL
  SELECT '1/1/2019', 'ar-EG' UNION ALL
  SELECT '3/31/2019', 'ar-IQ' UNION ALL
  SELECT '4/20/2019', 'ar-JO' UNION ALL
  SELECT '3/17/2019', 'ar-KW' UNION ALL
  SELECT '1/8/2019', 'ar-LB' UNION ALL
  SELECT '3/26/2019', 'ar-LY' UNION ALL
  SELECT '5/7/2019', 'ar-MA' UNION ALL
  SELECT '3/12/2019', 'arn-CL' UNION ALL
  SELECT '5/19/2019', 'ar-OM' UNION ALL
  SELECT '4/19/2019', 'ar-QA' UNION ALL
  SELECT '4/20/2019', 'ar-SA' UNION ALL
  SELECT '5/22/2019', 'ar-SY' UNION ALL
  SELECT '5/23/2019', 'ar-TN' UNION ALL
  SELECT '3/10/2019', 'ar-YE' UNION ALL
  SELECT '4/6/2019', 'as-IN' UNION ALL
  SELECT '2/5/2019', 'az-Cyrl' UNION ALL
  SELECT '3/1/2019', 'az-Latn' UNION ALL
  SELECT '3/25/2019', 'ba-RU' UNION ALL
  SELECT '1/1/2019', 'be-BY' UNION ALL
  SELECT '2/1/2019', 'bg-BG' UNION ALL
  SELECT '5/3/2019', 'bn-BD' UNION ALL
  SELECT '5/2/2019', 'bn-IN' UNION ALL
  SELECT '3/19/2019', 'bo-CN' UNION ALL
  SELECT '1/19/2019', 'br-FR'
)
SELECT
  FORMAT_DATE('%b %Y', PARSE_DATE('%m/%d/%Y', dt)) month_year,
  REGEXP_EXTRACT(code, r'(.*?)-') code,
  COUNT(1) cnt
FROM `project.dataset.date_locales`
GROUP BY month_year, code

with result as

Row month_year  code    cnt
1   Jan 2019    ar      2
2   Mar 2019    ar      5
3   Mar 2019    af      1
4   Feb 2019    az      1
5   Mar 2019    am      1
6   Apr 2019    as      1
7   May 2019    ar      6
8   Mar 2019    ba      1
9   May 2019    bn      2
10  Feb 2019    bg      1
11  Mar 2019    arn     1
12  Mar 2019    bo      1
13  Mar 2019    az      1
14  Jan 2019    br      1
15  Apr 2019    ar      3
16  Jan 2019    be      1


问:
Getting "php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution" error when using docker-compose to build containers
It seems as if my php container cannot resolve the host "db" of my database container when I run php artisan migrate, I'm wondering if I've set something up wrong in the config.

Tried messing with the depends_on: and links: options on the dockerfile.

docker-compose.yml

```<code>version: '3.3'

services:
  db:
    container_name: tasks-db
    image: mariadb:latest
    volumes:
      - dbdata:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=tasks
      - MYSQL_USER=root
      - MYSQL_PASSWORD=password
    restart: always

  webserver:
    container_name: tasks-webserver
    image: nginx:latest
    ports:
      - "8080:80"
      - "443:443"
    volumes:
      - .:/app
      - ./provision/nginx/:/etc/nginx/conf.d/
    depends_on:
      - php
    restart: always

  php:
    container_name: tasks-php
    build:
      context: .
      dockerfile: provision/php.docker
    depends_on:
      - db
    restart: always
    env_file:
      - .env

volumes:
  dbdata:
    driver: local
</code>```

provision/db.docker

```<code>FROM php:7.3-fpm

# Add dependencies
RUN apt-get update -y && apt-get install -y openssl libpng-dev libxml2-dev curl cron git libzip-dev zip unzip

# Install php extensions
RUN docker-php-ext-install pdo mbstring gd xml pdo_mysql zip

# Install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

COPY . /app/

WORKDIR /app

RUN chown -R $USER:www-data /app/storage
RUN chown -R $USER:www-data /app/bootstrap/cache

RUN chmod -R 775 /app/storage
RUN chmod -R 775 /app/bootstrap/cache

# Install composer dependencies
RUN composer install

RUN php artisan optimize

#RUN php artisan migrate --seed

RUN crontab -l | { cat; echo "* * * * * php /app/artisan schedule:run >> /dev/null 2>&1"; } | crontab -

STOPSIGNAL SIGTERM

CMD ["php-fpm"]
</code>```

db.docker

```<code>FROM mariadb:latest

CMD ["mysqld", "--user=mysql"]
</code>```

I'm getting this error:

```<code>Step 13/16 : RUN php artisan migrate --no-interaction --seed
 ---> Running in ccbfcde9324d

   Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution (SQL: select * from information_schema.tables where table_schema = tasks and table_name = migrations and table_type = 'BASE TABLE')

  at /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution")
      /app/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70

  2   PDO::__construct("mysql:host=db;port=3306;dbname=tasks", "root", "password", [])
      /app/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70

  Please use the argument -v to see more details.
ERROR: Service 'php' failed to build: The command '/bin/sh -c php artisan migrate --no-interaction --seed' returned a non-zero code: 1
</code>```

答:
You are missing

```<code>  links:
    - db
</code>```

in your php configuration.

Anyway as @David Maze mentioned, running php artisan migrate in a Dockerfile is not only a bad practice, but it will not work.

You should run that command only when your containers are started. Think about it, php artisan migrate will modify another container's data, which is not guaranteed it is running at the time the image is being built. That is against the container philosophy.

Body:
It seems as if my php container cannot resolve the host "db" of my database container when I run php artisan migrate, I'm wondering if I've set something up wrong in the config.

Tried messing with the depends_on: and links: options on the dockerfile.

docker-compose.yml

version: '3.3'

services:
  db:
    container_name: tasks-db
    image: mariadb:latest
    volumes:
      - dbdata:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=tasks
      - MYSQL_USER=root
      - MYSQL_PASSWORD=password
    restart: always

  webserver:
    container_name: tasks-webserver
    image: nginx:latest
    ports:
      - "8080:80"
      - "443:443"
    volumes:
      - .:/app
      - ./provision/nginx/:/etc/nginx/conf.d/
    depends_on:
      - php
    restart: always

  php:
    container_name: tasks-php
    build:
      context: .
      dockerfile: provision/php.docker
    depends_on:
      - db
    restart: always
    env_file:
      - .env

volumes:
  dbdata:
    driver: local

provision/db.docker

FROM php:7.3-fpm

# Add dependencies
RUN apt-get update -y && apt-get install -y openssl libpng-dev libxml2-dev curl cron git libzip-dev zip unzip

# Install php extensions
RUN docker-php-ext-install pdo mbstring gd xml pdo_mysql zip

# Install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

COPY . /app/

WORKDIR /app

RUN chown -R $USER:www-data /app/storage
RUN chown -R $USER:www-data /app/bootstrap/cache

RUN chmod -R 775 /app/storage
RUN chmod -R 775 /app/bootstrap/cache

# Install composer dependencies
RUN composer install

RUN php artisan optimize

#RUN php artisan migrate --seed

RUN crontab -l | { cat; echo "* * * * * php /app/artisan schedule:run >> /dev/null 2>&1"; } | crontab -

STOPSIGNAL SIGTERM

CMD ["php-fpm"]

db.docker

FROM mariadb:latest

CMD ["mysqld", "--user=mysql"]

I'm getting this error:

Step 13/16 : RUN php artisan migrate --no-interaction --seed
 ---> Running in ccbfcde9324d

   Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution (SQL: select * from information_schema.tables where table_schema = tasks and table_name = migrations and table_type = 'BASE TABLE')

  at /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the database's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   PDOException::("PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution")
      /app/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70

  2   PDO::__construct("mysql:host=db;port=3306;dbname=tasks", "root", "password", [])
      /app/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70

  Please use the argument -v to see more details.
ERROR: Service 'php' failed to build: The command '/bin/sh -c php artisan migrate --no-interaction --seed' returned a non-zero code: 1

Body:
You are missing

  links:
    - db

in your php configuration.

Anyway as @David Maze mentioned, running php artisan migrate in a Dockerfile is not only a bad practice, but it will not work.

You should run that command only when your containers are started. Think about it, php artisan migrate will modify another container's data, which is not guaranteed it is running at the time the image is being built. That is against the container philosophy.


问:
htaccess: How to display GET variables?
I have code that displays news. but now I want to use .htaccess to hide the id=2 bla..
Everything is working fine but It doesn't display the get variables

I have tried using [L,QSA], [NC,QSA] none is working

//get variables

```<code><?php
if (isset($_GET['id']) && !empty($_GET['id'])) {
    $id        = $_GET['id'];
    $stmt_edit = $pdo->prepare('SELECT * FROM articles WHERE id =:uid');
    $stmt_edit->execute(array(
        ':uid' => $id
    ));
    $edit_row  = $stmt_edit->fetch(PDO::FETCH_ASSOC);
    $image     = $edit_row['headline_image'];
    $article   = $edit_row['article_body'];
    $headlines = $edit_row['headlines'];
    $date      = $edit_row['date'];
    $month     = $edit_row['month'];
    $admin     = $edit_row['admin'];
} else {
    header("Location: index.php");
}
</code>```

//.htaccess code

```<code>Options  -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -f

RewriteRule ^ - [L]
RewriteRule ^index?$ index.php
RewriteRule ^news/([0-9]+) news.php?id=$newsid [L,QSA]
</code>```

I am using the variables outside the get functions I want to to display the content of the respective variable.

答:
```<code>RewriteRule ^news/([0-9]+) news.php?id=$newsid [L,QSA]
</code>```

Why $newsid? $newsid is seen as a literal string here, so $id (ie. $_GET['id']) in your PHP code will be always be the literal string "$newsid" (but presumably you saw this while debugging your PHP code?)

You should be using the $1 backreference instead. For example:

```<code>RewriteRule ^news/([0-9]+) news.php?id=$1 [L,QSA]
</code>```

Aside: You may also want an end-of-string anchor ($) on the RewriteRule pattern, as otherwise this will match /news/123anything. Or maybe that's the intention?

Title: htaccess: How to display GET variables?

Body:
I have code that displays news. but now I want to use .htaccess to hide the id=2 bla..
Everything is working fine but It doesn't display the get variables

I have tried using [L,QSA], [NC,QSA] none is working

//get variables

<?php
if (isset($_GET['id']) && !empty($_GET['id'])) {
    $id        = $_GET['id'];
    $stmt_edit = $pdo->prepare('SELECT * FROM articles WHERE id =:uid');
    $stmt_edit->execute(array(
        ':uid' => $id
    ));
    $edit_row  = $stmt_edit->fetch(PDO::FETCH_ASSOC);
    $image     = $edit_row['headline_image'];
    $article   = $edit_row['article_body'];
    $headlines = $edit_row['headlines'];
    $date      = $edit_row['date'];
    $month     = $edit_row['month'];
    $admin     = $edit_row['admin'];
} else {
    header("Location: index.php");
}

//.htaccess code

Options  -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -f

RewriteRule ^ - [L]
RewriteRule ^index?$ index.php
RewriteRule ^news/([0-9]+) news.php?id=$newsid [L,QSA]

I am using the variables outside the get functions I want to to display the content of the respective variable.

Body:
RewriteRule ^news/([0-9]+) news.php?id=$newsid [L,QSA]

Why $newsid? $newsid is seen as a literal string here, so $id (ie. $_GET['id']) in your PHP code will be always be the literal string "$newsid" (but presumably you saw this while debugging your PHP code?)

You should be using the $1 backreference instead. For example:

RewriteRule ^news/([0-9]+) news.php?id=$1 [L,QSA]

Aside: You may also want an end-of-string anchor ($) on the RewriteRule pattern, as otherwise this will match /news/123anything. Or maybe that's the intention?


问:
Why do I get System.String [ ] in my code while debugging?
I am on my final project in c# for beginners, but I can't seem to get my list to work properly. It also closes automatically after being 'filled' with orders.

```<code>class Burgare
{
    private string[] hamburger = new string[24];
    private int no_burger = 0;

    public void add_burger()//Ordering of burgers
    {
        Console.Clear(); //Clears console to make it look cleaner
        while (true)
        {
            int Burger_option = 0;
            do
            {
                Console.WriteLine("");// The options user can choose from
                Console.WriteLine("Please choose burgers from our menu:");
                Console.WriteLine("-------Burgers--------");
                Console.WriteLine("1 Original One     109");
                Console.WriteLine("2 Pig & Cow        109");
                Console.WriteLine("3 Spice & Nice     109");
                Console.WriteLine("4 Green One        109");
                Console.WriteLine("0 Go back to main menu");
                Console.WriteLine("----------------------");
                Console.WriteLine("");

                try //Making sure the user only picks what is on the menu
                {
                    Burger_option = int.Parse(Console.ReadLine());
                }

                catch
                {
                    Console.WriteLine("You can only choose what is on the menu!");

                }

                switch (Burger_option) //Depending on the number user presses on keyboard different burgers will be added to order
                {
                    case 1:
                        Console.WriteLine("You've added the Original One to your order");
                        Console.WriteLine("If you're done press 0 to go back to the main menu");
                        hamburger[no_burger] = "Original One";
                        break;

                    case 2:
                        Console.WriteLine("You've added the Pig & Cow to your order");
                        Console.WriteLine("If you're done press 0 to go back to the main menu");
                        hamburger[no_burger] = "Pig & Cow";
                        break;

                    case 3:
                        Console.WriteLine("You've added the Spice & Nice to your order");
                        Console.WriteLine("If you're done press 0 to go back to the main menu");
                        hamburger[no_burger] = "Spice & Nice";
                        break;

                    case 4:
                        Console.WriteLine("You've added the Green One to your order");
                        Console.WriteLine("If you're done press 0 to go back to the main menu");
                        hamburger[no_burger] = "Green One";
                        break;

                    case 0: //Sends user back to main menu
                        Run();
                        break;
                }
                no_burger++; //Adds burger

            } while (no_burger != 0);

            if (no_burger <= 25) //Maximum number of orders
            {
                Console.WriteLine("The restaurant can't take more than 24 orders of burgers at the time");
                Run(); //Sends user back to main menu when the order is over 24
            }
        }
    }

    public void print_order()
    {

        Console.WriteLine("-Your current order-");

    foreach (var burger in hamburger) //Showing a list of what is in the order
        {
         Console.WriteLine(hamburger);

         if (burger != null)

                Console.WriteLine(burger);
         else
                Console.WriteLine("Empty space"); //Making empty space to show where you can add more burgers
        }

    }
</code>```

After entering 24 orders I get the error "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" I've looked around a bit but still don't really understand how to fix my code. I'd like for it to return to the main menu after telling the user the order is full.

For my second problem the System.String [] problem, it appears when I enter the 'print_order'. It shows itself as
System.String []
Empty space
System.String []
Empty space
And so on. If possible I'd like to either remove it completely or at least replace it with 1,2,3...etc.

答:
First off, please only post one question per question; you've described many problems here, but only actually asked one question. If you have multiple questions, post multiple questions.

Why do I get System.String[] in my code while debugging?

C# by default gives the name of the type when you print it out, and you're printing an array of strings. To turn an array of strings into a string, use the Join method of the string type. Be careful to not confuse it with the Join extension method on sequences.

It also closes automatically after being 'filled' with orders.

When a console program's control reaches the end of Main, it terminates the program. If you want something else to happen, write code that indicates what you'd like to happen.

After entering 24 orders I get the error "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" I've looked around a bit but still don't really understand how to fix my code. I'd like for it to return to the main menu after telling the user the order is full.

You've reserved space for 24 things, and you've tried to access the 25th thing. That's a fatal error. Don't do that. You are required to detect that situation and prevent it.

If you want it to return to the main menu after telling the user the order is full then write code to do that. How? Since apparently the main menu is a thing that can happen more than once, you'll want to put it in a loop. You've already written two loops; put more stuff in the loops!

While we're looking at your code, some more good advice:

Start using the conventions of the C# language now.  You wrote Console.WriteLine and then made a method print_order.  Follow the pattern set by the designers of the framework, not something you've just made up on your own.  Types and methods should be CasedLikeThis.

Never put an int.Parse in a try-catch, ever. That's what int.TryParse is for!

Your program has a bug; what happens if someone types in, say, 7?  Handle that case!

Body:
I am on my final project in c# for beginners, but I can't seem to get my list to work properly. It also closes automatically after being 'filled' with orders.

class Burgare
{
    private string[] hamburger = new string[24];
    private int no_burger = 0;

    public void add_burger()//Ordering of burgers
    {
        Console.Clear(); //Clears console to make it look cleaner
        while (true)
        {
            int Burger_option = 0;
            do
            {
                Console.WriteLine("");// The options user can choose from
                Console.WriteLine("Please choose burgers from our menu:");
                Console.WriteLine("-------Burgers--------");
                Console.WriteLine("1 Original One     109");
                Console.WriteLine("2 Pig & Cow        109");
                Console.WriteLine("3 Spice & Nice     109");
                Console.WriteLine("4 Green One        109");
                Console.WriteLine("0 Go back to main menu");
                Console.WriteLine("----------------------");
                Console.WriteLine("");

                try //Making sure the user only picks what is on the menu
                {
                    Burger_option = int.Parse(Console.ReadLine());
                }

                catch
                {
                    Console.WriteLine("You can only choose what is on the menu!");

                }

                switch (Burger_option) //Depending on the number user presses on keyboard different burgers will be added to order
                {
                    case 1:
                        Console.WriteLine("You've added the Original One to your order");
                        Console.WriteLine("If you're done press 0 to go back to the main menu");
                        hamburger[no_burger] = "Original One";
                        break;

                    case 2:
                        Console.WriteLine("You've added the Pig & Cow to your order");
                        Console.WriteLine("If you're done press 0 to go back to the main menu");
                        hamburger[no_burger] = "Pig & Cow";
                        break;

                    case 3:
                        Console.WriteLine("You've added the Spice & Nice to your order");
                        Console.WriteLine("If you're done press 0 to go back to the main menu");
                        hamburger[no_burger] = "Spice & Nice";
                        break;

                    case 4:
                        Console.WriteLine("You've added the Green One to your order");
                        Console.WriteLine("If you're done press 0 to go back to the main menu");
                        hamburger[no_burger] = "Green One";
                        break;

                    case 0: //Sends user back to main menu
                        Run();
                        break;
                }
                no_burger++; //Adds burger

            } while (no_burger != 0);

            if (no_burger <= 25) //Maximum number of orders
            {
                Console.WriteLine("The restaurant can't take more than 24 orders of burgers at the time");
                Run(); //Sends user back to main menu when the order is over 24
            }
        }
    }

    public void print_order()
    {

        Console.WriteLine("-Your current order-");

    foreach (var burger in hamburger) //Showing a list of what is in the order
        {
         Console.WriteLine(hamburger);

         if (burger != null)

                Console.WriteLine(burger);
         else
                Console.WriteLine("Empty space"); //Making empty space to show where you can add more burgers
        }

    }

After entering 24 orders I get the error "System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'" I've looked around a bit but still don't really understand how to fix my code. I'd like for it to return to the main menu after telling the user the order is full.

For my second problem the System.String [] problem, it appears when I enter the 'print_order'. It shows itself as
System.String []
Empty space
System.String []
Empty space
And so on. If possible I'd like to either remove it completely or at least replace it with 1,2,3...etc.


问:
Any good tutorials/examples for the Spring3 Security Framework?
Can someone please help me out, I am just getting into Spring3, Spring3 MVC Validation and Hibernate

Can someone please tell me of  any good tutorials/examples for the Spring3 Security Framework?

I would love to find a example that looks up the user information from a database.  please help me out!  thanks.  SPRING3

答:
I would visit the Getting Started link of spring security and follow the steps mentioned therein, specifically

deploy the sample application

follow the petclinic tutorial

Then move on to links suggested by others.

ContentLicense: CC BY-SA 2.5


问:
Calculate mean and median by date range in Shiny
Want to calculate mean and median of the numeric variables grouped by a selected date range for the datatable only, not the leaflet data. The leaflet map works (just need to zoom out to see the fake long/lat plots but not worried about that now).

I created a second dataframe df10 for the datatable median/mean summations of the data.

So far tried altering the input function to create separate variables for the mean but found it to be cumbersome and not necessary for my needs.

Attempted to use colMeans(dataset()[,which(sapply(dataset(), class) != "Date")]) here Shiny calculate the mean of columns in dataframe

The error is "invalid 'x' type in 'x && y". It's in relation to the colmeans

```<code>### Generate a dataset ###
start_date <- as.Date('2018-01-01')
end_date <- as.Date('2019-05-10')
set.seed(1984)
date1 <- as.Date(sample( as.numeric(start_date): as.numeric(end_date), 988,
                         replace = T), origin = '1970-01-01')
group <- rep(letters[1:26], each = 38)
x1 <- runif(n = 988, min = 3.26, max = 10)
x2 <- runif(n = 988, min = 3.26, max = 10)
x3 <- runif(n = 988, min = 3.26, max = 10)
x4 <- runif(n = 988, min = 3.26, max = 10)
x5 <- runif(n = 988, min = 3.26, max = 10)
latitude <- runif(988,40.75042,50.75042)
longitude <- runif(988,-73.98928,-63.98928)

dataframe <- cbind(data.frame(date1,group,x1,x2,x3,x4,x5,latitude,longitude))

df10 <- cbind(data.frame(date1,group,x1,x2,x3,x4,x5))
library(lubridate)
dataframe$date <- ymd(dataframe$date1)
df10$date <- ymd(df10$date1)

library(shiny)
library(leaflet)
library(DT)
dataframe$defectrateLvl <- cut(dataframe$x1,
                               c(3.26,6,100), include.lowest = T,
                               labels = c('3.26-6x','6x+'))
beatCol <- colorFactor(palette = c('yellow', 'red'), dataframe$defectrateLvl)

ui <- fluidPage(
  dateInput(inputId = "date", label="Select a date", value = "2019-03-01", min = "2018-01-01", max = "2019-05-10",
            format = "yyyy-mm-dd", startview = "month",
            language = "en", width = NULL),
  leafletOutput("map"),
  fluidRow(
    dateRangeInput("daterange","Date range:",start=Sys.Date()-10, end=Sys.Date() -1),
    DT::dataTableOutput("tbl")
  )
)

server <- shinyServer(function (input, output,session) {
  dailyData <- reactive(dataframe[dataframe$date == format(input$date, '%Y/%m/%d'), ] )
  output$map <- renderLeaflet({
    dataframe <- dailyData()  # Added this in attempt to integrate
    dataframe %>% leaflet() %>%
      setView(lng = -73.98928, lat = 40.75042, zoom = 10) %>%
      addProviderTiles("CartoDB.Positron", options = providerTileOptions(noWrap = TRUE)) %>%
      addCircleMarkers(
        lng=~dataframe$longitude, # Longitude coordinates
        lat=~dataframe$latitude, # Latitude coordinates
        #radius=~defectrateLvl, # Total count
        popup =~ dataframe$group,
        color = ~beatCol(dataframe$defectrateLvl),
        fillOpacity=0.5 # Circle Fill Opacity
      )
  })
  output$tbl<-DT::renderDataTable({
    dataset <- reactive({df10 })
    dataset() %>% group_by(group) %>%
      filter(date > input$daterange[1],
             date < input$daterange[2])
    #sapply(Filter(is.numeric, df6), mean)
    colMeans(dataset()[,which(sapply(dataset(), class) !="date","date1","group")])
  })

})

shinyApp(ui, server)
</code>```

I expect to have the numeric variables to be summarized by mean and if possible by median but that's less important at this time.  Any help would be greatly appreciated.

答:
The error is caused by the last function.

```<code>colMeans(df[,which(sapply(df, class) !="date","date1","group")])
</code>```

This code will apply the function to all columns which are not of class xy. "date" or "group" are column names.

ColMeans also produces a numeric vector, which will result in an error, because DT can only display a matrix or a data.frame. I provided you a code with creates a dataframe. But in generell I would think about using dplyr to create your result. It is much easier.

Here is a solution that works, however you have to change the dateinputs, since the predefined selection creates a data.frame with 0 rows.

```<code>library(lubridate)
library(shiny)
library(leaflet)
library(DT)
library(dplyr)

### Generate a dataset ###
start_date <- as.Date('2018-01-01')
end_date <- as.Date('2019-05-10')
set.seed(1984)
date1 <- as.Date(sample( as.numeric(start_date): as.numeric(end_date), 988,
                         replace = T), origin = '1970-01-01')
group <- rep(letters[1:26], each = 38)
x1 <- runif(n = 988, min = 3.26, max = 10)
x2 <- runif(n = 988, min = 3.26, max = 10)
x3 <- runif(n = 988, min = 3.26, max = 10)
x4 <- runif(n = 988, min = 3.26, max = 10)
x5 <- runif(n = 988, min = 3.26, max = 10)
latitude <- runif(988,40.75042,50.75042)
longitude <- runif(988,-73.98928,-63.98928)

dataframe <- cbind(data.frame(date1,group,x1,x2,x3,x4,x5,latitude,longitude))

df10 <- cbind(data.frame(date1,group,x1,x2,x3,x4,x5))
dataframe$date <- ymd(dataframe$date1)
df10$date <- ymd(df10$date1)

dataframe$defectrateLvl <- cut(dataframe$x1,
                               c(3.26,6,100), include.lowest = T,
                               labels = c('3.26-6x','6x+'))
beatCol <- colorFactor(palette = c('yellow', 'red'), dataframe$defectrateLvl)

ui <- fluidPage(
    dateInput(inputId = "date", label="Select a date", value = "2019-03-01", min = "2018-01-01", max = "2019-05-10",
              format = "yyyy-mm-dd", startview = "month",
              language = "en", width = NULL),
    leafletOutput("map"),
    fluidRow(
        dateRangeInput("daterange","Date range:",start=Sys.Date()-10, end=Sys.Date() -1),
        DT::dataTableOutput("tbl")
    )
)

server <- shinyServer(function (input, output,session) {
    dailyData <- reactive(dataframe[dataframe$date == format(input$date, '%Y/%m/%d'), ] )
    output$map <- renderLeaflet({
        dataframe <- dailyData()  # Added this in attempt to integrate
        dataframe %>% leaflet() %>%
            setView(lng = -73.98928, lat = 40.75042, zoom = 10) %>%
            addProviderTiles("CartoDB.Positron", options = providerTileOptions(noWrap = TRUE)) %>%
            addCircleMarkers(
                lng=~dataframe$longitude, # Longitude coordinates
                lat=~dataframe$latitude, # Latitude coordinates
                #radius=~defectrateLvl, # Total count
                popup =~ dataframe$group,
                color = ~beatCol(dataframe$defectrateLvl),
                fillOpacity=0.5 # Circle Fill Opacity
            )
    })

    dataset <- reactive({df10 })

    output$tbl <-DT::renderDataTable({
        df <- dataset()

        df <- df %>%
            group_by(group) %>%
            filter(date > input$daterange[1],
                   date < input$daterange[2])
        #sapply(Filter(is.numeric, df6), mean)
        result <- data.frame(colMeans(df[which(sapply(df, class)=="numeric")]))
        colnames(result)[1] <- "Result"
        result
        #colMeans(df[,which(sapply(df, class) !="date","date1","group")])
    })

})

shinyApp(ui, server)
</code>```

Body:
Want to calculate mean and median of the numeric variables grouped by a selected date range for the datatable only, not the leaflet data. The leaflet map works (just need to zoom out to see the fake long/lat plots but not worried about that now).

I created a second dataframe df10 for the datatable median/mean summations of the data.

So far tried altering the input function to create separate variables for the mean but found it to be cumbersome and not necessary for my needs.

Attempted to use colMeans(dataset()[,which(sapply(dataset(), class) != "Date")]) here Shiny calculate the mean of columns in dataframe

The error is "invalid 'x' type in 'x && y". It's in relation to the colmeans

### Generate a dataset ###
start_date <- as.Date('2018-01-01')
end_date <- as.Date('2019-05-10')
set.seed(1984)
date1 <- as.Date(sample( as.numeric(start_date): as.numeric(end_date), 988,
                         replace = T), origin = '1970-01-01')
group <- rep(letters[1:26], each = 38)
x1 <- runif(n = 988, min = 3.26, max = 10)
x2 <- runif(n = 988, min = 3.26, max = 10)
x3 <- runif(n = 988, min = 3.26, max = 10)
x4 <- runif(n = 988, min = 3.26, max = 10)
x5 <- runif(n = 988, min = 3.26, max = 10)
latitude <- runif(988,40.75042,50.75042)
longitude <- runif(988,-73.98928,-63.98928)

dataframe <- cbind(data.frame(date1,group,x1,x2,x3,x4,x5,latitude,longitude))

df10 <- cbind(data.frame(date1,group,x1,x2,x3,x4,x5))
library(lubridate)
dataframe$date <- ymd(dataframe$date1)
df10$date <- ymd(df10$date1)

library(shiny)
library(leaflet)
library(DT)
dataframe$defectrateLvl <- cut(dataframe$x1,
                               c(3.26,6,100), include.lowest = T,
                               labels = c('3.26-6x','6x+'))
beatCol <- colorFactor(palette = c('yellow', 'red'), dataframe$defectrateLvl)

ui <- fluidPage(
  dateInput(inputId = "date", label="Select a date", value = "2019-03-01", min = "2018-01-01", max = "2019-05-10",
            format = "yyyy-mm-dd", startview = "month",
            language = "en", width = NULL),
  leafletOutput("map"),
  fluidRow(
    dateRangeInput("daterange","Date range:",start=Sys.Date()-10, end=Sys.Date() -1),
    DT::dataTableOutput("tbl")
  )
)

server <- shinyServer(function (input, output,session) {
  dailyData <- reactive(dataframe[dataframe$date == format(input$date, '%Y/%m/%d'), ] )
  output$map <- renderLeaflet({
    dataframe <- dailyData()  # Added this in attempt to integrate
    dataframe %>% leaflet() %>%
      setView(lng = -73.98928, lat = 40.75042, zoom = 10) %>%
      addProviderTiles("CartoDB.Positron", options = providerTileOptions(noWrap = TRUE)) %>%
      addCircleMarkers(
        lng=~dataframe$longitude, # Longitude coordinates
        lat=~dataframe$latitude, # Latitude coordinates
        #radius=~defectrateLvl, # Total count
        popup =~ dataframe$group,
        color = ~beatCol(dataframe$defectrateLvl),
        fillOpacity=0.5 # Circle Fill Opacity
      )
  })
  output$tbl<-DT::renderDataTable({
    dataset <- reactive({df10 })
    dataset() %>% group_by(group) %>%
      filter(date > input$daterange[1],
             date < input$daterange[2])
    #sapply(Filter(is.numeric, df6), mean)
    colMeans(dataset()[,which(sapply(dataset(), class) !="date","date1","group")])
  })

})

shinyApp(ui, server)

I expect to have the numeric variables to be summarized by mean and if possible by median but that's less important at this time.  Any help would be greatly appreciated.

Body:
The error is caused by the last function.

colMeans(df[,which(sapply(df, class) !="date","date1","group")])

This code will apply the function to all columns which are not of class xy. "date" or "group" are column names.

ColMeans also produces a numeric vector, which will result in an error, because DT can only display a matrix or a data.frame. I provided you a code with creates a dataframe. But in generell I would think about using dplyr to create your result. It is much easier.

Here is a solution that works, however you have to change the dateinputs, since the predefined selection creates a data.frame with 0 rows.

library(lubridate)
library(shiny)
library(leaflet)
library(DT)
library(dplyr)

### Generate a dataset ###
start_date <- as.Date('2018-01-01')
end_date <- as.Date('2019-05-10')
set.seed(1984)
date1 <- as.Date(sample( as.numeric(start_date): as.numeric(end_date), 988,
                         replace = T), origin = '1970-01-01')
group <- rep(letters[1:26], each = 38)
x1 <- runif(n = 988, min = 3.26, max = 10)
x2 <- runif(n = 988, min = 3.26, max = 10)
x3 <- runif(n = 988, min = 3.26, max = 10)
x4 <- runif(n = 988, min = 3.26, max = 10)
x5 <- runif(n = 988, min = 3.26, max = 10)
latitude <- runif(988,40.75042,50.75042)
longitude <- runif(988,-73.98928,-63.98928)

dataframe <- cbind(data.frame(date1,group,x1,x2,x3,x4,x5,latitude,longitude))

df10 <- cbind(data.frame(date1,group,x1,x2,x3,x4,x5))
dataframe$date <- ymd(dataframe$date1)
df10$date <- ymd(df10$date1)

dataframe$defectrateLvl <- cut(dataframe$x1,
                               c(3.26,6,100), include.lowest = T,
                               labels = c('3.26-6x','6x+'))
beatCol <- colorFactor(palette = c('yellow', 'red'), dataframe$defectrateLvl)

ui <- fluidPage(
    dateInput(inputId = "date", label="Select a date", value = "2019-03-01", min = "2018-01-01", max = "2019-05-10",
              format = "yyyy-mm-dd", startview = "month",
              language = "en", width = NULL),
    leafletOutput("map"),
    fluidRow(
        dateRangeInput("daterange","Date range:",start=Sys.Date()-10, end=Sys.Date() -1),
        DT::dataTableOutput("tbl")
    )
)

server <- shinyServer(function (input, output,session) {
    dailyData <- reactive(dataframe[dataframe$date == format(input$date, '%Y/%m/%d'), ] )
    output$map <- renderLeaflet({
        dataframe <- dailyData()  # Added this in attempt to integrate
        dataframe %>% leaflet() %>%
            setView(lng = -73.98928, lat = 40.75042, zoom = 10) %>%
            addProviderTiles("CartoDB.Positron", options = providerTileOptions(noWrap = TRUE)) %>%
            addCircleMarkers(
                lng=~dataframe$longitude, # Longitude coordinates
                lat=~dataframe$latitude, # Latitude coordinates
                #radius=~defectrateLvl, # Total count
                popup =~ dataframe$group,
                color = ~beatCol(dataframe$defectrateLvl),
                fillOpacity=0.5 # Circle Fill Opacity
            )
    })

    dataset <- reactive({df10 })

    output$tbl <-DT::renderDataTable({
        df <- dataset()

        df <- df %>%
            group_by(group) %>%
            filter(date > input$daterange[1],
                   date < input$daterange[2])
        #sapply(Filter(is.numeric, df6), mean)
        result <- data.frame(colMeans(df[which(sapply(df, class)=="numeric")]))
        colnames(result)[1] <- "Result"
        result
        #colMeans(df[,which(sapply(df, class) !="date","date1","group")])
    })

})

shinyApp(ui, server)


问:
How to match a string between <>?
I tried \w+\:(\w+\-?\.?(\d+)?) but that is not correct

I have following text

<staticText:HelloWorld>_<xmlNode:Node.03>_<date:yyy-MM-dd>_<time:HH-mm-ss-fff>

The end result I want is something like the following

["staticText:HelloWorld", "xmlNode:Node.03","date:yyy-MM-dd","time:HH-mm-ss-fff"]
```

答:
Your pattern does not match the 3rd and the 4th part of the example data because in this part \w+\-?\.?(\d+)? the dash and the digits match only once and are not repeated.

For your example data, you might use a character class [\w.-]+to match the part after the colon to make the match a bit more broad:

```<code><(\w+\:[\w.-]+)>
</code>```

Regex demo | C# demo

Or to make it more specific, specify a pattern for either the Node.03 part and for the year month date hour etc parts using a repeated pattern.

```<code><(\w+\:\w+(?:\.\d+|\d+(?:-\d+)+)?)>
</code>```

Explanation

< Match <

( Capturing group

\w+\:\w+ Match 1+ word chars, : and 1+ word chars

(?: Non capturing group

\.\d+ Match . and 1+ digits

| Or

\d+(?:-\d+)+ Match 1+ digits and repeat 1+ times matching - and 1+ digits

)? Close non capturing group and make it optional

) Close capturing group

>

Regex demo | C# Demo

Title: How to match a string between <>?

Body:
Your pattern does not match the 3rd and the 4th part of the example data because in this part \w+\-?\.?(\d+)? the dash and the digits match only once and are not repeated.

For your example data, you might use a character class [\w.-]+to match the part after the colon to make the match a bit more broad:

<(\w+\:[\w.-]+)>

Regex demo | C# demo

Or to make it more specific, specify a pattern for either the Node.03 part and for the year month date hour etc parts using a repeated pattern.

<(\w+\:\w+(?:\.\d+|\d+(?:-\d+)+)?)>

Explanation

< Match <

( Capturing group

\w+\:\w+ Match 1+ word chars, : and 1+ word chars

(?: Non capturing group

\.\d+ Match . and 1+ digits

| Or

\d+(?:-\d+)+ Match 1+ digits and repeat 1+ times matching - and 1+ digits

)? Close non capturing group and make it optional

) Close capturing group

>

Regex demo | C# Demo


问:
How to add new widget in GridLayout without resizing older widgets?
I have added GridLayout to ScrollView, and I'm adding widgets in GridLayout dynamically from python program.Instead of using more space of window it's resizing height of older widgets.What am i doing wrong here?

I tried putting BoxLayout inside GridLayout but it's not working.
I also tried to add widgets directly to ScrollView but i found out ScrollView only supports one widget.

My kv code:

```<code><Downloading>:
    my_grid: mygrid
    GridLayout:
        cols: 1
        size_hint_y : None
        hight: self.minimum_height
        id: mygrid
</code>```

My python code:

```<code>class Downloading(ScrollView):
    set_text = ObjectProperty()
    my_grid = ObjectProperty()

    def __init__(self, select, link, path, username, password):

        self.select = select
        self.link = link
        self.path = path
        self.username = username
        self.password = password
        self.p_bar = []
        self.stat = []

        self.parent_conn, self.child_conn = Pipe()

        p = Process(target=main, args=(self.child_conn, self.select,
                                       self.link, self.path,
                                       self.username, self.password))
        p.start()

        super().__init__()

        self.event = Clock.schedule_interval(self.download_GUI, 0.1)

    def newFile(self, title):
        # self.newId = "stat" + str(len(self.p_bar) + 1)
        self.stat.append(Label(text=''))
        self.p_bar.append(ProgressBar())
        self.my_grid.add_widget(Label(text=title))
        self.my_grid.add_widget(self.stat[-1])
        self.my_grid.add_widget(self.p_bar[-1])

    def download_GUI(self, a):

        temp = self.parent_conn.recv()

        print(temp)

        if temp == "new":
            self.downloading = True
            return
        if self.downloading:
            self.newFile(temp)
            self.downloading = False
            return
        if type(temp) == type({}):
            self.complete = temp['complete']
            if not self.complete:
                status = "{0}//{1} @ {2}  ETA: {3}".format(temp['dl_size'],
                                                      temp['total_size'],temp['speed'],temp['eta'])
                self.stat[-1].text = status
                self.p_bar[-1].value = temp['progress']
                return

        if temp == "end":
            self.event.cancel()
            Clock.schedule_once(exit, 3)
</code>```

答:
After applying following changes to kv file

```<code><Downloading>:
    size: self.size
    my_grid: mygrid
    GridLayout:
        cols: 1
        size_hint_y : None
        row_default_height: '25dp'
        row_force_default: True
        id: mygrid
</code>```

And adding this line in the end of constructor (__init__), it is working as expected.

self.my_grid.bind(minimum_height=self.my_grid.setter('height'))
```

Body:
I have added GridLayout to ScrollView, and I'm adding widgets in GridLayout dynamically from python program.Instead of using more space of window it's resizing height of older widgets.What am i doing wrong here?

I tried putting BoxLayout inside GridLayout but it's not working.
I also tried to add widgets directly to ScrollView but i found out ScrollView only supports one widget.

My kv code:

<Downloading>:
    my_grid: mygrid
    GridLayout:
        cols: 1
        size_hint_y : None
        hight: self.minimum_height
        id: mygrid

My python code:

class Downloading(ScrollView):
    set_text = ObjectProperty()
    my_grid = ObjectProperty()

    def __init__(self, select, link, path, username, password):

        self.select = select
        self.link = link
        self.path = path
        self.username = username
        self.password = password
        self.p_bar = []
        self.stat = []

        self.parent_conn, self.child_conn = Pipe()

        p = Process(target=main, args=(self.child_conn, self.select,
                                       self.link, self.path,
                                       self.username, self.password))
        p.start()

        super().__init__()

        self.event = Clock.schedule_interval(self.download_GUI, 0.1)

    def newFile(self, title):
        # self.newId = "stat" + str(len(self.p_bar) + 1)
        self.stat.append(Label(text=''))
        self.p_bar.append(ProgressBar())
        self.my_grid.add_widget(Label(text=title))
        self.my_grid.add_widget(self.stat[-1])
        self.my_grid.add_widget(self.p_bar[-1])

    def download_GUI(self, a):

        temp = self.parent_conn.recv()

        print(temp)

        if temp == "new":
            self.downloading = True
            return
        if self.downloading:
            self.newFile(temp)
            self.downloading = False
            return
        if type(temp) == type({}):
            self.complete = temp['complete']
            if not self.complete:
                status = "{0}//{1} @ {2}  ETA: {3}".format(temp['dl_size'],
                                                      temp['total_size'],temp['speed'],temp['eta'])
                self.stat[-1].text = status
                self.p_bar[-1].value = temp['progress']
                return

        if temp == "end":
            self.event.cancel()
            Clock.schedule_once(exit, 3)

Body:
After applying following changes to kv file

<Downloading>:
    size: self.size
    my_grid: mygrid
    GridLayout:
        cols: 1
        size_hint_y : None
        row_default_height: '25dp'
        row_force_default: True
        id: mygrid

And adding this line in the end of constructor (__init__), it is working as expected.

self.my_grid.bind(minimum_height=self.my_grid.setter('height'))


问:
Add ckeditors fields dynamically in modal
i have a cms where on click open modal and inside i have few fields and then i have another button inside of modal where i can add dynamically ckeditors fields by clicking on button, here is what i was trying to do:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>

  <button style="margin-bottom:5px;" type="button" data-toggle="modal" data-target="#add_data_Modal" class="btn btn-success"> Adauga</button>

      <button type="button" class="close" data-dismiss="modal">×</button>

Adauga categorie

          <form action="add.php" method="POST">

              Nume Categorie

              <input type="text" class="form-control" name="nume" id="nume" placeholder="Nume categorie">

              Categorie

              <select class="form-control" id="categorie" name="categorie">

                  <option value="0">Categorie principala</option>

              </select>

              Vizibil

              <select class="form-control" id="activ" name="activ">

                  <option selected>Selecteaza vizibilitatea</option>

                  <option value="1">Da</option>

                  <option value="0">Nu</option>

              </select>

              Pozitia

              <input type="text" class="form-control" name="pozitie" id="pozitie" placeholder="Pozitie">

                <input type="checkbox" id="user-checkbox1" checked="">

                Modele Produse

                <input type="checkbox" id="user-checkbox2" checked="">

                Paletar Materiale

                <input type="checkbox" id="user-checkbox3" checked="">

                Estimare Pret

Adauga tab-uri

                +

        <button type="button" class="btn btn-secondary" data-dismiss="modal"> Inchide</button>

        <button type="submit" name="submit" class="btn btn-primary"> Salveaza</button>

       </form>

```

In this modal when i click on add i want to add more fields, is done this but not appear ckeditor just a plain textarea which i don`t need that.
Thank you!

答:
You are probably going to want to give the textarea a custom id if you plan to have multiple of them.

```<code>let currentId = 0;
</code>```

I moved the 'var html' code inside the create function so that we can edit the id every time the add button is clicked because we need a unique id each time. After the textarea exists, I call .ckeditor() on that textarea which should enable the ckeditor tools for that field. Then I increment the customId to make sure that the next form that is added has a different id.

```<code>$("#add_aut").click(function(e){

    var html3 = '<div class="row" id="parent-autor"> <p id="auth-del"><i class="fa fa-minus-square" aria-hidden="true"></i></p> <div class="row"> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" placeholder="titlu_tab" name="titlu_tab[]"> </div> </div> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" placeholder="Pozitie" name="pozitie_tab[]"> </div> </div> </div> <div class="col-md-12"> <div class="form-group"> <textarea name="editor[]" class="ckeditor" id="continut' + currentId + '" rows="8" cols="80"></textarea> </div> </div></div>';
    $('#auth-rows').append(html3);
    $('#continut' + currentId).ckeditor();
    currentId += 1;

});
</code>```

You may not want the customId in the id of the textarea depending on what you are trying to accomplish, but this should get you going in the correct direction.

Also, you need to add the ckeditor.js as well as a jquery adapter script for this to work.

See this fiddle https://jsfiddle.net/bkqxnu8f/3/

Body:
i have a cms where on click open modal and inside i have few fields and then i have another button inside of modal where i can add dynamically ckeditors fields by clicking on button, here is what i was trying to do:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>

  <button style="margin-bottom:5px;" type="button" data-toggle="modal" data-target="#add_data_Modal" class="btn btn-success"> Adauga</button>

      <button type="button" class="close" data-dismiss="modal">×</button>

Adauga categorie

          <form action="add.php" method="POST">

              Nume Categorie

              <input type="text" class="form-control" name="nume" id="nume" placeholder="Nume categorie">

              Categorie

              <select class="form-control" id="categorie" name="categorie">

                  <option value="0">Categorie principala</option>

              </select>

              Vizibil

              <select class="form-control" id="activ" name="activ">

                  <option selected>Selecteaza vizibilitatea</option>

                  <option value="1">Da</option>

                  <option value="0">Nu</option>

              </select>

              Pozitia

              <input type="text" class="form-control" name="pozitie" id="pozitie" placeholder="Pozitie">

                <input type="checkbox" id="user-checkbox1" checked="">

                Modele Produse

                <input type="checkbox" id="user-checkbox2" checked="">

                Paletar Materiale

                <input type="checkbox" id="user-checkbox3" checked="">

                Estimare Pret

Adauga tab-uri

                +

        <button type="button" class="btn btn-secondary" data-dismiss="modal"> Inchide</button>

        <button type="submit" name="submit" class="btn btn-primary"> Salveaza</button>

       </form>

In this modal when i click on add i want to add more fields, is done this but not appear ckeditor just a plain textarea which i don`t need that.
Thank you!

Body:
You are probably going to want to give the textarea a custom id if you plan to have multiple of them.

let currentId = 0;

I moved the 'var html' code inside the create function so that we can edit the id every time the add button is clicked because we need a unique id each time. After the textarea exists, I call .ckeditor() on that textarea which should enable the ckeditor tools for that field. Then I increment the customId to make sure that the next form that is added has a different id.

$("#add_aut").click(function(e){

    var html3 = '<div class="row" id="parent-autor"> <p id="auth-del"><i class="fa fa-minus-square" aria-hidden="true"></i></p> <div class="row"> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" placeholder="titlu_tab" name="titlu_tab[]"> </div> </div> <div class="col-md-4"> <div class="form-group"> <input type="text" class="form-control" placeholder="Pozitie" name="pozitie_tab[]"> </div> </div> </div> <div class="col-md-12"> <div class="form-group"> <textarea name="editor[]" class="ckeditor" id="continut' + currentId + '" rows="8" cols="80"></textarea> </div> </div></div>';
    $('#auth-rows').append(html3);
    $('#continut' + currentId).ckeditor();
    currentId += 1;

});

You may not want the customId in the id of the textarea depending on what you are trying to accomplish, but this should get you going in the correct direction.

Also, you need to add the ckeditor.js as well as a jquery adapter script for this to work.

See this fiddle https://jsfiddle.net/bkqxnu8f/3/


问:
Deploying to Weblogic 10.3.6 from Eclipse -- "There are no resources that can be added or removed from the server."
I have a Spring Boot application. I build it with Maven. I have the pom configured to produce a Weblogic-compatible .war file. I can deploy this war file manually via either the WebLogic console or via the weblogic-maven-plugin Maven command.

I have now added my WebLogic server and domain to my Eclipse servers panel. I can start and stop it just fine, but when I click "Add and Remove", I get:

```<code>There are no resources that can be added or removed from the server.
</code>```

In my Project Facets, I have:

```<code>Dynamic Web Module 2.5
Java 1.7 (matches what WebLogic wants and what my pom specifies)
</code>```

What else can I check or change?

答:
Sometimes the problem might also because you did not select the dynamic web module .
To do so open your project properties then goto your Project Facets then Check/Select the Dynamic Web Module checkbox then apply & close.</p>

Body:
I have a Spring Boot application. I build it with Maven. I have the pom configured to produce a Weblogic-compatible .war file. I can deploy this war file manually via either the WebLogic console or via the weblogic-maven-plugin Maven command.

I have now added my WebLogic server and domain to my Eclipse servers panel. I can start and stop it just fine, but when I click "Add and Remove", I get:

There are no resources that can be added or removed from the server.

In my Project Facets, I have:

Dynamic Web Module 2.5
Java 1.7 (matches what WebLogic wants and what my pom specifies)

What else can I check or change?


问:
Does Spring Kafka producer guarantee delivery by default?
I wonder whether spring kafka Producer within spring boot guarantee delivery or not.

Does anybody know what happens if some random listener fails to receive message? Would spring kafka retry to send the message?

答:
There are some concepts here:

Producer will produce events and send them to kafka server. You must be aware on the producer side for retries and things like that if Kafka will have downtime or other error scenarios that are specific to your context.

Consumers will have assign partitions by Kafka, each partition will deliver events and each event will have an offset. Consumers will poll for data from kafka (they will request for data, kafka will not push data to consumers, but consumers will go to kafka and require data). Every event that is delivered with success by Kafka to the consumers will produce and Acknowledgment and Kafka will commit the offset of the event. So the next event, with a higher offeset will be delivered to the consumer. If a consumer goes down, partitions will be reasigned to other consumers, so you won't lose your data. If you have only one consumer, the data will be stored in Kafka and when the consumer will be back, it will go and request data from the latest/earliest offset.


问:
Remove the scroll bar on a list box
I'm using a userForm in vba and I have a list box.  I want to remove the horoz. scroll bar from the bottom.  Is there a way to do this?  I don't see any option in the properties box.

答:
Try making the listbox a little wider.... not mucn wider, but just enough to get rid of the horizontal scroll bar.

Maybe that will work.

Title: Remove the scroll bar on a list box


问:
AppDomains and debug symbols
I have a project in which I'm using AppDomains with a very restricted PermissionSet.

The problem is that, if an exception occurs inside the AppDomain, the StackTrace property of the Exception object contains the names of the methods in the stack trace, but not the line numbers, despite the fact that the PDB data has been loaded into the assembly within the AppDomain.

In the course of debugging, I found that if I made the following change to my permission set, then line numbers start appearing in the stack trace:

```<code>PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);    // Was PermissionState.None
permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, new AppDomainSetup {......}, permSet);
</code>```

Obviously the downside of setting the permission set to be unrestricted is that the code that runs in this AppDomain can now do whatever it wants, so although this lets me see the line numbers in the stack trace, it's not an acceptable solution. I'm figuring that there must be a specific permission I need to add to the permission set - but I can't for the life of me figure out what permission that is.

Can anyone point me in the right direction here, or even better, tell me what permission I need to add? Thanks!

答: As discussed in the comments, the solution was hiding in the source code of the Exception object, and it is that you need to add FileIOPermission(PathDiscovery).</p>

Title: AppDomains and debug symbols

Body:
I have a project in which I'm using AppDomains with a very restricted PermissionSet.

The problem is that, if an exception occurs inside the AppDomain, the StackTrace property of the Exception object contains the names of the methods in the stack trace, but not the line numbers, despite the fact that the PDB data has been loaded into the assembly within the AppDomain.

In the course of debugging, I found that if I made the following change to my permission set, then line numbers start appearing in the stack trace:

PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);    // Was PermissionState.None
permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, new AppDomainSetup {......}, permSet);

Obviously the downside of setting the permission set to be unrestricted is that the code that runs in this AppDomain can now do whatever it wants, so although this lets me see the line numbers in the stack trace, it's not an acceptable solution. I'm figuring that there must be a specific permission I need to add to the permission set - but I can't for the life of me figure out what permission that is.

Can anyone point me in the right direction here, or even better, tell me what permission I need to add? Thanks!


问:
pip install & uninstall recursively in non-interactive mode
As a part of my bash script, I want to install and uninstall pip dependencies that I have their names in a file in a non-interactive mode. I was able to search around and find these commands:

```<code>pip3 uninstall --yes -r host-requirements.txt
pip3 install --no-input -r host-requirements.txt
</code>```

I wasn't able to find --yes & --no-input options in the help doc of pip, and I'm not sure if they are officially supported.

答:
For uninstall, you can use the --yes or -y flag as described here: https://pip.pypa.io/en/stable/cli/pip_uninstall/

For installation, you can pass a yes | pip install -r requirements.txt as described here: python pip silent install

Hope this helps.

Body:
As a part of my bash script, I want to install and uninstall pip dependencies that I have their names in a file in a non-interactive mode. I was able to search around and find these commands:

pip3 uninstall --yes -r host-requirements.txt
pip3 install --no-input -r host-requirements.txt

I wasn't able to find --yes & --no-input options in the help doc of pip, and I'm not sure if they are officially supported.


问:
Merging two csv files into list of dictionaries
i have a task to do and i got stuck because whatever i do it does't seem to work.

So i have to csv files.
First called persons_file and it contains header line: id, name, surname.
And visits_file containing id, person_id, site.
I have to write a function called merge that gets to files as arguments (both StrionIO type) and returns list of dictionaries with number of visits for each users:

```<code>[ {
 "id": (person's id),
 "name": (person's name),
 "surname": (person's surname),
 "visits": (number of visits)
 } ]
</code>```

I came up with this and i don't know where my mistake is.

```<code>import io

def merge(persons_file,visits_file):
    line_counter = 0
    return_list = []
    list_of_person_ids = []
    visits = 0

    for row in visits_file:
        if line_counter == 0:
            line_counter+=1
            continue
        list_of_person_ids.append(row.split(',')[1])

    line_counter = 0

    for row in persons_file:
        if line_counter == 0:
            line_counter+=1
            continue
        help_dict = {}
        split_row = row.split(',')
        help_dict['id'] = split_row[0]
        help_dict['name'] = split_row[1]
        help_dict['surname'] = split_row[2][:len(split_row[2])-1]
        if split_row[0] in list_of_person_ids:
            visits = list_of_person_ids.count(split_row[0])
        help_dict['visits'] = str(visits)
        return_list.append(help_dict)
        visits=0
    return return_list

file1 = open('persons_file.csv' , mode='r')
file2 = open('visits_file.csv' , mode='r')
persons_file_arg = io.StringIO(file1.read())
visits_file_arg = io.StringIO(file2.read())

list_of_visits = merge(persons_file_arg,visits_file_arg)
for i in list_of_visits:
    print(i)
file1.close()
file2.close()
</code>```

I will be glad if anyone could help me.

答:
What is the issue? Is it the output that is not what you expected, or are you getting an exception? Your code seems like it should achieve the result you want, but I have a couple suggestions to make that could simplify things.

Look into collections.Counter you could then call count_of_visits_by_person_id = Counter(list_of_person_ids) to get a result of the form:
{person_id: number_of_visits, ...}. You could then use this to simply look up the number of visits in your next for loop. e.g.:

```<code>from collections import Counter

...

count_of_visits_by_person_id = Counter(list_of_person_ids)

for row in persons_file:
    if line_counter == 0:
        line_counter += 1
        continue

    help_dict = {}
    split_row = row.split(',')

    help_dict['id'] = split_row[0]
    help_dict['name'] = split_row[1]
    help_dict['surname'] = split_row[2][:-1]
   # [:len(split_row[2]) - 1] is equivalent to [:-1]
   # I assume you are stripping whitespace from the right side,
   # which can also be accomplished using split_row[2].rstrip()

    if split_row[0] in count_of_visits_by_person_id:
        visits = count_of_visits_by_person_id[split_row[0]]
    else:
        visits = 0
    help_dict['visits'] = str(visits)

    return_list.append(help_dict)

</code>```

The generally simpler and safer way to open files is using the with statement. Here is an example:

```<code>with open('visits_file.csv', mode='r') as visits_file:
   row = visits_file.readline()
   while row:
       row = visits_file.readline()  # Skips the first line
       list_of_person_ids.append(row.split(',')[1])
</code>```

Body:
i have a task to do and i got stuck because whatever i do it does't seem to work.

So i have to csv files.
First called persons_file and it contains header line: id, name, surname.
And visits_file containing id, person_id, site.
I have to write a function called merge that gets to files as arguments (both StrionIO type) and returns list of dictionaries with number of visits for each users:

[ {
 "id": (person's id),
 "name": (person's name),
 "surname": (person's surname),
 "visits": (number of visits)
 } ]

I came up with this and i don't know where my mistake is.

import io

def merge(persons_file,visits_file):
    line_counter = 0
    return_list = []
    list_of_person_ids = []
    visits = 0

    for row in visits_file:
        if line_counter == 0:
            line_counter+=1
            continue
        list_of_person_ids.append(row.split(',')[1])

    line_counter = 0

    for row in persons_file:
        if line_counter == 0:
            line_counter+=1
            continue
        help_dict = {}
        split_row = row.split(',')
        help_dict['id'] = split_row[0]
        help_dict['name'] = split_row[1]
        help_dict['surname'] = split_row[2][:len(split_row[2])-1]
        if split_row[0] in list_of_person_ids:
            visits = list_of_person_ids.count(split_row[0])
        help_dict['visits'] = str(visits)
        return_list.append(help_dict)
        visits=0
    return return_list

file1 = open('persons_file.csv' , mode='r')
file2 = open('visits_file.csv' , mode='r')
persons_file_arg = io.StringIO(file1.read())
visits_file_arg = io.StringIO(file2.read())

list_of_visits = merge(persons_file_arg,visits_file_arg)
for i in list_of_visits:
    print(i)
file1.close()
file2.close()

I will be glad if anyone could help me.

Body:
What is the issue? Is it the output that is not what you expected, or are you getting an exception? Your code seems like it should achieve the result you want, but I have a couple suggestions to make that could simplify things.

Look into collections.Counter you could then call count_of_visits_by_person_id = Counter(list_of_person_ids) to get a result of the form:
{person_id: number_of_visits, ...}. You could then use this to simply look up the number of visits in your next for loop. e.g.:

from collections import Counter

...

count_of_visits_by_person_id = Counter(list_of_person_ids)

for row in persons_file:
    if line_counter == 0:
        line_counter += 1
        continue

    help_dict = {}
    split_row = row.split(',')

    help_dict['id'] = split_row[0]
    help_dict['name'] = split_row[1]
    help_dict['surname'] = split_row[2][:-1]
   # [:len(split_row[2]) - 1] is equivalent to [:-1]
   # I assume you are stripping whitespace from the right side,
   # which can also be accomplished using split_row[2].rstrip()

    if split_row[0] in count_of_visits_by_person_id:
        visits = count_of_visits_by_person_id[split_row[0]]
    else:
        visits = 0
    help_dict['visits'] = str(visits)

    return_list.append(help_dict)

The generally simpler and safer way to open files is using the with statement. Here is an example:

with open('visits_file.csv', mode='r') as visits_file:
   row = visits_file.readline()
   while row:
       row = visits_file.readline()  # Skips the first line
       list_of_person_ids.append(row.split(',')[1])


问:
How to emulate float/double/real in Bazel?
Bazel (0.26.0) does not support float types as you can read here.

However, I would like to compute some magic (floating-point) number store them in string as shown here:

```<code>def magicNumber():
    fileStr = ""
    count = 200
    for i in range(0, count-1):
        v = i / count
        fileStr += str(v) + " "

    return fileStr
</code>```

I want to use Bazel-only features to achieve this. It is clear to me that I could also place my computation for instance in batch/shell script, but I want stick to Bazel-only features. Any ideas how to achieve this?

答:
It's unclear why you'd want to do that. Integers should usually be enough.

If what you want is the sequence "0.0 0.005 0.01 0.015 0.02... 0.995", you can do that like this:

def magic():
  fileStr = ""
  for i in range(0, 1000, 5):
    s = ("000" + str(i))[-3:] # Add leading 0s
    fileStr += "0.{} ".format(s.rstrip('0'))
  return fileStr
```

<p>Since the strings are not mutable, <code>+=</code> on a string will copy it. Doing that in a loop is not recommended for performance (quadratic complexity). Instead, you may append data to an array and join it at the end. It's the same result, except that it doesn't have the trailing space:</p>

<pre class="lang-py prettyprint-override"><code>def magic():
  data = []
  for i in range(0, 1000, 5):
    s = ("000" + str(i))[-3:]
    data.append("0." + s.rstrip('0'))
  return " ".join(data)
</code>```

Body:
Bazel (0.26.0) does not support float types as you can read here.

However, I would like to compute some magic (floating-point) number store them in string as shown here:

def magicNumber():
    fileStr = ""
    count = 200
    for i in range(0, count-1):
        v = i / count
        fileStr += str(v) + " "

    return fileStr

I want to use Bazel-only features to achieve this. It is clear to me that I could also place my computation for instance in batch/shell script, but I want stick to Bazel-only features. Any ideas how to achieve this?

Body:
It's unclear why you'd want to do that. Integers should usually be enough.

If what you want is the sequence "0.0 0.005 0.01 0.015 0.02... 0.995", you can do that like this:

def magic():
  fileStr = ""
  for i in range(0, 1000, 5):
    s = ("000" + str(i))[-3:] # Add leading 0s
    fileStr += "0.{} ".format(s.rstrip('0'))
  return fileStr

Since the strings are not mutable, += on a string will copy it. Doing that in a loop is not recommended for performance (quadratic complexity). Instead, you may append data to an array and join it at the end. It's the same result, except that it doesn't have the trailing space:

def magic():
  data = []
  for i in range(0, 1000, 5):
    s = ("000" + str(i))[-3:]
    data.append("0." + s.rstrip('0'))
  return " ".join(data)


问:
tabs/indents blocking code on windows server
I have the following code and it's working great on my local xampp and test linux webhosting:

```<code><?php
// include config file
include('config.php');

// get page intel
$_PAGE = switchPage($_GET);

// require language file
require_once("languages/".$_PAGE['language'].".lang.php");

// include header file
include('includes/header.inc.php');
?>

            <section id="main" class="clearfix">

                <?php
                // include correct page
                include($_PAGE['include_path']);
                ?>

            </section>

<?php
// include footer file
include('includes/footer.inc.php');
?>
</code>```

My client has a windows server with PHP 5.2.6 installed. The hosting company claims that tabs/indents like used in the following snipet out of the code does not work on a windows php hosting.

```<code>            <?php
            // include correct page
            include($_PAGE['include_path']);
            ?>
</code>```

So they claim my code is not valid PHP code.. Can someone advice please? I don't want to rewrite my code just because of all the indents I use to keep my code clean and readable ..

答: It makes no difference if you use tabs or spaces. That's still valid php.</p>

Body:
I have the following code and it's working great on my local xampp and test linux webhosting:

<?php
// include config file
include('config.php');

// get page intel
$_PAGE = switchPage($_GET);

// require language file
require_once("languages/".$_PAGE['language'].".lang.php");

// include header file
include('includes/header.inc.php');
?>

                <?php
                // include correct page
                include($_PAGE['include_path']);
                ?>

<?php
// include footer file
include('includes/footer.inc.php');
?>

My client has a windows server with PHP 5.2.6 installed. The hosting company claims that tabs/indents like used in the following snipet out of the code does not work on a windows php hosting.

            <?php
            // include correct page
            include($_PAGE['include_path']);
            ?>

So they claim my code is not valid PHP code.. Can someone advice please? I don't want to rewrite my code just because of all the indents I use to keep my code clean and readable ..