问:
How to make sure a task is started and safely start it if not?
I get an IEnumerable<Task> tasks from somewhere that I do not control. I don't know if the tasks are manually created using new Task, Task.Run, or if they are a result of an async method call async Task DoSomethingAsync().

If I do await Task.WhenAll(tasks), I risk hanging indefinitely because maybe one or more of the tasks are not started.

I can't do tasks.ForEach(t => t.Start()), because then I will get an InvalidOperationException "Start may not be called on a promise-style task" if it's from an async method call (already started).

I can't do await Task.WhenAll(tasks.Select(t => Task.Run(async () => await t))) because each t still does not start just by awaiting it.

I assume the solution has something to do with checking each task's Status and Start() based on that, but I also assume that it can be tricky because that status could change at any time, right? If this is still the way to go, which statuses would be correct to check and what threading issues should I worry about?

Non working case example:

```<code>//making an IEnumerable as an example, remember I don't control this part
Task t = new Task( () => Console.WriteLine("started"));
IEnumerable<Task> tasks = new[] {t};

//here I receive the tasks
await Task.WhenAll(tasks);//waits forever because t is not started
</code>```

Working case example:

```<code>//calls the async function, starting it.
Task t = DoSomethingAsync();
IEnumerable<Task> tasks = new[] {t};

//here I receive the tasks and it will complete because the task is already started
await Task.WhenAll(tasks);

async Task DoSomethingAsync() => Console.WriteLine("started");
</code>```

答:
If for whatever reason you cannot change the code to not return unstarted tasks, you can check Status and start task if it has Created status:

```<code>if (task.Status == TaskStatus.Created)
   task.Start();
</code>```

All other task statues indicate that task is either completed, running, or being scheduled, so you don't need to start tasks in that statuses.

Of course in theory this introduces race condition, because task can be started right between your check and Start call, but, as correctly pointed by Servy in comments - if there ever is race condition here - that means another party (which created that task) is also trying to start it. Even if you handle exception (InvalidOperationException) - another party is unlikely to do that, and so will get exception while trying to start their own task. So only one side (either you, or code that created that task) should be trying to start it.

That said - much better than doing this is to ensure you might never get unstarted task in the first place, because it's just bad design to return such tasks to external code, at least without explicitly indicating that (while it's for some use cases ok to use unstarted task internally).

Body:
I get an IEnumerable<Task> tasks from somewhere that I do not control. I don't know if the tasks are manually created using new Task, Task.Run, or if they are a result of an async method call async Task DoSomethingAsync().

If I do await Task.WhenAll(tasks), I risk hanging indefinitely because maybe one or more of the tasks are not started.

I can't do tasks.ForEach(t => t.Start()), because then I will get an InvalidOperationException "Start may not be called on a promise-style task" if it's from an async method call (already started).

I can't do await Task.WhenAll(tasks.Select(t => Task.Run(async () => await t))) because each t still does not start just by awaiting it.

I assume the solution has something to do with checking each task's Status and Start() based on that, but I also assume that it can be tricky because that status could change at any time, right? If this is still the way to go, which statuses would be correct to check and what threading issues should I worry about?

Non working case example:

//making an IEnumerable as an example, remember I don't control this part
Task t = new Task( () => Console.WriteLine("started"));
IEnumerable<Task> tasks = new[] {t};

//here I receive the tasks
await Task.WhenAll(tasks);//waits forever because t is not started

Working case example:

//calls the async function, starting it.
Task t = DoSomethingAsync();
IEnumerable<Task> tasks = new[] {t};

//here I receive the tasks and it will complete because the task is already started
await Task.WhenAll(tasks);

async Task DoSomethingAsync() => Console.WriteLine("started");

Body:
If for whatever reason you cannot change the code to not return unstarted tasks, you can check Status and start task if it has Created status:

if (task.Status == TaskStatus.Created)
   task.Start();

All other task statues indicate that task is either completed, running, or being scheduled, so you don't need to start tasks in that statuses.

Of course in theory this introduces race condition, because task can be started right between your check and Start call, but, as correctly pointed by Servy in comments - if there ever is race condition here - that means another party (which created that task) is also trying to start it. Even if you handle exception (InvalidOperationException) - another party is unlikely to do that, and so will get exception while trying to start their own task. So only one side (either you, or code that created that task) should be trying to start it.

That said - much better than doing this is to ensure you might never get unstarted task in the first place, because it's just bad design to return such tasks to external code, at least without explicitly indicating that (while it's for some use cases ok to use unstarted task internally).


来源: stackexchange

问:
Java Generics - method which accept different generic interfaces
Say I have this code:

```<code>IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...
</code>```

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

```<code>void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}
</code>```

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

答:
Elaborating Michael answer this is what I came up.
Seems almost nice ;)

```<code>switch (operation) {
  case TYPE_1:
    processDbOperation(
      dbOperation,
      new MyOperation<Type1>(),
      new MyTotallyDifferentOperation<Type1>());
    break;
  case TYPE_2:
    processDbOperation(
      dbOperation,
      new MyOperation<Type2>(),
      new MyTotallyDifferentOperation<Type2>());
    break;

...

<T> void processDbOperation(final DbOperation dbOperation, final IOperation<T> operation, final ITotallyDifferentOperation<T> totallyDifferentOperation) {
  switch (dbOperation) {
    case DB_TYPE_1:
      myMethod(parameter1, parameter2);
      break;
    case DB_TYPE_2:
      myOtherMethod(parameter1, parameter2);
      break;
}

...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Say I have this code:

IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

Body:
Elaborating Michael answer this is what I came up.
Seems almost nice ;)

switch (operation) {
  case TYPE_1:
    processDbOperation(
      dbOperation,
      new MyOperation<Type1>(),
      new MyTotallyDifferentOperation<Type1>());
    break;
  case TYPE_2:
    processDbOperation(
      dbOperation,
      new MyOperation<Type2>(),
      new MyTotallyDifferentOperation<Type2>());
    break;

...

<T> void processDbOperation(final DbOperation dbOperation, final IOperation<T> operation, final ITotallyDifferentOperation<T> totallyDifferentOperation) {
  switch (dbOperation) {
    case DB_TYPE_1:
      myMethod(parameter1, parameter2);
      break;
    case DB_TYPE_2:
      myOtherMethod(parameter1, parameter2);
      break;
}

...


问:
ASP.NET - IIS 7 - DotNetNuke - How do I force browsers to reload the site's CSS?
I have run into the problem where my css files are being cached in browsers. This is a fairly common problem, and a common solution is to simple add a version number in the url to the css file. Example: MyCSS.css?ver=1.12

However, I'm using a custom skin for DotNetNuke which forces the usage of the file: skin.css

I don't have a way to point browsers to skin.css?ver=1.12 (or at least I'm not aware of a way)

Are there any tricks I can play with IIS, DNN, or ASP.NET (default.aspx file for DNN perhaps?) to force clients to reload CSS?

答:
When the skin is created "correctly" the skin.css file should (in DNN 6+ I think) include a version QS parameter when it's loaded.
The version number is upped when you install a new skin version or you can do this through Host > Host (application) settings > Advanced settings > Client Resource Management > [Increment Version]</p>


问:
$browser->resize(INT, INT); no longer works for me?
I am currently learning my way around laravel dusk. All of my test were working yesterday, today i get the following error and a blank screenshot.

```<code>1) Tests\Browser\NewTest::testExample
Facebook\WebDriver\Exception\UnrecognizedExceptionException: disconnected: unable to connect to renderer
  (Session info: headless chrome=62.0.3202.94)
  (Driver info: chromedriver=2.32.498537 (cb2f855cbc7b82e20387eaf9a43f6b99b6105061),platform=Mac OS X 10.12.6 x86_64)
</code>```

I assume that my chrome may have updated since and no longer plays nice with ChromeDrivers.

Anyone else experiencing anything similar?

Thanks.

答:
The problem may be that you need to upgrade to chromedriver 2.33 (your error message shows that you were using chromedriver 2.32).

If you reference this github issue, you will see that a user has solved the problem by inserting the following into composer.json:

"post-install-cmd": [
  "cp -f drivers/* vendor/laravel/dusk/bin"
]

Otherwise, you could temporarily solve the problem by putting the chromedriver 2.33 executable file directly into vendor\laravel\dusk\bin and changing its file name to the file name appropriate for your operating system (since you appear to be using MacOS, this filename should be: chromedriver-mac).

ContentLicense: CC BY-SA 4.0

Body:
I am currently learning my way around laravel dusk. All of my test were working yesterday, today i get the following error and a blank screenshot.

1) Tests\Browser\NewTest::testExample
Facebook\WebDriver\Exception\UnrecognizedExceptionException: disconnected: unable to connect to renderer
  (Session info: headless chrome=62.0.3202.94)
  (Driver info: chromedriver=2.32.498537 (cb2f855cbc7b82e20387eaf9a43f6b99b6105061),platform=Mac OS X 10.12.6 x86_64)

I assume that my chrome may have updated since and no longer plays nice with ChromeDrivers.

Anyone else experiencing anything similar?

Thanks.


问:
Android BottomSheetBehavior callback method onSlide() gives confusing slideOffset values
I am implementing an application where I use a bottom sheet with the behavior defined by @string/bottom_sheet_behavior. Additionally I set a BottomSheetBehavior.BottomSheetCallback() programmatically because I want to use the onSlide() method to animate a padding. Therefore I really need the slideOffset value to calculate the new padding to set.
I read the  docs. There they say that the value ranges from -1 to 0 when the state is between hidden and collapsed state. I only can see this behavior when my phone or tablet is in portrait mode and is independent of the android version. However in landscape mode the range goes all from 1 to -1.
In detail here is a value history of a bottom sheet going from hidden to expand:

```<code>D/SLIDE: -0.86160713
D/SLIDE: -0.5714286
D/SLIDE: -0.29910713
D/SLIDE: -0.0625
D/SLIDE: 0.11382114
D/SLIDE: 0.27235773
D/SLIDE: 0.40650406
D/SLIDE: 0.51626015
D/SLIDE: 0.6300813
D/SLIDE: 0.69512194
D/SLIDE: 0.75609756
D/SLIDE: 0.8130081
D/SLIDE: 0.8577236
D/SLIDE: 0.8943089
D/SLIDE: 0.9186992
D/SLIDE: 0.9430894
D/SLIDE: 0.9593496
D/SLIDE: 0.97154474
D/SLIDE: 0.9796748
D/SLIDE: 0.9878049
D/SLIDE: 0.9918699
D/SLIDE: 0.99593496
D/SLIDE: 1.0
</code>```

I only set the new state of the bottom sheet on a button click.
The desired values would begin on -1 and end on 0.0 with more granular steps between. In this history the values increase as well but they go up to +1.

Does anybody else had to face the same strange behavior and can give me a hint what I am missing?

If any additional code is required I will update my question.

Thanks in advance.

Peter

答:
I had the same problem as you, I can not say the problem is fixed because the onSlide method of the BottomSheetBehavior.BottomSheetCallback() is not behaving according to the documentation (values from -1 to 1), but at least I was able to standardize it by setting the peak height to 0, like this:

bottomSheetBehavior.setPeekHeight(0);

After adding this line, I saw that onSlide method always had positive values (0 - 1).

I'm still trying to understand what is happening in order to find a better solution.

Body:
I am implementing an application where I use a bottom sheet with the behavior defined by @string/bottom_sheet_behavior. Additionally I set a BottomSheetBehavior.BottomSheetCallback() programmatically because I want to use the onSlide() method to animate a padding. Therefore I really need the slideOffset value to calculate the new padding to set.
I read the  docs. There they say that the value ranges from -1 to 0 when the state is between hidden and collapsed state. I only can see this behavior when my phone or tablet is in portrait mode and is independent of the android version. However in landscape mode the range goes all from 1 to -1.
In detail here is a value history of a bottom sheet going from hidden to expand:

D/SLIDE: -0.86160713
D/SLIDE: -0.5714286
D/SLIDE: -0.29910713
D/SLIDE: -0.0625
D/SLIDE: 0.11382114
D/SLIDE: 0.27235773
D/SLIDE: 0.40650406
D/SLIDE: 0.51626015
D/SLIDE: 0.6300813
D/SLIDE: 0.69512194
D/SLIDE: 0.75609756
D/SLIDE: 0.8130081
D/SLIDE: 0.8577236
D/SLIDE: 0.8943089
D/SLIDE: 0.9186992
D/SLIDE: 0.9430894
D/SLIDE: 0.9593496
D/SLIDE: 0.97154474
D/SLIDE: 0.9796748
D/SLIDE: 0.9878049
D/SLIDE: 0.9918699
D/SLIDE: 0.99593496
D/SLIDE: 1.0

I only set the new state of the bottom sheet on a button click.
The desired values would begin on -1 and end on 0.0 with more granular steps between. In this history the values increase as well but they go up to +1.

Does anybody else had to face the same strange behavior and can give me a hint what I am missing?

If any additional code is required I will update my question.

Thanks in advance.

Peter


问:
Encoding problem in aspx/html files
I am developing a website in ASP.NET. I am facing a problem while I am trying to read the values from an .aspx page(using jsonp). I tried seeing this problem using Firebug and it was showing an error in one of my html files. Here's the screenshot: http://i.stack.imgur.com/GlQjC.jpg

I checked the respective html file and it was correct (according to me) except that I remember Visual Studio giving me some prompt regarding some encoding after which I saved the file. This was probably because this html file came from a Linux system. Here's my html file: http://pastebin.com/V3f6KDSa

Can there be such a problem because I then checked in Google Chrome too and it was giving an error as shown in this screenshot: http://i.stack.imgur.com/h67Me.jpg

I didn't see any error in this html file. I am guessing this encoding might be the error but there could some other problem too. I am trying to read the output of a menu.aspx using getJSON.
The output on my menu.aspx page is something like:

foo({"1":"Jeff","2":"Mic","5":"Mark"}); in html form using this .cs code

```<code>outputText += Convert.ToString(k.GetValue(0));
            for (Int32 i = 1; i < k.Length; i++)
            {
                outputText += "," + Convert.ToString(k.GetValue(i));
            }
            //
            outputText += "}" +");";

            Response.Write(outputText);
</code>```

Please suggest something to resolve this.

答:
Do a Response.Clear before writing anything to the output stream:

```<code>Response.Clear();
Response.Write(outputText);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Encoding problem in aspx/html files

Body:
I am developing a website in ASP.NET. I am facing a problem while I am trying to read the values from an .aspx page(using jsonp). I tried seeing this problem using Firebug and it was showing an error in one of my html files. Here's the screenshot: http://i.stack.imgur.com/GlQjC.jpg

I checked the respective html file and it was correct (according to me) except that I remember Visual Studio giving me some prompt regarding some encoding after which I saved the file. This was probably because this html file came from a Linux system. Here's my html file: http://pastebin.com/V3f6KDSa

Can there be such a problem because I then checked in Google Chrome too and it was giving an error as shown in this screenshot: http://i.stack.imgur.com/h67Me.jpg

I didn't see any error in this html file. I am guessing this encoding might be the error but there could some other problem too. I am trying to read the output of a menu.aspx using getJSON.
The output on my menu.aspx page is something like:

foo({"1":"Jeff","2":"Mic","5":"Mark"}); in html form using this .cs code

outputText += Convert.ToString(k.GetValue(0));
            for (Int32 i = 1; i < k.Length; i++)
            {
                outputText += "," + Convert.ToString(k.GetValue(i));
            }
            //
            outputText += "}" +");";

            Response.Write(outputText);

Please suggest something to resolve this.

Body:
Do a Response.Clear before writing anything to the output stream:

Response.Clear();
Response.Write(outputText);


问:
Getting the sum of total balance in C#
I need to calculate the total amount. I have a sales invoice that looks like

How can I add up the amounts to display it in the total sales?

```<code>int orderNo = 234;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] {
                    new DataColumn("QUANTITY", typeof(string)),
                    new DataColumn("UNIT", typeof(string)),
                    new DataColumn("DESCRIPTION", typeof(string)),
                    new DataColumn("UNIT PRICE", typeof(string)),
                    new DataColumn("AMOUNT", typeof(string))});

while (dr.Read()) {
    finalam = dr.GetDouble(0);
    quantity = dr.GetInt32(1);
    unit = dr.GetString(2);
    description = dr.GetString(3);
    unitpr = dr.GetDouble(4);
    dt.Rows.Add(quantity, unit, description, unitpr, totalam);
    double sum = 0.0;
    Session["FinalAmount"]= sum += finalam;
}
 foreach (DataColumn column in dt.Columns)
            {
                sb.Append("<th size='small' align='center'><b>");
                sb.Append(column.ColumnName);
                sb.Append("</th></b>");
            }
</code>```

答:
Let the database calculate the sum (using SQL SUM method), this is much faster than first pulling all rows into memory and then looping over them.

```<code>try {
    dbconnection.Open();

    SqlDataReader myReader = null;

    SqlCommand cmd = new SqlCommand(
        "SELECT SUM(AMOUNT) AS FinalAmount FROM [ordersTable] WHERE orderNo = @orderNo ",
        con
    );
    cmd.Parameters.Add(new SqlParameter("@orderNo", orderNo ));

    myReader = cmd.ExecuteReader();
    while (myReader.Read()) {
        Session["FinalAmount"]= (myReader["FinalAmount"]);
    }

    dbconnection.Close();
}
catch (Exception ex) {
    _logger.Error(ex);
}
</code>```

Title: Getting the sum of total balance in C#

Body:
I need to calculate the total amount. I have a sales invoice that looks like

How can I add up the amounts to display it in the total sales?

int orderNo = 234;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] {
                    new DataColumn("QUANTITY", typeof(string)),
                    new DataColumn("UNIT", typeof(string)),
                    new DataColumn("DESCRIPTION", typeof(string)),
                    new DataColumn("UNIT PRICE", typeof(string)),
                    new DataColumn("AMOUNT", typeof(string))});

while (dr.Read()) {
    finalam = dr.GetDouble(0);
    quantity = dr.GetInt32(1);
    unit = dr.GetString(2);
    description = dr.GetString(3);
    unitpr = dr.GetDouble(4);
    dt.Rows.Add(quantity, unit, description, unitpr, totalam);
    double sum = 0.0;
    Session["FinalAmount"]= sum += finalam;
}
 foreach (DataColumn column in dt.Columns)
            {
                sb.Append("");
                sb.Append(column.ColumnName);
                sb.Append("	");
            }

Body:
Let the database calculate the sum (using SQL SUM method), this is much faster than first pulling all rows into memory and then looping over them.

try {
    dbconnection.Open();

    SqlDataReader myReader = null;

    SqlCommand cmd = new SqlCommand(
        "SELECT SUM(AMOUNT) AS FinalAmount FROM [ordersTable] WHERE orderNo = @orderNo ",
        con
    );
    cmd.Parameters.Add(new SqlParameter("@orderNo", orderNo ));

    myReader = cmd.ExecuteReader();
    while (myReader.Read()) {
        Session["FinalAmount"]= (myReader["FinalAmount"]);
    }

    dbconnection.Close();
}
catch (Exception ex) {
    _logger.Error(ex);
}


问:
pip install returning invalid syntax
I've just installed python 3.6 which comes with pip

However, in Windows command prompt, when I do: 'pip install bs4' it returns 'SyntaxError: invalid syntax' under the install word.

Typing 'python' returns the version, which means it is installed correctly. What could be the problem?

答:
In windows, you have to run pip install command from( python path)/ scripts path in cmd prompt

C:/python27/scripts

pip install pandas

Title: pip install returning invalid syntax


问:
Webpack - webpack-dev-server two configs
I have a project, which consists of two parts.. an admin environment and a part of web for regular users. Each part has another assets, so I have two configurations for webpack. First is named webpack-front.config.js and second is named webpack-admin.config.js.

My structure:

```<code>├─┬ dist
│ ├── front.bundle.js
│ └── admin.bundle.js
|
├─┬ src
│ ├─┬ front
| | └── index.js
│ └─┬ admin
|   └── index.js
</code>```

Problem starts, when I try to run "webpack-dev-server --open". Npm prints:

```<code>> webpack-dev-server --open

No configuration file found and no entry configured via CLI option.
When using the CLI you need to provide at least two arguments: entry and output.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.
npm ERR! code ELIFECYCLE
npm ERR! errno 255
npm ERR! www@1.0.0 start: `webpack-dev-server --open`
npm ERR! Exit status 255
npm ERR!
npm ERR! Failed at the www@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-04T14_16_35_084Z-debug.log
</code>```

This problem occurs because my configs are not named "webpack.config.js". Is there any way, how to run webpack-dev-server with another config or with both configs at once?

答:
You can use the config option to specify your custom config file. </p>

```<code>> webpack-dev-server --config /home/user/project/path_to_config_file
</code>```

Body:
I have a project, which consists of two parts.. an admin environment and a part of web for regular users. Each part has another assets, so I have two configurations for webpack. First is named webpack-front.config.js and second is named webpack-admin.config.js.

My structure:

├─┬ dist
│ ├── front.bundle.js
│ └── admin.bundle.js
|
├─┬ src
│ ├─┬ front
| | └── index.js
│ └─┬ admin
|   └── index.js

Problem starts, when I try to run "webpack-dev-server --open". Npm prints:

> webpack-dev-server --open

No configuration file found and no entry configured via CLI option.
When using the CLI you need to provide at least two arguments: entry and output.
A configuration file could be named 'webpack.config.js' in the current directory.
Use --help to display the CLI options.
npm ERR! code ELIFECYCLE
npm ERR! errno 255
npm ERR! www@1.0.0 start: `webpack-dev-server --open`
npm ERR! Exit status 255
npm ERR!
npm ERR! Failed at the www@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-04T14_16_35_084Z-debug.log

This problem occurs because my configs are not named "webpack.config.js". Is there any way, how to run webpack-dev-server with another config or with both configs at once?

Body:
You can use the config option to specify your custom config file.

> webpack-dev-server --config /home/user/project/path_to_config_file


问:
Giving error on first load
Having problem on first load but when i refresh the page it seems okay. Is it problem with firebase database plugin loading?
How to get rid of this issue?

答:
You just need declare it like this:</p>

```<code>pays : any = [];
</code>```

Title: Giving error on first load

Body:
You just need declare it like this:

pays : any = [];


问:
Message contract wrappername and message body name attribute does not work
I have couple of classes which define as message contract and properties define as message body. I specified wrappername and name attribute respectively. It works for parent class but does not work for child class.

Classes:

```<code>[MessageContract(WrapperName = "ticketstatus",IsWrapped = true)]
public class TicketStatusResponse
{

    [MessageBodyMember(Name="status")]
    public string Status { get; set; }

    [MessageBodyMember(Name="errorcode")]
    public string ErrorCode { get; set; }

    [MessageBodyMember(Name="errormessage")]
    public string ErrorMessage { get; set; }

    [MessageBodyMember(Name="tasks")]
    public List<Task> Tasks { get; set; }
}

[MessageContract(WrapperName="task")]
public class Task
{
    [MessageBodyMember(Name="taskname")]
    public string TaskName { get; set; }

    [MessageBodyMember(Name="complete")]
    public string Complete { get; set; }
}
</code>```

Response info:

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
  <ticketstatus xmlns="http://tempuri.org/">
     <errorcode>0</errorcode>
     <errormessage/>
     <status>Pending</status>
     <tasks xmlns:a="http://schemas.datacontract.org/2004/07/MessageContractExample.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:Task>
           <a:Complete>1</a:Complete>
           <a:TaskName>task1</a:TaskName>
        </a:Task>
        <a:Task>
           <a:Complete>2</a:Complete>
           <a:TaskName>task2</a:TaskName>
        </a:Task>
     </tasks>
     <ticketno>567890</ticketno>
     <waittime>4</waittime>
  </ticketstatus>
</s:Body>
</s:Envelope>
</code>```

My expected xml tag name of "Task" should be as follows because I change name using wrappername and name attribute:

```<code>        <a:task>
           <a:complete>2</a:complete>
           <a:taskname>task2</a:taskName>
        </a:task>
</code>```

But i am getting

```<code>       <a:Task>
           <a:Complete>1</a:Complete>
           <a:TaskName>task1</a:TaskName>
        </a:Task>
</code>```

Why wrapper name and name attribute do not work for child node. How can I fix node name?

Any idea or hints?

答: Have you considered IsWrapped = true as that is the difference between the classes.

Body:
I have couple of classes which define as message contract and properties define as message body. I specified wrappername and name attribute respectively. It works for parent class but does not work for child class.

Classes:

[MessageContract(WrapperName = "ticketstatus",IsWrapped = true)]
public class TicketStatusResponse
{

    [MessageBodyMember(Name="status")]
    public string Status { get; set; }

    [MessageBodyMember(Name="errorcode")]
    public string ErrorCode { get; set; }

    [MessageBodyMember(Name="errormessage")]
    public string ErrorMessage { get; set; }

    [MessageBodyMember(Name="tasks")]
    public List<Task> Tasks { get; set; }
}

[MessageContract(WrapperName="task")]
public class Task
{
    [MessageBodyMember(Name="taskname")]
    public string TaskName { get; set; }

    [MessageBodyMember(Name="complete")]
    public string Complete { get; set; }
}

Response info:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
  <ticketstatus xmlns="http://tempuri.org/">
     <errorcode>0</errorcode>
     <errormessage/>
     <status>Pending</status>
     <tasks xmlns:a="http://schemas.datacontract.org/2004/07/MessageContractExample.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

           1
           task1

           2
           task2

     </tasks>
     <ticketno>567890</ticketno>
     <waittime>4</waittime>
  </ticketstatus>
</s:Body>
</s:Envelope>

My expected xml tag name of "Task" should be as follows because I change name using wrappername and name attribute:

           2
           task2

But i am getting

           1
           task1

Why wrapper name and name attribute do not work for child node. How can I fix node name?

Any idea or hints?


问:
SQL left join multiple product id's
I have a SQL table and need to join some data.  In table 2 there a multiple product ID's some with the but with differnt dates.

eg

```<code>Table 1 (Master)
Product
</code>```

left join

Table 2

```<code>Product | Date 1
AA      | 01/01/2018
AA      | 01/02/2018
AB      | 01/01/2018
AC      | 01/01/2018
AC      | 01/02/2018
</code>```

What im looking for is to have the data looking like:

```<code>Product | Date 1     | Date 2
AA      | 01/01/2018 | 01/02/2018
AB      | 01/01/2018
AC      | 01/01/2018 | 01/02/2018
</code>```

Any suggestions would be a great help.

Thank you

Chris

答:
You can try something like the following query:

SELECT t1.Product,
       MIN(Date) AS Date1,
       CASE WHEN COUNT(*) > 1 THEN MAX(Date) END AS Date2
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.Product = t2.Product
GROUP BY t1.Product
```

The query uses a LEFT JOIN to get the correlated records from Table2 Hence, Date1 and Date2 are going to be NULL in case there is no relevant record. Date2 is set only if Product has at least two correlated records.

Demo here

Title: SQL left join multiple product id's

Body:
I have a SQL table and need to join some data.  In table 2 there a multiple product ID's some with the but with differnt dates.

eg

Table 1 (Master)
Product

left join

Table 2

Product | Date 1
AA      | 01/01/2018
AA      | 01/02/2018
AB      | 01/01/2018
AC      | 01/01/2018
AC      | 01/02/2018

What im looking for is to have the data looking like:

Product | Date 1     | Date 2
AA      | 01/01/2018 | 01/02/2018
AB      | 01/01/2018
AC      | 01/01/2018 | 01/02/2018

Any suggestions would be a great help.

Thank you

Chris

Body:
You can try something like the following query:

SELECT t1.Product,
       MIN(Date) AS Date1,
       CASE WHEN COUNT(*) > 1 THEN MAX(Date) END AS Date2
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 ON t1.Product = t2.Product
GROUP BY t1.Product

The query uses a LEFT JOIN to get the correlated records from Table2 Hence, Date1 and Date2 are going to be NULL in case there is no relevant record. Date2 is set only if Product has at least two correlated records.

Demo here


问:
Eclipse shows error if variable declare in .js file by let
I am using eclipse Luna Release (4.4.0), but it throw's an error when i declare varibale in .js file by let but fine with var

```<code>let x =10; it throw's an error
</code>```

syntax error on token

but var x = 10; is fine.

答:
are you using the  "use strict" ?

Also are you removing the eclipse validations?

Body:
I am using eclipse Luna Release (4.4.0), but it throw's an error when i declare varibale in .js file by let but fine with var

let x =10; it throw's an error

syntax error on token

but var x = 10; is fine.


问:
sudo: a password is required ansible-playbook
I have an ansible playbook which installs docker. It looks like this:

```<code>---
- hosts: local
  connection: local
  become: yes
  become_user: root
  tasks:
    - name: add docker's key
      apt_key:
        keyserver: hkp://p80.pool.sks-keyservers.net:80
        id: 58118E89F3A912897C070ADBF76221572C52609D

    - name: add deb repo
      file: path=/etc/apt/sources.list.d/docker.list state=touch

    - name: register apt sources
      lineinfile: dest="/etc/apt/sources.list.d/docker.list" line="{{item}}"
      with_items:
      - "deb https://apt.dockerproject.org/repo ubuntu-trusty main"

    - name: install docker-engine
      apt: name=docker-engine state=present update-cache=yes force=yes
</code>```

The problem is that when I run this playbook on my localhost I get an error:

```<code>fatal: [127.0.0.1]: FAILED! => {"changed": false, "module_stderr": "sudo: a password is required\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}
</code>```

So what parts of this playbook may cause such an error and how can I change them?

答: Try to use <code>--ask-become-pass</code> with your command line. You should then be prompted for the password. </p>

Body:
I have an ansible playbook which installs docker. It looks like this:

---
- hosts: local
  connection: local
  become: yes
  become_user: root
  tasks:
    - name: add docker's key
      apt_key:
        keyserver: hkp://p80.pool.sks-keyservers.net:80
        id: 58118E89F3A912897C070ADBF76221572C52609D

    - name: add deb repo
      file: path=/etc/apt/sources.list.d/docker.list state=touch

    - name: register apt sources
      lineinfile: dest="/etc/apt/sources.list.d/docker.list" line="{{item}}"
      with_items:
      - "deb https://apt.dockerproject.org/repo ubuntu-trusty main"

    - name: install docker-engine
      apt: name=docker-engine state=present update-cache=yes force=yes

The problem is that when I run this playbook on my localhost I get an error:

fatal: [127.0.0.1]: FAILED! => {"changed": false, "module_stderr": "sudo: a password is required\n", "module_stdout": "", "msg": "MODULE FAILURE", "rc": 1}

So what parts of this playbook may cause such an error and how can I change them?

Body: Try to use --ask-become-pass with your command line. You should then be prompted for the password.


问:
create relation when node exist else create a new node
I have 2 types of node staff and client where staff has
StaffList

```<code>{
  "name": "vipul",
  "cprNumber": 121
}
,{
  "name": "amit",
  "cprNumber": 123
}
</code>```

ClientList

```<code>{
  "property1": "pptVal",
  "cprNumber": 121
}
</code>```

now I want to create a relationship between these 2 nodes like in the first case the CPR number is matched so a relationship creates "BELONGS_TO" for vipul, but since no, any node exists for amit's cpr number so a new node needs to be created and a relationship to be created.

答:
I think you can achieve your goal using MERGE:</p>

```<code>// Match Vipul and Amit nodes
MATCH (a:Client)
// Match :ClientList node when it has cprNumber = a.cprNumber.
// When no node is matched, create it.
MERGE (b:ClientList {cprNumber : a.cprNumber})
// Create :BELONGS_TO relationship
CREATE (a)-[:BELONGS_TO]->(b)
</code>```

Body:
I have 2 types of node staff and client where staff has
StaffList

{
  "name": "vipul",
  "cprNumber": 121
}
,{
  "name": "amit",
  "cprNumber": 123
}

ClientList

{
  "property1": "pptVal",
  "cprNumber": 121
}

now I want to create a relationship between these 2 nodes like in the first case the CPR number is matched so a relationship creates "BELONGS_TO" for vipul, but since no, any node exists for amit's cpr number so a new node needs to be created and a relationship to be created.

Body:
I think you can achieve your goal using MERGE:

// Match Vipul and Amit nodes
MATCH (a:Client)
// Match :ClientList node when it has cprNumber = a.cprNumber.
// When no node is matched, create it.
MERGE (b:ClientList {cprNumber : a.cprNumber})
// Create :BELONGS_TO relationship
CREATE (a)-[:BELONGS_TO]->(b)


问:
Extracting data from a Rhapsody Table View using Rational Publishing Engine
I am producing a document using Rational Publishing Engine which need to extract information from Rhapsody. I looked into several sources of information about their integration (e.g. http://www-01.ibm.com/support/docview.wss?uid=swg27035704&aid=1), but it's not clear to me how to extract data from Rhapsody's Table View. I know that is possible to obtain an image of the table, but I need to access structured data.

I managed to extract all of the other information I need, but I am not able to identify which of the child node of the TableView rhapsody data source in RPE represents the elements of the table, or if such a node exist.

Is this operation possible?

答:
no, you can iterate over the Table Views you have and then print each cell with the columns available in that View (which are defined by a given Table Layout).

So you could end up creating specific Layouts in RPE for each table layout you have... to avoid this, you could use "DataAsXML" which does all for you and allows you to have a generic template. Look for examples here: http://merlinscave.info/Merlins_Cave/Models/Entries/2017/5/26_RPE_Templates_for_Reporting_on_Harmony_Models.html


问:
Rotating a drawable in Android
How can a Drawable loaded from a resource be rotated when it is drawn? For example, I would like to draw an arrow and be able to rotate it to face in different directions when it is drawn?

答:
essentially this:

```<code>ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage);
Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
spaceshipImage.startAnimation(hyperspaceJumpAnimation);
</code>```

source link:

http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation

Title: Rotating a drawable in Android

Body:
essentially this:

ImageView spaceshipImage = (ImageView) findViewById(R.id.spaceshipImage);
Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
spaceshipImage.startAnimation(hyperspaceJumpAnimation);

source link:

http://developer.android.com/guide/topics/graphics/2d-graphics.html#tween-animation


问:
Fetch data with Vue from Web API
I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.

Here is my code:

```<code>const v = new Vue({
    el: '#divContent',
    ready: function () {
        this.loadData();
    },
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData: function (viewerUserId, posterUserId) {
            const that = this;
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "Post",
                success: function (response) {
                    that.$data.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    }
});
</code>```

My HTML

```<code><div id="divContent" class="content">
 {{ content }}
</div>
</code>```

答:
You appear to already be using jQuery, so to load the Vue when the page is loaded you can update your code to the following:

```<code>$(function(){
  const v = new Vue({
    el: '#divContent',
    created: function () {
      this.loadData();
    },
    data: {
      content: 'loading',
      serverData: null
    },
    methods: {
      loadData: function (viewerUserId, posterUserId) {
        const that = this;
        $.ajax({
          contentType: "application/json",
          dataType: "json",
          url: "http://my-webapi/",
          method: "Post",
          success: response => this.serverData = response,
          error: err => alert('Error')
        });
      }
    }
  });
})
</code>```

The syntax above is using the jQuery.ready shorthand to create the Vue only after the page is loaded.

Without jQuery, you might want to listen for the DOMContentLoaded event.

Alternatively, just load the script that creates the Vue at the bottom of the page and not in the header.

Here is a complete, working example.

console.clear()

$(function(){
  const v = new Vue({
    el: '#divContent',
    created: function () {
      this.loadData();
    },
    data: {
      content: 'loading',
      serverData: null
    },
    methods: {
      loadData: function (viewerUserId, posterUserId) {
        $.ajax({
          contentType: "application/json",
          dataType: "json",
          url: "https://httpbin.org/post",
          data: JSON.stringify({testing: "some value"}),
          method: "Post",
          success: response => {
            this.content = "loaded"
            this.serverData = response.json
          },
          error: err => console.log('Error')
        });
      }
    }
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="divContent" class="content">
  {{ content }}
  <hr>
  Response: <br>
  {{ serverData }}
</div></code>```

Title: Fetch data with Vue from Web API

Body:
I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.

Here is my code:

const v = new Vue({
    el: '#divContent',
    ready: function () {
        this.loadData();
    },
    data: {
        content: 'loading',
        serverData: null
    },
    methods: {
        loadData: function (viewerUserId, posterUserId) {
            const that = this;
            $.ajax({
                contentType: "application/json",
                dataType: "json",
                url: "http://my-webapi/",
                method: "Post",
                success: function (response) {
                    that.$data.serverData = response;

                },
                error: function () {
                    alert('Error')
                }
            });
        }
    }
});

My HTML

 {{ content }}

Body:
You appear to already be using jQuery, so to load the Vue when the page is loaded you can update your code to the following:

$(function(){
  const v = new Vue({
    el: '#divContent',
    created: function () {
      this.loadData();
    },
    data: {
      content: 'loading',
      serverData: null
    },
    methods: {
      loadData: function (viewerUserId, posterUserId) {
        const that = this;
        $.ajax({
          contentType: "application/json",
          dataType: "json",
          url: "http://my-webapi/",
          method: "Post",
          success: response => this.serverData = response,
          error: err => alert('Error')
        });
      }
    }
  });
})

The syntax above is using the jQuery.ready shorthand to create the Vue only after the page is loaded.

Without jQuery, you might want to listen for the DOMContentLoaded event.

Alternatively, just load the script that creates the Vue at the bottom of the page and not in the header.

Here is a complete, working example.

console.clear()

$(function(){
  const v = new Vue({
    el: '#divContent',
    created: function () {
      this.loadData();
    },
    data: {
      content: 'loading',
      serverData: null
    },
    methods: {
      loadData: function (viewerUserId, posterUserId) {
        $.ajax({
          contentType: "application/json",
          dataType: "json",
          url: "https://httpbin.org/post",
          data: JSON.stringify({testing: "some value"}),
          method: "Post",
          success: response => {
            this.content = "loaded"
            this.serverData = response.json
          },
          error: err => console.log('Error')
        });
      }
    }
  });
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="divContent" class="content">
  {{ content }}
  <hr>
  Response: <br>
  {{ serverData }}
</div>


问:
Gremlin : Add multiple vertices in single gremlin query?
I am using Titan 0.4 + Cassandra.
My use-case requires insert multiple vertices at a time.
(aprrox batch size is 100 vertices at a time.)
eg :

```<code>v01 = g.addVertex(["UC":"B","i":2]); v02 = g.addVertex(["UC":"H","i":1])
v03 = g.addVertex(["LC":"a"]); v04 = g.addVertex(["LC":"a"]);
v05 = g.addVertex(["LC":"d"]); v06 = g.addVertex(["LC":"h"]);
v07 = g.addVertex(["LC":"i"]); v08 = g.addVertex(["LC":"p"]);
</code>```

Is there any gremlin command to add all Eight vertices in a single request. ( something like  g.addVertices() ?? )

答:
I had the requirement to add several vertices at the same time too. Individual addV queries weren't practical for inserting thousands of record at a time, while also retrieving their database generated ids.

Here's what I came up with as a batch insertion command/query

```<code>g.addV('One').values('id').as('one').addV('Two').values('id').as('two').select('one', 'two')
</code>```

CosmosDB returns

```<code>[{
   "one": "372be552-7f63-4d7b-be81-a73d5d677afa",
   "two": "a60d3773-5c29-454e-b079-dec734c4f431"
}]
</code>```

Body:
I am using Titan 0.4 + Cassandra.
My use-case requires insert multiple vertices at a time.
(aprrox batch size is 100 vertices at a time.)
eg :

v01 = g.addVertex(["UC":"B","i":2]); v02 = g.addVertex(["UC":"H","i":1])
v03 = g.addVertex(["LC":"a"]); v04 = g.addVertex(["LC":"a"]);
v05 = g.addVertex(["LC":"d"]); v06 = g.addVertex(["LC":"h"]);
v07 = g.addVertex(["LC":"i"]); v08 = g.addVertex(["LC":"p"]);

Is there any gremlin command to add all Eight vertices in a single request. ( something like  g.addVertices() ?? )

Body:
I had the requirement to add several vertices at the same time too. Individual addV queries weren't practical for inserting thousands of record at a time, while also retrieving their database generated ids.

Here's what I came up with as a batch insertion command/query

g.addV('One').values('id').as('one').addV('Two').values('id').as('two').select('one', 'two')

CosmosDB returns

[{
   "one": "372be552-7f63-4d7b-be81-a73d5d677afa",
   "two": "a60d3773-5c29-454e-b079-dec734c4f431"
}]


问:
Cannot create ECS Service via CloudFormation
I create the following CloudFormation template files to create ECS Cluster and TaskDefinition, Service but got an error.
What's wrong these settings?

When create ECS Service using the following templates, got Please verify that the ECS service role being passed has the proper permissions

When create the templates without a property Role: !ImportValue "IAMRoleECSService" , does not occur errors, but does not finish from CREATE_IN_PROGRESS

```<code>ECSApplicationService:
  Type: "AWS::ECS::Service"
  DependsOn:
    - "ECSApplicationCluster"
    - "ECSApplicationTaskDefinition"
  Properties:
    Cluster: !Ref "ECSApplicationCluster"
    DeploymentConfiguration:
      MaximumPercent: 100
      MinimumHealthyPercent: 50
    DesiredCount: 4
    LoadBalancers:
      - ContainerName: !Ref "ContainerAppName"
        ContainerPort: 80
        TargetGroupArn: !ImportValue "ALBTargetGroup"
    Role: !ImportValue "IAMRoleECSService"
    ServiceName: "ecs-application-service"
    TaskDefinition: !Ref "ECSApplicationTaskDefinition"

IAMRoleECSService:
  Type: "AWS::IAM::Role"
  Properties:
    RoleName: "ecs-service"
    AssumeRolePolicyDocument:
      Version: "2012-10-17"
      Statement:
        - Effect: "Allow"
          Principal:
            Service:
              - "ecs.amazonaws.com"
          Action:
            - "sts:AssumeRole"
    Policies:
      - PolicyName: "ec2-management"
        PolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: "Allow"
              Action:
                - "ec2:AuthorizeSecurityGroupIngress"
                - "ec2:Describe*"
              Resource: "*"
      - PolicyName: "alb-management"
        PolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: "Allow"
              Action:
                - "elasticloadbalancing:DeregisterInstancesFromLoadBalancer"
                - "elasticloadbalancing:DeregisterTargets"
                - "elasticloadbalancing:DescribeTargetGroups"
                - "elasticloadbalancing:DescribeTargetHealth"
                - "elasticloadbalancing:Describe*"
                - "elasticloadbalancing:RegisterInstancesWithLoadBalancer"
                - "elasticloadbalancing:RegisterTargets"
              Resource: "*"
</code>```

What should I do?

答:
UPDATE:
As of July 19th 2018, it is now possible to create a IAM Service-Linked Roles using CloudFormation https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-servicelinkedrole.html.

```<code>   EcsServiceLinkedRole:
    Type: "AWS::IAM::ServiceLinkedRole"
    Properties:
      AWSServiceName: "ecs.amazonaws.com"
      Description: "Role to enable Amazon ECS to manage your cluster."
</code>```

OLD ANSWER:
ECS now rely on a Service-Linked Roles instead of normal roles. Make sure you have created it for the account using:

aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com

Then remove the Role parameter from your IAMRoleECSService as it's no longer needed.

Body:
I create the following CloudFormation template files to create ECS Cluster and TaskDefinition, Service but got an error.
What's wrong these settings?

When create ECS Service using the following templates, got Please verify that the ECS service role being passed has the proper permissions

When create the templates without a property Role: !ImportValue "IAMRoleECSService" , does not occur errors, but does not finish from CREATE_IN_PROGRESS

ECSApplicationService:
  Type: "AWS::ECS::Service"
  DependsOn:
    - "ECSApplicationCluster"
    - "ECSApplicationTaskDefinition"
  Properties:
    Cluster: !Ref "ECSApplicationCluster"
    DeploymentConfiguration:
      MaximumPercent: 100
      MinimumHealthyPercent: 50
    DesiredCount: 4
    LoadBalancers:
      - ContainerName: !Ref "ContainerAppName"
        ContainerPort: 80
        TargetGroupArn: !ImportValue "ALBTargetGroup"
    Role: !ImportValue "IAMRoleECSService"
    ServiceName: "ecs-application-service"
    TaskDefinition: !Ref "ECSApplicationTaskDefinition"

IAMRoleECSService:
  Type: "AWS::IAM::Role"
  Properties:
    RoleName: "ecs-service"
    AssumeRolePolicyDocument:
      Version: "2012-10-17"
      Statement:
        - Effect: "Allow"
          Principal:
            Service:
              - "ecs.amazonaws.com"
          Action:
            - "sts:AssumeRole"
    Policies:
      - PolicyName: "ec2-management"
        PolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: "Allow"
              Action:
                - "ec2:AuthorizeSecurityGroupIngress"
                - "ec2:Describe*"
              Resource: "*"
      - PolicyName: "alb-management"
        PolicyDocument:
          Version: "2012-10-17"
          Statement:
            - Effect: "Allow"
              Action:
                - "elasticloadbalancing:DeregisterInstancesFromLoadBalancer"
                - "elasticloadbalancing:DeregisterTargets"
                - "elasticloadbalancing:DescribeTargetGroups"
                - "elasticloadbalancing:DescribeTargetHealth"
                - "elasticloadbalancing:Describe*"
                - "elasticloadbalancing:RegisterInstancesWithLoadBalancer"
                - "elasticloadbalancing:RegisterTargets"
              Resource: "*"

What should I do?

Body:
UPDATE:
As of July 19th 2018, it is now possible to create a IAM Service-Linked Roles using CloudFormation https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-servicelinkedrole.html.

   EcsServiceLinkedRole:
    Type: "AWS::IAM::ServiceLinkedRole"
    Properties:
      AWSServiceName: "ecs.amazonaws.com"
      Description: "Role to enable Amazon ECS to manage your cluster."

OLD ANSWER:
ECS now rely on a Service-Linked Roles instead of normal roles. Make sure you have created it for the account using:

aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com

Then remove the Role parameter from your IAMRoleECSService as it's no longer needed.


问:
Function returns array with dates of tiles
I have js code which returns dates of layers (Using OpenLayers and Momentjs) that stored on my PC.

As we see that the function returns all the dates between two dates from the folder (folder) with a 60-second step. But I want to return just the dates which I have files (layers) on my PC because I don't have layers for all the dates.

So what I need is a function returns an array of dates for which I have tiles only, and then add from this layer to the map depends on the entered dates

function loopLayer() {
  const FromDateTime = document.getElementById("fromdate").value;
  const dateFrom = moment(FromDateTime, "YYYY-MM-DD HH:mm:ss", true);
  if (!dateFrom.isValid()) {
    log("something");
    return;
  }

  const ToDateTime = document.getElementById("todate").value;
  const dateTo = moment(ToDateTime, "YYYY-MM-DD HH:mm:ss", true);
  if (!dateTo.isValid()) {
    log("something");
    return;
  }

  let loopDate = dateFrom;
  for(let i=0; dateFrom.isSameOrBefore(dateTo) && i < 100; i++) {
    // preventing from loading thousands of layers
    loopLayerByDate(loopDate);
    loopDate = loopDate.add(60, 'seconds');

  }
}

function loopLayerByDate(dateObject) {
  const folderDate = dateObject.format("YYYY-MM-DD_HHmmss");
  const source = new ol.source.XYZ({
    projection: 'EPSG:3854',
    // adapt url and source tile type to your setup
    url: "folder/" + folderDate + "/{z}/{x}/{-y}.png"

  });

  const layer = new ol.layer.Tile({
    source: source,
    title: "layer"
  });
  map.addLayer(layer)
}```

答:
An Website usually cannot read data from your local file system for security reasons. Otherwise any website could spy on your harddisk.

As you already found out, there is an exception to that rule: when you open a local HTML file, it can read file content from the harddisk. But you can't crawl through folders, so we cannot read a list of the available dates.

you have two options now:

add an <input type="file" multiple>, upload the files and use the FileAPI (example here).

your thing is a local html file which you open from your harddisk. You could use a trial-and-error guess approach

find a method to build a list of dates without the need to guess them, e.g. naming the folders with an increasing number instead of timestamps!

Use a server software which serves everything. The server can access the file-system and send the "front-end" the required list of dates. I won't provide an how-to here, there are tons of software-solutions and how-tos on stackoverflow and in search engines.

Option 2, local html:

Since you know roughly in what ranges the filenames is, you could use a brute-force approach and just query for all dates in a range and see which ones actually respond. Be aware that this approach is far from ideal and probably quite slow.

```<code>function guessValidDates(arrayOfDates){
    const validDates = [];
    arrayOfDates.forEach((date) => {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "time/" + date + "/1.png", true);
        xhttp.send();
    console.log('request returned', xhttp);
        if (xhttp.response) {
            validDates.push(date;
        }
    });
    return validDates;
}
</code>```

Example usage:

```<code>// example from loopLayer function
let loopDate = dateFromObject;
const allDates = [];
for(let i=0; dateFromObject.isSameOrBefore(dateToObject) && i < 100; i++) {
  // the i counts as a failsafe, preventing us from loading billions of
  // or whatever the pattern is for your file path
  allDates.push(loopDate.format("YYYY-MM-DD_HHmmss"));

  // step forward by X
  loopDate = loopDate.add(1, 'minutes');
}

const validDates = guessValidDates(allDates);
// now you know the valid dates and can use them. Example:
validDates.forEach(function(someDate){
  loopLayerByDate(someDate);
});
</code>```

Or if you have a pattern where all layers for a single day have an increasing number, eg "time/" + yearMontDay + '_' + increasingNumber + "/{z}/{x}/{-y}.png", just keep adding layers until you get a non-valid response:

```<code>function isValidLayer(someDateString, someNumber) {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "time/" + someDateString + "_" + someNumber + "/1.png", true);
  xhttp.send();
  if (xhttp.response) {
      return true;
  }
  return false;
}

// you can now count up until you don't get a valid response anymore:

let someDateString = dateObject.format("YYYY-MM-DD_HHmmss");
let increasingNumber = 0;
while(increasingNumber < 1000) {
    // the condition is just a failsafe
    if(isValidLayer(someDateString, increasingNumber) {
      // add layer with that number to your map
      const source = new ol.source.XYZ({
        projection: 'EPSG:4326',
        wrapX: false,
        url: "time/" + folderDate + "_" + increasingNumber + "/{z}/{x}/{-y}.png"
      });
      // TODO add layer here and so on....
    } else {
      // no more layers, stop!
      console.log('stopped after' + increasingNumber + 'layers on date ' + someDateString);
      break;
    }
}
</code>```

Body:
An Website usually cannot read data from your local file system for security reasons. Otherwise any website could spy on your harddisk.

As you already found out, there is an exception to that rule: when you open a local HTML file, it can read file content from the harddisk. But you can't crawl through folders, so we cannot read a list of the available dates.

you have two options now:

add an <input type="file" multiple>, upload the files and use the FileAPI (example here).

your thing is a local html file which you open from your harddisk. You could use a trial-and-error guess approach

find a method to build a list of dates without the need to guess them, e.g. naming the folders with an increasing number instead of timestamps!

Use a server software which serves everything. The server can access the file-system and send the "front-end" the required list of dates. I won't provide an how-to here, there are tons of software-solutions and how-tos on stackoverflow and in search engines.

Option 2, local html:

Since you know roughly in what ranges the filenames is, you could use a brute-force approach and just query for all dates in a range and see which ones actually respond. Be aware that this approach is far from ideal and probably quite slow.

function guessValidDates(arrayOfDates){
    const validDates = [];
    arrayOfDates.forEach((date) => {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "time/" + date + "/1.png", true);
        xhttp.send();
    console.log('request returned', xhttp);
        if (xhttp.response) {
            validDates.push(date;
        }
    });
    return validDates;
}

Example usage:

// example from loopLayer function
let loopDate = dateFromObject;
const allDates = [];
for(let i=0; dateFromObject.isSameOrBefore(dateToObject) && i < 100; i++) {
  // the i counts as a failsafe, preventing us from loading billions of
  // or whatever the pattern is for your file path
  allDates.push(loopDate.format("YYYY-MM-DD_HHmmss"));

  // step forward by X
  loopDate = loopDate.add(1, 'minutes');
}

const validDates = guessValidDates(allDates);
// now you know the valid dates and can use them. Example:
validDates.forEach(function(someDate){
  loopLayerByDate(someDate);
});

Or if you have a pattern where all layers for a single day have an increasing number, eg "time/" + yearMontDay + '_' + increasingNumber + "/{z}/{x}/{-y}.png", just keep adding layers until you get a non-valid response:

function isValidLayer(someDateString, someNumber) {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "time/" + someDateString + "_" + someNumber + "/1.png", true);
  xhttp.send();
  if (xhttp.response) {
      return true;
  }
  return false;
}

// you can now count up until you don't get a valid response anymore:

let someDateString = dateObject.format("YYYY-MM-DD_HHmmss");
let increasingNumber = 0;
while(increasingNumber < 1000) {
    // the condition is just a failsafe
    if(isValidLayer(someDateString, increasingNumber) {
      // add layer with that number to your map
      const source = new ol.source.XYZ({
        projection: 'EPSG:4326',
        wrapX: false,
        url: "time/" + folderDate + "_" + increasingNumber + "/{z}/{x}/{-y}.png"
      });
      // TODO add layer here and so on....
    } else {
      // no more layers, stop!
      console.log('stopped after' + increasingNumber + 'layers on date ' + someDateString);
      break;
    }
}


问:
Gitlab CI - How to start Shared Runner
I'm new to Gitlab CI.

I have configured .gitlab-ci.yml file, and using CI Lint it has passed the validation process.

Based on this documentation, I can see a specific runner should be configured on a virtual machine, a VPS, a bare-metal machine, a docker container or
even a cluster of containers.

But I can see gitlab has its own shared runners and enabled by default.

The question is how to use this shared runner?

When I visit the Pipeline page I can only see the blue Get Started with Pipeline button and when clicked I was redirected to this page.

Here's my .gitlab-ci.yml content :

```<code>before_script:
  - eval $(ssh-agent -s)

stage_deploy:
  only:
    - testing
  script:
    - ssh-add <(echo "$STAGING_PRIVATE_KEY")
    - ssh root@1.2.3.4 "sh update_app.sh"
</code>```

答: It will only run the job for your testing branch, have you added the .gitlab-ci.yml file to that branch too?

Title: Gitlab CI - How to start Shared Runner

Body:
I'm new to Gitlab CI.

I have configured .gitlab-ci.yml file, and using CI Lint it has passed the validation process.

Based on this documentation, I can see a specific runner should be configured on a virtual machine, a VPS, a bare-metal machine, a docker container or
even a cluster of containers.

But I can see gitlab has its own shared runners and enabled by default.

The question is how to use this shared runner?

When I visit the Pipeline page I can only see the blue Get Started with Pipeline button and when clicked I was redirected to this page.

Here's my .gitlab-ci.yml content :

before_script:
  - eval $(ssh-agent -s)

stage_deploy:
  only:
    - testing
  script:
    - ssh-add <(echo "$STAGING_PRIVATE_KEY")
    - ssh root@1.2.3.4 "sh update_app.sh"


问:
Python RegEx find and add to beginning
Just learning RegEx in Python, and got stuck on this case:

```<code>str = '''
Here are some order bullets:
i. Foo
ii. Bar
iii. Baz
iv. YOLO
...
x. LOL
'''
</code>```

How do I get to this:

```<code>str = '''
Here are some order bullets:
- i. Foo
- ii. Bar
- iii. Baz
- iv. YOLO
...
- x. LOL
'''
</code>```

答:
You can use this regex in MULTILINE mode:

```<code>>>> print re.sub(r'(?m)^([a-zA-Z0-9]+\.)', r'- \1', str)

Here are some order bullets:
- i. Foo
- ii. Bar
- iii. Baz
- iv. YOLO
...
- x. LOL
</code>```

RegEx Breakup:

Search:

(?m): Enable MULTILINE mode

^: Start

([a-zA-Z0-9]+\.): Match and group 1+ alphanumeric characters

Replacement:

-: Place literal "- "

\1: Back-reference to captured group #1

Title: Python RegEx find and add to beginning

Body:
Just learning RegEx in Python, and got stuck on this case:

str = '''
Here are some order bullets:
i. Foo
ii. Bar
iii. Baz
iv. YOLO
...
x. LOL
'''

How do I get to this:

str = '''
Here are some order bullets:
- i. Foo
- ii. Bar
- iii. Baz
- iv. YOLO
...
- x. LOL
'''

Body:
You can use this regex in MULTILINE mode:

>>> print re.sub(r'(?m)^([a-zA-Z0-9]+\.)', r'- \1', str)

Here are some order bullets:
- i. Foo
- ii. Bar
- iii. Baz
- iv. YOLO
...
- x. LOL

RegEx Breakup:

Search:

(?m): Enable MULTILINE mode

^: Start

([a-zA-Z0-9]+\.): Match and group 1+ alphanumeric characters

Replacement:

-: Place literal "- "

\1: Back-reference to captured group #1


问:
ramotion expanding collection instructions unclear
I'm trying to use the expanding-collection library and I'm having some trouble understanding the guide. Here's the readme: https://github.com/Ramotion/expanding-collection/blob/master/README.md

I'm having trouble understanding the first instruction

Create UICollectionViewCell inherit from BasePageCollectionCell
  (recommend create cell with xib file)

Does this mean I should add a collectionviewcell to main.storyboard? As I have tried, however, xCode did not allow me to drag and drop an individual uicollectionviewcell into the storyboard or create a class called UICollectionViewCell that inherits from BasePageCollectionCell.

答: You should make a new file to add in your project, go File>New>File...>Cocoa Touch Class, enter name of class, select to inherit from BasePageCollectionCell and that's it.</p>


问:
Laravel Intervention/image memory_limit
In my floder I have 120MB of images. One image - near 3 MB. I try to use this code to resize them:

```<code>public function images_zip(Request $request){
    if($request->width < 1 || $request->hight < 1 || $request->width > 2000 || $request->hight >2000){
        return Redirect::back()->withErrors(['Некорректные входные данные']);
    }
    $files = Storage::disk('images')->files('/'.$request->name.'/image');
    $mime_types = array('image/gif','image/jpeg','image/png','image/svg+xml');
    ini_set('memory_limit','128M');
    foreach ($files as $file){
        if(in_array(File::mimeType($file),$mime_types)) {
            $img = Image::make(public_path() . '/' . $file);
                $img->resize($request->width, $request->hight);
                $img->save(public_path() . '/' . $file);
                $img->destroy();
        }
    }
    return \redirect()->back();
}
</code>```

But I take this error -

```<code>Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
</code>```

I tried to use ->destroy() and ini_set('memory_limit','128M') ,like people say, but it didnt help. My server have 128MB memory. Help me,please!

答:
You can try editing /etc/php5/fpm/php.ini:

```<code>; Old Limit
; memory_limit = 512M

; New Limit
memory_limit = 2048M
</code>```

You need to restart apache.

Title: Laravel Intervention/image memory_limit

Body:
In my floder I have 120MB of images. One image - near 3 MB. I try to use this code to resize them:

public function images_zip(Request $request){
    if($request->width < 1 || $request->hight < 1 || $request->width > 2000 || $request->hight >2000){
        return Redirect::back()->withErrors(['Некорректные входные данные']);
    }
    $files = Storage::disk('images')->files('/'.$request->name.'/image');
    $mime_types = array('image/gif','image/jpeg','image/png','image/svg+xml');
    ini_set('memory_limit','128M');
    foreach ($files as $file){
        if(in_array(File::mimeType($file),$mime_types)) {
            $img = Image::make(public_path() . '/' . $file);
                $img->resize($request->width, $request->hight);
                $img->save(public_path() . '/' . $file);
                $img->destroy();
        }
    }
    return \redirect()->back();
}

But I take this error -

Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)

I tried to use ->destroy() and ini_set('memory_limit','128M') ,like people say, but it didnt help. My server have 128MB memory. Help me,please!

Body:
You can try editing /etc/php5/fpm/php.ini:

; Old Limit
; memory_limit = 512M

; New Limit
memory_limit = 2048M

You need to restart apache.


问:
iPhone X App Store Previews not working with iMovie?
I'm trying to submit a video preview for the App Store for my iPhone X app, but when I exported with iMovie, it's exporting in the iPhone 6 size, not X. When I tried uploading to iTunes Connect, it said it's the wrong size. I don't know if iMovie doesn't support the X yet or if it's a bug?

And is there any way for me to change the frame size of the video so I can upload? Thank you!

答:
Unfortunately iMovie doesn't support iPhone X yet.
What you can try is changing the dimensions of exported video yourself as:

```<code> ffmpeg -i filename.mp4 -strict -2 -vf scale=1080:1920 -ac 2 output_file.mp4
</code>```

However video will be distorted. Another option is to use another editing software like Adobe Premier Pro.

Edit: For a free solution try openshot. It lets you export your video at custom dimensions. (Then you might have to run the command above)

Body:
Unfortunately iMovie doesn't support iPhone X yet.
What you can try is changing the dimensions of exported video yourself as:

 ffmpeg -i filename.mp4 -strict -2 -vf scale=1080:1920 -ac 2 output_file.mp4

However video will be distorted. Another option is to use another editing software like Adobe Premier Pro.

Edit: For a free solution try openshot. It lets you export your video at custom dimensions. (Then you might have to run the command above)


问:
NotFittedError issue with Sklearn
I'm trying to use the LinearSVC of sklearn and export the decision tree to a .dot file. I can fit the classifier with sample data and then use it on some test data but the export to the .dot file gives a NotFittedError.

```<code>data = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=list(range(0, 41)))
data = data.fillna('Missing value').apply(pp.LabelEncoder().fit_transform)

target = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=[41])

dataTest = pd.read_csv("census-income-test.test", skipinitialspace=True, usecols=list(range(0, 41)))
dataTest = dataTest.fillna('Missing value').apply(pp.LabelEncoder().fit_transform)

targetTest = pd.read_csv("census-income-test.test", skipinitialspace=True, usecols=[41])
clfSVC = LinearSVC(random_state=0)

clfSVC = clfSVC.fit(data, target.target)
scoreSVC = clfSVC.score(dataTest, targetTest.target)
print(scoreSVC)
tree.export_graphviz(clfSVC, out_file='tree.dot')
</code>```

Here is the output:

```<code>> Traceback (most recent call last):
  File "D:\Documents\Telecom\IA\ai-person-income\project\sklearn_test.py", line 49, in <module>
    tree.export_graphviz(clfSVC, out_file='tree.dot')
  File "D:\Program Files\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\sklearn\tree\export.py", line 392, in export_graphviz
    check_is_fitted(decision_tree, 'tree_')
  File "D:\Program Files\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\sklearn\utils\validation.py", line 768, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
sklearn.exceptions.NotFittedError: This LinearSVC instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.
</code>```

What am I missing ?

答:
You are using a function to plot a decision-tree. Look at the first argument: decision_tree, like an object of this.

A SVM is not a decision-tree! It isn't any kind of tree and you can't use this function and it also makes no sense in theory.

The error itself is based on this code:

```<code>check_is_fitted(decision_tree, 'tree_')
</code>```

where the internal tree of a decision-tree object is queried. This does not exists for SVMs.

Title: NotFittedError issue with Sklearn

Body:
I'm trying to use the LinearSVC of sklearn and export the decision tree to a .dot file. I can fit the classifier with sample data and then use it on some test data but the export to the .dot file gives a NotFittedError.

data = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=list(range(0, 41)))
data = data.fillna('Missing value').apply(pp.LabelEncoder().fit_transform)

target = pd.read_csv("census-income-data.data", skipinitialspace=True, usecols=[41])

dataTest = pd.read_csv("census-income-test.test", skipinitialspace=True, usecols=list(range(0, 41)))
dataTest = dataTest.fillna('Missing value').apply(pp.LabelEncoder().fit_transform)

targetTest = pd.read_csv("census-income-test.test", skipinitialspace=True, usecols=[41])
clfSVC = LinearSVC(random_state=0)

clfSVC = clfSVC.fit(data, target.target)
scoreSVC = clfSVC.score(dataTest, targetTest.target)
print(scoreSVC)
tree.export_graphviz(clfSVC, out_file='tree.dot')

Here is the output:

> Traceback (most recent call last):
  File "D:\Documents\Telecom\IA\ai-person-income\project\sklearn_test.py", line 49, in <module>
    tree.export_graphviz(clfSVC, out_file='tree.dot')
  File "D:\Program Files\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\sklearn\tree\export.py", line 392, in export_graphviz
    check_is_fitted(decision_tree, 'tree_')
  File "D:\Program Files\WinPython-64bit-3.6.3.0Qt5\python-3.6.3.amd64\lib\site-packages\sklearn\utils\validation.py", line 768, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
sklearn.exceptions.NotFittedError: This LinearSVC instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.

What am I missing ?

Body:
You are using a function to plot a decision-tree. Look at the first argument: decision_tree, like an object of this.

A SVM is not a decision-tree! It isn't any kind of tree and you can't use this function and it also makes no sense in theory.

The error itself is based on this code:

check_is_fitted(decision_tree, 'tree_')

where the internal tree of a decision-tree object is queried. This does not exists for SVMs.


问:
Obtaining list of objects from client side in asp.net core 2.0
I'm new to asp.net core. I've been reading and I know now how to submit data on a form as an object to the code behind, through post methods. That's fine. But how about sending a list of objects? What I would need to do would be (in this example it would be for an hotel management room types and rate types) something like a grid where I have a list of room types, where each one has a list of rate types. How can I do this? as I've done it, I can pass through the name of the room type (only as one object, though) but not any rates.

I have it like this (models):

```<code>public class RateType
    {
        public string Name { get; set; }
        public bool IsActive { get; set; }
    }

public class RoomType
    {
        public string Name { get; set; }

        public List<RateType> Rates { get; set; } = new List<RateType>();
    }
</code>```

In the HomeController:

```<code>public IActionResult RoomConfig()
        {
            return View(room);
        }

        [HttpGet]
        public ViewResult SaveRoomConfig()
        {

            return View("RoomConfig");
        }

        [HttpPost]
        public ViewResult SaveRoomConfig(RoomType room)
        {

            return View("RoomConfig");
        }
</code>```

And in the view:

```<code>@model RoomType
@{
    ViewData["Title"] = "RoomConfig";
}

<h2>@Model.Name</h2>

<form class="p-a-1" asp-action="SaveRoomConfig" method="post">
    @foreach (var item in Model.Rates)
    {
        <label asp-for="Name">@item.Name </label>
        <input class="form-control" asp-for="Name" />
        <input asp-for="@item.IsActive" type="checkbox" />

    }
    <button type="submit">Send</button>

</form>
</code>```

So, I send an initial object with some pre-defined values just for testing and they are shown on the page. But then, when I click "send" I can only send the first object (makes sense, since I only have an object parameter, so it will send only the first one. Still, I tried putting a list of RoomType's to see what it did but it shows count as zero. So, how can I do it? Pass a list of objects with another list of objects (nested). Is this possible? It doesn't make sense to make to only have the possibility to pass one and only single object.

答:
Ok, I realized why it wasn't working. I was doing everything right, except for the fact that I was binding items to an empty list which, by definition, didn't have any items. So, instead of a 'foreach', I wrote a 'for' statement, in order to get to the index. That way, I binded the object to the position on the list, instead of a non-existing object. Like this:

```<code>@model RoomType
@{
    ViewData["Title"] = "RoomConfig";
}

<form class="p-a-1" asp-action="SaveRoomConfig" method="post">
    <input asp-for="Name" />
    @for (int i=0;i< Model.Rates.Count;i++)
    {
        <div class=" form-control">
            <label asp-for="@Model.Rates[i].Name">@Model.Rates[i].Name </label>
            <input asp-for="@Model.Rates[i].Name" />
            <input asp-for="@Model.Rates[i].IsActive" type="checkbox" />
        </div>
    }
    <button type="submit">Send</button>

</form>
</code>```

Of course, if anyone has a better way to do this I'm all ears. :)

Body:
I'm new to asp.net core. I've been reading and I know now how to submit data on a form as an object to the code behind, through post methods. That's fine. But how about sending a list of objects? What I would need to do would be (in this example it would be for an hotel management room types and rate types) something like a grid where I have a list of room types, where each one has a list of rate types. How can I do this? as I've done it, I can pass through the name of the room type (only as one object, though) but not any rates.

I have it like this (models):

public class RateType
    {
        public string Name { get; set; }
        public bool IsActive { get; set; }
    }

public class RoomType
    {
        public string Name { get; set; }

        public List<RateType> Rates { get; set; } = new List<RateType>();
    }

In the HomeController:

public IActionResult RoomConfig()
        {
            return View(room);
        }

        [HttpGet]
        public ViewResult SaveRoomConfig()
        {

            return View("RoomConfig");
        }

        [HttpPost]
        public ViewResult SaveRoomConfig(RoomType room)
        {

            return View("RoomConfig");
        }

And in the view:

@model RoomType
@{
    ViewData["Title"] = "RoomConfig";
}

@Model.Name

<form class="p-a-1" asp-action="SaveRoomConfig" method="post">
    @foreach (var item in Model.Rates)
    {
        @item.Name
        <input class="form-control" asp-for="Name" />
        <input asp-for="@item.IsActive" type="checkbox" />

    }
    <button type="submit">Send</button>

</form>

So, I send an initial object with some pre-defined values just for testing and they are shown on the page. But then, when I click "send" I can only send the first object (makes sense, since I only have an object parameter, so it will send only the first one. Still, I tried putting a list of RoomType's to see what it did but it shows count as zero. So, how can I do it? Pass a list of objects with another list of objects (nested). Is this possible? It doesn't make sense to make to only have the possibility to pass one and only single object.

Body:
Ok, I realized why it wasn't working. I was doing everything right, except for the fact that I was binding items to an empty list which, by definition, didn't have any items. So, instead of a 'foreach', I wrote a 'for' statement, in order to get to the index. That way, I binded the object to the position on the list, instead of a non-existing object. Like this:

@model RoomType
@{
    ViewData["Title"] = "RoomConfig";
}

<form class="p-a-1" asp-action="SaveRoomConfig" method="post">
    <input asp-for="Name" />
    @for (int i=0;i< Model.Rates.Count;i++)
    {
        <div class=" form-control">
            <label asp-for="@Model.Rates[i].Name">@Model.Rates[i].Name </label>
            <input asp-for="@Model.Rates[i].Name" />
            <input asp-for="@Model.Rates[i].IsActive" type="checkbox" />
        </div>
    }
    <button type="submit">Send</button>

</form>

Of course, if anyone has a better way to do this I'm all ears. :)


问:
Java Scanner unable to read file
I'm doing a very simple text-parsing program, using files given to me by a friend.
However, when I open the file using a Scanner like so,

```<code>Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
    System.err.println(scan.nextLine());
System.err.println(scan.next());
</code>```

result:

```<code>false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)
</code>```

the scanner treats the file(which is some 1400 lines long) as empty.

Can anyone think of any reason a scanner might not be able to see a file? I suspect the fact that the file was imported from a Windows machine to a Linux machine may have something to do with it, but my mind is open to other possibilities

edited for formatting and code errors

答:
Found the problem:
Looked at the file byte by byte. found an EOF character in the first byte.
Java was ignoring the rest of the file.</p>

Title: Java Scanner unable to read file

Body:
I'm doing a very simple text-parsing program, using files given to me by a friend.
However, when I open the file using a Scanner like so,

Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
    System.err.println(scan.nextLine());
System.err.println(scan.next());

result:

false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)

the scanner treats the file(which is some 1400 lines long) as empty.

Can anyone think of any reason a scanner might not be able to see a file? I suspect the fact that the file was imported from a Windows machine to a Linux machine may have something to do with it, but my mind is open to other possibilities

edited for formatting and code errors


问:
ASP.NET Core Identity - How to add new claims after initial login
I am trying to add new claims to the Identity after the initial login based on certain data that is queried from database. The new claims that I am adding not persisting for subsequent requests.

This is how i'm setting/Adding claims in ASP.NET MVC

```<code>public static void UpdateClaim(IPrincipal principal, string key, string value)
        {
            var identity = principal.Identity as ClaimsIdentity;
            if (identity == null)
                return;

            // check for existing claim and remove it
            var existingClaim = identity.FindFirst(key);
            if (existingClaim != null)
                identity.RemoveClaim(existingClaim);

            // add new claim
            identity.AddClaim(new Claim(key, value));
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
        }
</code>```

Is there is similar way in ASP.NET Core 2.0 to persist newly added claims. Appreciate any ideas on this.

答: The claims are persisting, but they are only loaded when signing in. If you make a change to something like claims or roles, you must sign the user out and then either automatically sign them back in or prompt them to reauthenticated to update the claims.</p>

Body:
I am trying to add new claims to the Identity after the initial login based on certain data that is queried from database. The new claims that I am adding not persisting for subsequent requests.

This is how i'm setting/Adding claims in ASP.NET MVC

public static void UpdateClaim(IPrincipal principal, string key, string value)
        {
            var identity = principal.Identity as ClaimsIdentity;
            if (identity == null)
                return;

            // check for existing claim and remove it
            var existingClaim = identity.FindFirst(key);
            if (existingClaim != null)
                identity.RemoveClaim(existingClaim);

            // add new claim
            identity.AddClaim(new Claim(key, value));
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
        }

Is there is similar way in ASP.NET Core 2.0 to persist newly added claims. Appreciate any ideas on this.


问:
Font-Awesome Icon not appearing
I am using Bootstrap4 and Font-Awesome together.
I know Bootstrap4 is working fine because all classes I'm using from Bootstrap4 work fine. However, this is my first time working with Font-Awesome and I really don't know why the icons aren't appearing.
I fetched FontAwesome using this in my head.

```<code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
</code>```

Then later I use.

```<code><div class="container text-center">
    <br /><br /><br />
    <i class="icon-search"></i> <input id="search" type="text" placeholder="Search for a City" />
</div>
</code>```

I used this documentation: http://fontawesome.io/3.2.1/icon/search/
Also, my network tab says that font-awesome has been fetched with a status of 200.

答:
When using the CDN for 3.2.1version, everything is working fine.

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />

     <input id="search" type="text" placeholder="Search for a City" />

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

<p>If you want to use <code>4.7.0</code>, you have to do it like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
    <div class="container text-center">
        <br /><br /><br />
        <i class="fa fa-search"></i> <input id="search" type="text" placeholder="Search for a City" />
    </div></code>```

Documentation from v4: http://fontawesome.io/icon/search/

Title: Font-Awesome Icon not appearing

Body:
I am using Bootstrap4 and Font-Awesome together.
I know Bootstrap4 is working fine because all classes I'm using from Bootstrap4 work fine. However, this is my first time working with Font-Awesome and I really don't know why the icons aren't appearing.
I fetched FontAwesome using this in my head.

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

Then later I use.

     <input id="search" type="text" placeholder="Search for a City" />

I used this documentation: http://fontawesome.io/3.2.1/icon/search/
Also, my network tab says that font-awesome has been fetched with a status of 200.

Body:
When using the CDN for 3.2.1version, everything is working fine.

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet" />
<div class="container text-center">
    <br /><br /><br />
    <i class="icon-search"></i> <input id="search" type="text" placeholder="Search for a City" />
</div>

If you want to use 4.7.0, you have to do it like this:

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
    <div class="container text-center">
        <br /><br /><br />
        <i class="fa fa-search"></i> <input id="search" type="text" placeholder="Search for a City" />
    </div>

Documentation from v4: http://fontawesome.io/icon/search/


问:
Accessing form's button field
I have a button on my form, but I am unable to access it from my code. My code (from Program.cs):

Form1.button1.Text = "Button text"
```

I cannot access it due to it's protection level. What shall I do to change this field protection level or something?

答:
Changing the modifier of an object is a bad idea.
Better would  be to create a public property on Form1, for example Button1Text and call that in stead of accesing a private object.

```<code>public string Button1Text
{
   get { return Button1.Text; }
   set {Button1.Text = value; }
}
</code>```

then call it like this

```<code>form1.Button1Text = "I am a button"
</code>```

Make sure that form1 is the created instance for your form, not the class name !

Title: Accessing form's button field

Body:
I have a button on my form, but I am unable to access it from my code. My code (from Program.cs):

Form1.button1.Text = "Button text"

I cannot access it due to it's protection level. What shall I do to change this field protection level or something?

Body:
Changing the modifier of an object is a bad idea.
Better would  be to create a public property on Form1, for example Button1Text and call that in stead of accesing a private object.

public string Button1Text
{
   get { return Button1.Text; }
   set {Button1.Text = value; }
}

then call it like this

form1.Button1Text = "I am a button"

Make sure that form1 is the created instance for your form, not the class name !


问:
How to do inclusion of schema in other schema using Z language
I am writing a formal specification for my model using z-notation of Z-language. I am stuck and don't know how to include one schema in another schema and creates its variables in other schemas. Any guidance and help would be appreciated.
Thanks.</p>

答:
You can use a schema like a record data type. E.g. let's assume you have a schema describing a complex integer number:

```<code>--- Complex ---
| real, img: ℤ
------
</code>```

You can declare a variable in another schema to be of that type:

```<code>--- Ex1 ---
| c: Complex
----
| c.real = 5 ∧ c.img = 6
-------
</code>```

You can of course create more complex data types with it, here a sequence and an operation to append an element:

```<code>--- State ---
| data: seq Complex
-------

--- Add1 ---
| ΔState
| real?, img?: ℤ
----
| ∃ c:Complex · c.real = real? ∧ c.img = img? ∧ data' = data^<c>
-------
</code>```

You can also use the theta-operator to create an instance of that type. The values for the variables are taken from the current context (+ optional decorations):

```<code>--- Add2 ---
| ΔState
| real?, img?: ℤ
----
| data' = data^< θComplex? >
-------
</code>```

θComplex? is an instance of Complex where the values for real and img are taken from the local variables real? and img?.

We can also declare the input variables by using the original schema and write the operation more concise (Add3 is the same as Add2):

```<code>--- Add3 ---
| ΔState
| Complex?
----
| data' = data^< θComplex? >
-------
</code>```

(I deleted my original answer because I misinterpret your question.)

Body:
You can use a schema like a record data type. E.g. let's assume you have a schema describing a complex integer number:

--- Complex ---
| real, img: ℤ
------

You can declare a variable in another schema to be of that type:

--- Ex1 ---
| c: Complex
----
| c.real = 5 ∧ c.img = 6
-------

You can of course create more complex data types with it, here a sequence and an operation to append an element:

--- State ---
| data: seq Complex
-------

--- Add1 ---
| ΔState
| real?, img?: ℤ
----
| ∃ c:Complex · c.real = real? ∧ c.img = img? ∧ data' = data^<c>
-------

You can also use the theta-operator to create an instance of that type. The values for the variables are taken from the current context (+ optional decorations):

--- Add2 ---
| ΔState
| real?, img?: ℤ
----
| data' = data^< θComplex? >
-------

θComplex? is an instance of Complex where the values for real and img are taken from the local variables real? and img?.

We can also declare the input variables by using the original schema and write the operation more concise (Add3 is the same as Add2):

--- Add3 ---
| ΔState
| Complex?
----
| data' = data^< θComplex? >
-------

(I deleted my original answer because I misinterpret your question.)


问:
Carbon\Carbon not found inconsistently - Laravel 5.5
So currently I pull back a date and convert it to a readable format in carbon:

```<code></div>
<div class="">
 <label for="Name">Letter Sent:</label>
 @if (is_null($Client->letter_posted))
 @else
   {{  \carbon\carbon::createFromFormat('Y-m-d',$Client->letter_posted)->format('d/m/Y')}}
 @endif
</div>
</code>```

And it works when testing  (Testing both whilst letter_posted is null and not) however very occasionally it will spit out the error on the live server:

```<code>Class 'carbon\carbon' not found
</code>```

It has only occurred 3 times in the last 2 months very randomly and a refresh of the page will remove this error eg. the error appears, if you refresh the page it is no longer there.

Any help appreciated.

答:
Most likely you are receiving the error because you're using carbon\carbon somewhere in your code instead of \carbon\carbon.

Putting the \ in front refers to the global namespace. Without the \, you are referring to a class that might not exist (which is the error you are getting).

See: Class 'App\Carbon\Carbon' not found Laravel 5

You can create an alias to avoid using the full name in Laravel. In app.php, go to aliases and add 'Carbon' => 'Carbon\Carbon'. You can then use it like this:
{{ Carbon::createFromFormat('Y-m-d', $Client->letter_posted)->format('d/m/Y') }}

Additional note: while PHP namespaces are not case-sensitive, it is good practice to treat them as case-sensitive: use \Carbon\Carbon instead of \carbon\carbon.

Body:
So currently I pull back a date and convert it to a readable format in carbon:

 Letter Sent:
 @if (is_null($Client->letter_posted))
 @else
   {{  \carbon\carbon::createFromFormat('Y-m-d',$Client->letter_posted)->format('d/m/Y')}}
 @endif

And it works when testing  (Testing both whilst letter_posted is null and not) however very occasionally it will spit out the error on the live server:

Class 'carbon\carbon' not found

It has only occurred 3 times in the last 2 months very randomly and a refresh of the page will remove this error eg. the error appears, if you refresh the page it is no longer there.

Any help appreciated.


问:
In R, if/then statement to incorporate fields from one dataframe to another?
I built a predictive model off of a data frame (DF1). I now want to apply that model to a different data frame (DF2) that contains some of the variables from DF1, but not all.

What I need to do is create an if/then statement, function, etc. that will delete variables that exist in DF2 but not in DF1 and create a column of 0's for variables that exist in DF1 but not in DF2.

Here is what the initial datasets look like:

```<code># DF_1
cust_id<- c(1234,1235,1236,1237,1238)
var_1<- c(4,5,7,8,7)
var_2<- c(7,9,7,8,9)
var_3<- c(5,7,8,5,4)
df_1<- data.frame(cust_id,var_1,var_2,var_3)

# DF_2
cust_id<- c(2123,2124,2125,2126,2127)
var_1<- c(45,45,48,38,48)
var_4<- c(65,62,61,57,48)
var_5<- c(15,18,14,25,23)
df_2<- data.frame(cust_id,var_1,var_4,var_5)

df_1
df_2
</code>```

Manually coding it, this is what the final dataset should look like:

```<code># DF_2b
cust_id<- c(2123,2124,2125,2126,2127)
var_1<- c(45,45,48,38,48)
var_2<- 0
var_3<- 0
df_2b<- data.frame(cust_id,var_1,var_2,var_3)

df_2b
</code>```

So what I need is code that would delete var_4 and var_5 from df_2 and insert columns of zeros titled var_2 and var_3 into df_2

Body:
I built a predictive model off of a data frame (DF1). I now want to apply that model to a different data frame (DF2) that contains some of the variables from DF1, but not all.

What I need to do is create an if/then statement, function, etc. that will delete variables that exist in DF2 but not in DF1 and create a column of 0's for variables that exist in DF1 but not in DF2.

Here is what the initial datasets look like:

# DF_1
cust_id<- c(1234,1235,1236,1237,1238)
var_1<- c(4,5,7,8,7)
var_2<- c(7,9,7,8,9)
var_3<- c(5,7,8,5,4)
df_1<- data.frame(cust_id,var_1,var_2,var_3)

# DF_2
cust_id<- c(2123,2124,2125,2126,2127)
var_1<- c(45,45,48,38,48)
var_4<- c(65,62,61,57,48)
var_5<- c(15,18,14,25,23)
df_2<- data.frame(cust_id,var_1,var_4,var_5)

df_1
df_2

Manually coding it, this is what the final dataset should look like:

# DF_2b
cust_id<- c(2123,2124,2125,2126,2127)
var_1<- c(45,45,48,38,48)
var_2<- 0
var_3<- 0
df_2b<- data.frame(cust_id,var_1,var_2,var_3)

df_2b

So what I need is code that would delete var_4 and var_5 from df_2 and insert columns of zeros titled var_2 and var_3 into df_2

Body:
try this code

df <- df_2[, intersect(names(df_2), names(df_1))]
df[, setdiff(names(df_1), names(df_2))] <- 0
df

output

    cust_id var_1 var_2 var_3
 1    2123    45     0     0
 2    2124    45     0     0
 3    2125    48     0     0
 4    2126    38     0     0
 5    2127    48     0     0