问:
How can I check whether CK Editor has input using JS/jQuery?
In my application, there is a textarea and I've used CK Editor for it. Now I want to check whether user has input something to it (except whitespace). There were some methods for this. But nothing worked for me. It throws an undefined error when I use it.

Textarea

```<code><div class="form-group {{ $errors->has('template_content') ? 'has-error' : '' }}">
    {{ Form::label('template_content', 'Template Content') }}
    {{ Form::textarea('template_content', null, array('class' => 'form-control', 'id' => 'editor1',
    'name' => 'editor1', 'required', 'data-error="Template content is required"', 'id' =>
   'templateContent')) }}
    {!! $errors->first('template_content', '<span class="help-block">:message</span>') !!}
    <div class="help-block with-errors"></div>
</div>
</code>```

JS Function

```<code>var a = CKEDITOR.instances["editor1"].getData();

    if (a == '') {
        //code to execute
    } else {
        //code to execute
    }
</code>```

Error

Uncaught TypeError: Cannot read property 'getData' of undefined

答:
First

    {{ Form::textarea('template_content', null, array('class' => 'form-control', 'id' => 'editor1',
    'name' => 'editor1', 'required', 'data-error="Template content is required"', 'id' =>
   'templateContent')) }}
```

<p>here you have two <code>id</code>s, your textarea id is templateContent. remove <code>'id' =>
   'templateContent'</code></p>

<p>Second, this is not a watcher!, it's not going to update you realtime. you need to trigger it somehow, for example</p>

<pre class="lang-html prettyprint-override"><code><button id="test">get data</button>

$(document).ready(function() {
  $("#test").click(function() {
    var a = CKEDITOR.instances["editor1"].getData();

    console.log(a);
  });
});
</code>```

Click the button and check the console.

Body:
In my application, there is a textarea and I've used CK Editor for it. Now I want to check whether user has input something to it (except whitespace). There were some methods for this. But nothing worked for me. It throws an undefined error when I use it.

Textarea

has('template_content') ? 'has-error' : '' }}">
    {{ Form::label('template_content', 'Template Content') }}
    {{ Form::textarea('template_content', null, array('class' => 'form-control', 'id' => 'editor1',
    'name' => 'editor1', 'required', 'data-error="Template content is required"', 'id' =>
   'templateContent')) }}
    {!! $errors->first('template_content', ':message') !!}

JS Function

var a = CKEDITOR.instances["editor1"].getData();

    if (a == '') {
        //code to execute
    } else {
        //code to execute
    }

Error

Uncaught TypeError: Cannot read property 'getData' of undefined

Body:
First

    {{ Form::textarea('template_content', null, array('class' => 'form-control', 'id' => 'editor1',
    'name' => 'editor1', 'required', 'data-error="Template content is required"', 'id' =>
   'templateContent')) }}

here you have two ids, your textarea id is templateContent. remove 'id' =>
   'templateContent'

Second, this is not a watcher!, it's not going to update you realtime. you need to trigger it somehow, for example

<button id="test">get data</button>

$(document).ready(function() {
  $("#test").click(function() {
    var a = CKEDITOR.instances["editor1"].getData();

    console.log(a);
  });
});

Click the button and check the console.


来源: stackexchange

问:
Values above the bars in a barchart in Matplotlib
I have the following code for a barchart in matplotlib

```<code>import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018')
y_pos = np.arange(len(objects))
performance = [8.5,9.1,9.7, 10.6, 11.4, 12.6, 13.2, 13.4, 14.7, 15.4, 16.2, 16.7, 17.0, 17.5, 18.0]

fig, ax = plt.subplots(figsize=(18,5))

plt.bar(y_pos, performance, align='center', alpha=0.5, color="green")
plt.xticks(y_pos, objects)
plt.ylim(0, 20)
plt.ylabel('Share in %',  fontsize = 16)
plt.xlim(-0.6, len(objects) - 0.4)
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('Share_Of_Renewables_Europe.png', edgecolor='black', dpi=400, bbox_inches='tight',
           figsize=(18,5) )

for i, performance in enumerate(performance):
    ax.text(performance - 0, i + .25, str(performance), color='black', fontweight='bold')

plt.show()
</code>```

I would like to have values above the bars. I use the suggestion (for loop at the end of my code) from How to display the value of the bar on each bar with pyplot.barh()? but it does not look correct. Here you see the output:

Can anyone help me on that?

答:
Try this:</p>

```<code>xlocs = ax.get_xticks()

for i, performance in enumerate(performance):
    ax.text(xlocs[i] - .25, performance + .25, str(performance), color='black', fontweight='bold')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following code for a barchart in matplotlib

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018')
y_pos = np.arange(len(objects))
performance = [8.5,9.1,9.7, 10.6, 11.4, 12.6, 13.2, 13.4, 14.7, 15.4, 16.2, 16.7, 17.0, 17.5, 18.0]

fig, ax = plt.subplots(figsize=(18,5))

plt.bar(y_pos, performance, align='center', alpha=0.5, color="green")
plt.xticks(y_pos, objects)
plt.ylim(0, 20)
plt.ylabel('Share in %',  fontsize = 16)
plt.xlim(-0.6, len(objects) - 0.4)
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('Share_Of_Renewables_Europe.png', edgecolor='black', dpi=400, bbox_inches='tight',
           figsize=(18,5) )

for i, performance in enumerate(performance):
    ax.text(performance - 0, i + .25, str(performance), color='black', fontweight='bold')

plt.show()

I would like to have values above the bars. I use the suggestion (for loop at the end of my code) from How to display the value of the bar on each bar with pyplot.barh()? but it does not look correct. Here you see the output:

Can anyone help me on that?

Body:
Try this:

xlocs = ax.get_xticks()

for i, performance in enumerate(performance):
    ax.text(xlocs[i] - .25, performance + .25, str(performance), color='black', fontweight='bold')


问:
Calling powershell script with C# - passing in string array as argument in powershell
I am writing C# code to execute a powershell script.
The powershell script has two arguments:

subscriptionId of type string

resourceGroupNames of type string[]

Problem:

When running the C# program, the resourceGroupNames that is passed a is not being read by the powershell script.

Additionally, when running the C# program, powershell prompts me a message "Do you want to run this script?" Is there anyway to suppress this alert and have the powershell script to run automatically?

Here is my code:
Note that chefRepo is the path of the powershell script.

```<code>public void DoDeploymentRTM(string chefRepo, string subscriptionId, string[] resourceGroupNames)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = @"powershell.exe";
            startInfo.Arguments = String.Format(@"& '{0}\AzurePowerShellScripts\azureVMStatusFetch.ps1' -subscriptionId {1} -resourceGroupNames {2}", chefRepo, subscriptionId, resourceGroupNames);
            startInfo.Verb = "runas";
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
        }
</code>```

答:
For passing an array as powershell argument you need to separate it's values by commas i.e. for integers you would pass e.g 1,2,3.
For string you need additional quotation marks (in case some items contain space) e.g.'first string','second string','third'.
In C# you would do this by

```<code>string.Join(',', resourceGroupNames.Select(x => "'" + x + "'"))
</code>```

In order to make this approach work when calling by ProcessStartInfo you need to use powershell option -Command so that the array would be parsed correctly (see more details in question).

Concerning your second problem use powershell commandline option -ExecutionPolicy UnRestricted

Finally you just need to change your Arguments like this:

```<code>startInfo.Arguments = String.Format("-ExecutionPolicy UnRestricted -Command &\"'{0}\\AzurePowerShellScripts\\azureVMStatusFetch.ps1' - subscriptionId {1} -resourceGroupNames {2}\"", chefRepo, subscriptionId, string.Join(',', resourceGroupNames.Select(x => "'" + x + "'")));
</code>```

or easier (for C# 7.0 or higher)

```<code>startInfo.Arguments = $"-ExecutionPolicy UnRestricted -Command &\"'{chefRepo}\\AzurePowerShellScripts\\azureVMStatusFetch.ps1' - subscriptionId {subscriptionId} -resourceGroupNames {string.Join(',', resourceGroupNames.Select(x => $"'{x}'"))}\"";
</code>```

Body:
I am writing C# code to execute a powershell script.
The powershell script has two arguments:

subscriptionId of type string

resourceGroupNames of type string[]

Problem:

When running the C# program, the resourceGroupNames that is passed a is not being read by the powershell script.

Additionally, when running the C# program, powershell prompts me a message "Do you want to run this script?" Is there anyway to suppress this alert and have the powershell script to run automatically?

Here is my code:
Note that chefRepo is the path of the powershell script.

public void DoDeploymentRTM(string chefRepo, string subscriptionId, string[] resourceGroupNames)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = @"powershell.exe";
            startInfo.Arguments = String.Format(@"& '{0}\AzurePowerShellScripts\azureVMStatusFetch.ps1' -subscriptionId {1} -resourceGroupNames {2}", chefRepo, subscriptionId, resourceGroupNames);
            startInfo.Verb = "runas";
            Process process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
        }

Body:
For passing an array as powershell argument you need to separate it's values by commas i.e. for integers you would pass e.g 1,2,3.
For string you need additional quotation marks (in case some items contain space) e.g.'first string','second string','third'.
In C# you would do this by

string.Join(',', resourceGroupNames.Select(x => "'" + x + "'"))

In order to make this approach work when calling by ProcessStartInfo you need to use powershell option -Command so that the array would be parsed correctly (see more details in question).

Concerning your second problem use powershell commandline option -ExecutionPolicy UnRestricted

Finally you just need to change your Arguments like this:

startInfo.Arguments = String.Format("-ExecutionPolicy UnRestricted -Command &\"'{0}\\AzurePowerShellScripts\\azureVMStatusFetch.ps1' - subscriptionId {1} -resourceGroupNames {2}\"", chefRepo, subscriptionId, string.Join(',', resourceGroupNames.Select(x => "'" + x + "'")));

or easier (for C# 7.0 or higher)

startInfo.Arguments = $"-ExecutionPolicy UnRestricted -Command &\"'{chefRepo}\\AzurePowerShellScripts\\azureVMStatusFetch.ps1' - subscriptionId {subscriptionId} -resourceGroupNames {string.Join(',', resourceGroupNames.Select(x => $"'{x}'"))}\"";


问:
How to query ElasticSearch with a wildcard
I'm performing the following query in ElasticSearch 7.5.2 and getting the expected results:

```<code>message:org.jooq.exception.TooManyRowsException
</code>```

But if I try like this, I get no results (even though it looks like a broader query):

```<code>message:*TooManyRowsException
</code>```

The mapping in this field is:

```<code>"messages": {
  "match": "*message",
  "match_mapping_type":"string",
  "mapping": {
    "type":"text",
    "analyzer":"custom_standard"
  }
}
</code>```

So, I think I'm misunderstanding how wildcards work in ES. Does anyone know why * is not matching "any character" in text fields?

Thanks.

By the way, I've also tried these variations with no luck:

```<code>message:*.TooManyRowsException
message:"*TooManyRowsException"
message:(*TooManyRowsException)
message:TooManyRowsException
</code>```

Reproducible example

Create the index

curl -H 'Content-Type: application/json' -XPUT localhost:9200/twitter
{
    "settings": {
        "analysis": {
            "analyzer": {
                "custom_standard": {
                    "type": "custom",
                    "tokenizer": "uax_url_email",
                    "filter": ["lowercase", "snowball", "stop"]
                }
            },
            "normalizer": {
                "custom_lowercase": {
                    "type": "custom",
                    "filter": ["lowercase"]
                }
            }
        }
    },
    "mappings": {
        "dynamic_templates": [
            {
                "messages": {
                    "match": "*message",
                    "match_mapping_type":"string",
                    "mapping": {
                        "type":"text",
                        "analyzer":"custom_standard"
                    }
                }
            }
        ]
    }
}```
</div>
</div>
</p></li>
<li><h2>Index a document</h2>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code>curl -s -H 'Content-Type: application/json' -XPOST localhost:9200/twitter/_doc
{
   "message": "org.jooq.exception.TooManyRowsException"
}</code>```

Perform a search that yields results

curl -s -H 'Content-Type: application/json' -XGET localhost:9200/twitter/_search
{
    "query": {
        "query_string": {
            "query": "message:org.jooq.exception.TooManyRowsException"
        }
    }
}```
</div>
</div>
</p></li>
<li><h2>Perform a search that doesn't yield results</h2>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code>curl -s -H 'Content-Type: application/json' -XGET localhost:9200/twitter/_search
{
    "query": {
        "query_string": {
            "query": "message:*TooManyRowsException"
        }
    }
}</code>```

答:
Ignore this, see edit 2

I think you're indeed misunderstanding how wildcards work. Can you post your complete mapping by chance? I see you're using dynamic mapping, however dynamic mapping is used to set the type of a field depending on a condition, and has nothing to do with search behaviour directly. So for example, your mapping would take all string fields whose name ends with message, and map them as text fields.

Whether that is what you want or not is hard to say, but if you're doing that specifically to allow wildcard search, you probably don't need any of that.

To perform a wildcard search, you really only need the * at the proper place in your query string.

```<code>{
    "query": {
        "query_string": {
            "query": "*.TooManyRowsException",
            "default_field" : "message",
            "allow_leading_wildcard": true
        }
    }
}
</code>```

or

```<code>{
    "query": {
        "query_string": {
            "query": "*message:.TooManyRowsException",
            "allow_leading_wildcard": true
        }
    }
}
</code>```

should match all exceptions that start with message: and end with .TooManyRowsExceptions. You may also want to set the default_field to messages. More info on that can be found here. Additionaly, a query_string query does alot more than just allow for wildcard search. It analyses your query, and parses things like AND or OR. Like @Gabriel mentioned, if all you want is wildcard search, a wildcard query could be a better option for you:

```<code>{
    "query": {
        "wildcard": {
            "message": {
                "value": "*.TooManyRowsException",
            }
        }
    }
}
</code>```

Edit: Changed query examples base on feedback

Edit2: Your query is indeed correct. The problem, it seems, is your custom analyzer. The query string matches on the analyzed field, and your uax_email_analyzer is based on the standard analyzer:

```<code>{
  "analyzer": "custom_standard",
  "text": "org.jooq.exception.TooManyRowsException"
}
</code>```

returns

```<code>{
  "tokens" : [
    {
      "token" : "org.jooq.exception.toomanyrowsexcept",
      "start_offset" : 0,
      "end_offset" : 39,
      "type" : "<ALPHANUM>",
      "position" : 0
    }
  ]
}
</code>```

Therefore, your inital query will not match, while

```<code>{
    "query": {
        "query_string": {
            "query": "message:*org.jooq.exception.toomanyrowsexcept"
        }
    }
}
</code>```

actually returns a match. I would probably use a different analyzer for a field like an exception message, but alternatively you could also send your query text through the analyzer first.

Body:
I'm performing the following query in ElasticSearch 7.5.2 and getting the expected results:

message:org.jooq.exception.TooManyRowsException

But if I try like this, I get no results (even though it looks like a broader query):

message:*TooManyRowsException

The mapping in this field is:

"messages": {
  "match": "*message",
  "match_mapping_type":"string",
  "mapping": {
    "type":"text",
    "analyzer":"custom_standard"
  }
}

So, I think I'm misunderstanding how wildcards work in ES. Does anyone know why * is not matching "any character" in text fields?

Thanks.

By the way, I've also tried these variations with no luck:

message:*.TooManyRowsException
message:"*TooManyRowsException"
message:(*TooManyRowsException)
message:TooManyRowsException

Reproducible example

Create the index

curl -H 'Content-Type: application/json' -XPUT localhost:9200/twitter
{
    "settings": {
        "analysis": {
            "analyzer": {
                "custom_standard": {
                    "type": "custom",
                    "tokenizer": "uax_url_email",
                    "filter": ["lowercase", "snowball", "stop"]
                }
            },
            "normalizer": {
                "custom_lowercase": {
                    "type": "custom",
                    "filter": ["lowercase"]
                }
            }
        }
    },
    "mappings": {
        "dynamic_templates": [
            {
                "messages": {
                    "match": "*message",
                    "match_mapping_type":"string",
                    "mapping": {
                        "type":"text",
                        "analyzer":"custom_standard"
                    }
                }
            }
        ]
    }
}

Index a document

curl -s -H 'Content-Type: application/json' -XPOST localhost:9200/twitter/_doc
{
   "message": "org.jooq.exception.TooManyRowsException"
}

Perform a search that yields results

curl -s -H 'Content-Type: application/json' -XGET localhost:9200/twitter/_search
{
    "query": {
        "query_string": {
            "query": "message:org.jooq.exception.TooManyRowsException"
        }
    }
}

Perform a search that doesn't yield results

curl -s -H 'Content-Type: application/json' -XGET localhost:9200/twitter/_search
{
    "query": {
        "query_string": {
            "query": "message:*TooManyRowsException"
        }
    }
}

Body:
Ignore this, see edit 2

I think you're indeed misunderstanding how wildcards work. Can you post your complete mapping by chance? I see you're using dynamic mapping, however dynamic mapping is used to set the type of a field depending on a condition, and has nothing to do with search behaviour directly. So for example, your mapping would take all string fields whose name ends with message, and map them as text fields.

Whether that is what you want or not is hard to say, but if you're doing that specifically to allow wildcard search, you probably don't need any of that.

To perform a wildcard search, you really only need the * at the proper place in your query string.

{
    "query": {
        "query_string": {
            "query": "*.TooManyRowsException",
            "default_field" : "message",
            "allow_leading_wildcard": true
        }
    }
}

or

{
    "query": {
        "query_string": {
            "query": "*message:.TooManyRowsException",
            "allow_leading_wildcard": true
        }
    }
}

should match all exceptions that start with message: and end with .TooManyRowsExceptions. You may also want to set the default_field to messages. More info on that can be found here. Additionaly, a query_string query does alot more than just allow for wildcard search. It analyses your query, and parses things like AND or OR. Like @Gabriel mentioned, if all you want is wildcard search, a wildcard query could be a better option for you:

{
    "query": {
        "wildcard": {
            "message": {
                "value": "*.TooManyRowsException",
            }
        }
    }
}

Edit: Changed query examples base on feedback

Edit2: Your query is indeed correct. The problem, it seems, is your custom analyzer. The query string matches on the analyzed field, and your uax_email_analyzer is based on the standard analyzer:

{
  "analyzer": "custom_standard",
  "text": "org.jooq.exception.TooManyRowsException"
}

returns

{
  "tokens" : [
    {
      "token" : "org.jooq.exception.toomanyrowsexcept",
      "start_offset" : 0,
      "end_offset" : 39,
      "type" : "<ALPHANUM>",
      "position" : 0
    }
  ]
}

Therefore, your inital query will not match, while

{
    "query": {
        "query_string": {
            "query": "message:*org.jooq.exception.toomanyrowsexcept"
        }
    }
}

actually returns a match. I would probably use a different analyzer for a field like an exception message, but alternatively you could also send your query text through the analyzer first.


问:
How to launch Chrome from Visual Studio code?
I am using Visual studio code for front end works. How can we launch Chrome or any browsers in debugging mode or run the html file from Visual Studio Code? </p>

答:
On a MacBook Pro, I right-click on the index.html file and select Open With Live Server
open with live server in vscode</p>


问:
How to deal with this error? 'Index signature is missing in type...'
I am trying to enrich this very nice tutorial from Josh Hicks

https://medium.com/@joshblf/dynamic-nested-reactive-forms-in-angular-654c1d4a769a

by adding some FormGroups and FormArrays, but in the form-model class

```<code>export class TeamForm {

  group1 = new FormGroup(new MyGroupForm(new MyGroup()));

  constructor(team: Team) {

    if (team.group1) {
      this.group1.setValue(team.group1);
    }
  }
}

</code>```

this line

```<code>group1 = new FormGroup(new MyGroupForm(new MyGroup()));
</code>```

returns the below error

```<code>Argument of type 'MyGroupForm' is not assignable to parameter of type '{ [key: string]: AbstractControl; }'.
Index signature is missing in type 'MyGroupForm'.
</code>```

Here is the MyGroupForm class

```<code>import { FormControl, Validators } from "@angular/forms";
import { MyGroup } from "./mygroup.model";

export class MyGroupForm {
  Input1 = new FormControl();
  Input2 = new FormControl();

  constructor(groupValue: MyGroup) {

    this.Input1.setValue(groupValue.Input1);
    this.Input1.setValidators([Validators.required]);

    this.Input2.setValue(groupValue.Input2);
  }
}
</code>```

and this is the MyGroup class

```<code>export class MyGroup {
  Input1: string;
  Input2: string;

  constructor(value?) {
    if (value) {
      this.Input1 = value.Input1;
      this.Input2 = value.Input2;
    }
  }
}
</code>```

The same code in stackblitz, returns the same error in the code editor, but builds fine!

Now, here is the weird thing!

If I replace the dot(.) in this filename
mycontrol-form.model.ts
 for a comma(,) like this: mycontrol-form,model.ts
the error disappears. But this only in stackblitz!

https://stackblitz.com/edit/form-nested-formarray-with-service

Apparently I'm doing something wrong, and I would much appreciate a little help with this issue...

答:
Today I learned how to implement index signatures in Classes. What I was missing is that I hadn't defined any type for the declared variables in the class. So, in my case the solution was as simple as this:

```<code>export class MyGroupForm  {

  Input1: FormControl = new FormControl();
  Input2: FormControl = new FormControl();
}
</code>```

Now, if we want to define the general model for our objects we create a type interface and we implement it in our class like this:

```<code>interface IndexSignature {
  [key: string]: FormControl;
}

export class MyGroupForm implements IndexSignature {
  [key: string]: FormControl;

  Input1 = new FormControl();
  Input2 = new FormControl();
}
</code>```

if our objects are of more than one type we can declare them like so:

```<code>interface IndexSignature {
  [key: string]: FormControl | FormArray;
}

export class MyGroupForm implements IndexSignature {
  [key: string]: FormControl | FormArray;

  Input1 = new FormControl();
  Array1 = new FormArray([]);
}
</code>```

or in this specific case where both FormControl and FormArray are of type AbstractControl we just define this type:

```<code>interface IndexSignature {
  [key: string]: AbstractControl;
}

export class MyGroupForm implements IndexSignature {
  [key: string]: AbstractControl;

  Input1 = new FormControl();
  Array1 = new FormArray([]);
}
</code>```

This is my understanding of index signatures. If anyone wants to add or correct anything, feel free to do so...

Body:
I am trying to enrich this very nice tutorial from Josh Hicks

https://medium.com/@joshblf/dynamic-nested-reactive-forms-in-angular-654c1d4a769a

by adding some FormGroups and FormArrays, but in the form-model class

export class TeamForm {

  group1 = new FormGroup(new MyGroupForm(new MyGroup()));

  constructor(team: Team) {

    if (team.group1) {
      this.group1.setValue(team.group1);
    }
  }
}

this line

group1 = new FormGroup(new MyGroupForm(new MyGroup()));

returns the below error

Argument of type 'MyGroupForm' is not assignable to parameter of type '{ [key: string]: AbstractControl; }'.
Index signature is missing in type 'MyGroupForm'.

Here is the MyGroupForm class

import { FormControl, Validators } from "@angular/forms";
import { MyGroup } from "./mygroup.model";

export class MyGroupForm {
  Input1 = new FormControl();
  Input2 = new FormControl();

  constructor(groupValue: MyGroup) {

    this.Input1.setValue(groupValue.Input1);
    this.Input1.setValidators([Validators.required]);

    this.Input2.setValue(groupValue.Input2);
  }
}

and this is the MyGroup class

export class MyGroup {
  Input1: string;
  Input2: string;

  constructor(value?) {
    if (value) {
      this.Input1 = value.Input1;
      this.Input2 = value.Input2;
    }
  }
}

The same code in stackblitz, returns the same error in the code editor, but builds fine!

Now, here is the weird thing!

If I replace the dot(.) in this filename
mycontrol-form.model.ts
 for a comma(,) like this: mycontrol-form,model.ts
the error disappears. But this only in stackblitz!

https://stackblitz.com/edit/form-nested-formarray-with-service

Apparently I'm doing something wrong, and I would much appreciate a little help with this issue...

Body:
Today I learned how to implement index signatures in Classes. What I was missing is that I hadn't defined any type for the declared variables in the class. So, in my case the solution was as simple as this:

export class MyGroupForm  {

  Input1: FormControl = new FormControl();
  Input2: FormControl = new FormControl();
}

Now, if we want to define the general model for our objects we create a type interface and we implement it in our class like this:

interface IndexSignature {
  [key: string]: FormControl;
}

export class MyGroupForm implements IndexSignature {
  [key: string]: FormControl;

  Input1 = new FormControl();
  Input2 = new FormControl();
}

if our objects are of more than one type we can declare them like so:

interface IndexSignature {
  [key: string]: FormControl | FormArray;
}

export class MyGroupForm implements IndexSignature {
  [key: string]: FormControl | FormArray;

  Input1 = new FormControl();
  Array1 = new FormArray([]);
}

or in this specific case where both FormControl and FormArray are of type AbstractControl we just define this type:

interface IndexSignature {
  [key: string]: AbstractControl;
}

export class MyGroupForm implements IndexSignature {
  [key: string]: AbstractControl;

  Input1 = new FormControl();
  Array1 = new FormArray([]);
}

This is my understanding of index signatures. If anyone wants to add or correct anything, feel free to do so...


问:
How to write a dynamic django orm queryset based on the filters passed?
i need to apply filters dynamically on a queryset depending on the filters passed as a json from the front end.

for ex.

if json passed is : { id:[1,2,3] }
then queryset will be : Model.objects.filter(id__in=id)

if json is passed as: { id:[1,2,3],country:['india','australia'] }

then queryset will be : Model.objects.filter(id__in=id,country__in=country)

how to achieve this dynamically?

答:
You could use an if/else statement to detect if the country list is empty:

```<code>if not country:
     Model.objects.filter(id__in=id)
else:
     Model.objects.filter(id__in=id, country__in=country)
</code>```

Edit:

A comment pointed out that the amount of filters are dynamic. So in Django .filter() returns another QuerySet and Querysets are lazily evaluated, meaning they can be chained and be used in a loop.

So using unpacking (**), we can compose the kwargs to pass to .filter().

Because the exact datatype/schema of the filters is not provided, I will use a dictionary as example, filter_dictionary. In this dictionary the key is the filter that will be used and the value will be a list.

```<code># Compose first Queryset
qs = Model.objects.all()

# Loop over dictionary
for key, value in filter_dictionary.items():

    # Use unpacking to compose kwarg
    qs.filter(**{'{0}__in'.format(key): value})

# do something with the QuerySet
</code>```

Body:
You could use an if/else statement to detect if the country list is empty:

if not country:
     Model.objects.filter(id__in=id)
else:
     Model.objects.filter(id__in=id, country__in=country)

Edit:

A comment pointed out that the amount of filters are dynamic. So in Django .filter() returns another QuerySet and Querysets are lazily evaluated, meaning they can be chained and be used in a loop.

So using unpacking (**), we can compose the kwargs to pass to .filter().

Because the exact datatype/schema of the filters is not provided, I will use a dictionary as example, filter_dictionary. In this dictionary the key is the filter that will be used and the value will be a list.

# Compose first Queryset
qs = Model.objects.all()

# Loop over dictionary
for key, value in filter_dictionary.items():

    # Use unpacking to compose kwarg
    qs.filter(**{'{0}__in'.format(key): value})

# do something with the QuerySet


问:
how to write on screen in AS3
So I am creating a module and I have a screen that I need to be able to allow the users to write questions that they have on their screens in a text box. Does anyone know how to do this?

This is the basic setup that I use for every screen:

```<code>package screens
{

import flash.filters.*;
import flash.text.*;
import mapSystem.screenSystem.*;
import mapSystem.*;
import screens.*;
import caurina.transitions.Tweener;

public class screen4 extends screenBase
{

       public function screen4(pSystem:mapManager)
       {
             super(pSystem);
             numActions = 1;

       }

     public override function onAction()
      {
             if (actionStep == 1)
             {
                   map.fID("54");
             }
       }

       public override function onEnter()
       {
             map.zoomTo("full");
       }
    }
}
</code>```

答:
For users to input text, simply create a textfield and set its "type" property to TextFieldType.INPUT. When you go to retrieve this data, just access the textFields "text" prop.

Update -

Ok = simple google search on "AS3 textField tutorial", first hit was this tutorial, which I yanked and added a couple things to for you. Its fairly basic and well documented, so, depending on your level of experience, should prove illuminating.

```<code>//Creating the textfield object and naming it "myTextField"
var myTextField:TextField = new TextField();

//Here we add the new textfield instance to the stage with addchild()
addChild(myTextField);

//Here we define some properties for our text field, starting with giving it some text to contain.
//A width, x and y coordinates.
myTextField.text = "input text here";
myTextField.width = 250;
myTextField.x = 25;
myTextField.y = 25;

//@b99 addition
myTextField.type = TextFieldType.INPUT;

//This is the section for our text styling, first we create a TextFormat instance naming it myFormat
var myFormat:TextFormat = new TextFormat();

//Giving the format a hex decimal color code
myFormat.color = 0xAA0000;

//Adding some bigger text size
myFormat.size = 24;

//Last text style is to make it italic.
myFormat.italic = true;

//Now the most important thing for the textformat, we need to add it to the myTextField with setTextFormat.
myTextField.setTextFormat(myFormat);
</code>```

Hope that helps!

ContentLicense: CC BY-SA 3.0

Title: how to write on screen in AS3

Body:
So I am creating a module and I have a screen that I need to be able to allow the users to write questions that they have on their screens in a text box. Does anyone know how to do this?

This is the basic setup that I use for every screen:

package screens
{

import flash.filters.*;
import flash.text.*;
import mapSystem.screenSystem.*;
import mapSystem.*;
import screens.*;
import caurina.transitions.Tweener;

public class screen4 extends screenBase
{

       public function screen4(pSystem:mapManager)
       {
             super(pSystem);
             numActions = 1;

       }

     public override function onAction()
      {
             if (actionStep == 1)
             {
                   map.fID("54");
             }
       }

       public override function onEnter()
       {
             map.zoomTo("full");
       }
    }
}

Body:
For users to input text, simply create a textfield and set its "type" property to TextFieldType.INPUT. When you go to retrieve this data, just access the textFields "text" prop.

Update -

Ok = simple google search on "AS3 textField tutorial", first hit was this tutorial, which I yanked and added a couple things to for you. Its fairly basic and well documented, so, depending on your level of experience, should prove illuminating.

//Creating the textfield object and naming it "myTextField"
var myTextField:TextField = new TextField();

//Here we add the new textfield instance to the stage with addchild()
addChild(myTextField);

//Here we define some properties for our text field, starting with giving it some text to contain.
//A width, x and y coordinates.
myTextField.text = "input text here";
myTextField.width = 250;
myTextField.x = 25;
myTextField.y = 25;

//@b99 addition
myTextField.type = TextFieldType.INPUT;

//This is the section for our text styling, first we create a TextFormat instance naming it myFormat
var myFormat:TextFormat = new TextFormat();

//Giving the format a hex decimal color code
myFormat.color = 0xAA0000;

//Adding some bigger text size
myFormat.size = 24;

//Last text style is to make it italic.
myFormat.italic = true;

//Now the most important thing for the textformat, we need to add it to the myTextField with setTextFormat.
myTextField.setTextFormat(myFormat);

Hope that helps!


问:
how to add date like input type date to td table inside a JS function?
for this example

  $("#add").click(function () {
      var html = "
";
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html +=
        '<button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Insert</button>	';
      html += "
";
      $("#user_data tbody").prepend(html);
    });```

if you could help me in this regard it will be appreciate it

答:
If i understand you correctly, you can make it like that.

```<code>$("#add").click(function () {
    var html = `
   <td contenteditable id="data1">
    <input type="date" id="start" name="trip-start" value="2018-07-22" min="2018-01-01" max="2018-12-31">
   </td>
   <td contenteditable id="data2"></td>
   <td contenteditable id="data3"></td>
   <td contenteditable id="data4"></td>
   <td contenteditable id="data5"></td>
   <td contenteditable id="data6"></td>
   <td contenteditable id="data7"></td>
   <td contenteditable id="data8"></td>
   <td contenteditable id="data9"></td>
   <td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Insert</button></td>
   </tr>
   `;
    $("#user_data tbody").prepend(html);
  });
</code>```

You can write inside `` as you write in HTML

Body:
for this example

  $("#add").click(function () {
      var html = "
";
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html += '	';
      html +=
        '<button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Insert</button>	';
      html += "
";
      $("#user_data tbody").prepend(html);
    });

if you could help me in this regard it will be appreciate it

Body:
If i understand you correctly, you can make it like that.

$("#add").click(function () {
    var html = `
   <td contenteditable id="data1">
    <input type="date" id="start" name="trip-start" value="2018-07-22" min="2018-01-01" max="2018-12-31">
   </td>
   <td contenteditable id="data2"></td>
   <td contenteditable id="data3"></td>
   <td contenteditable id="data4"></td>
   <td contenteditable id="data5"></td>
   <td contenteditable id="data6"></td>
   <td contenteditable id="data7"></td>
   <td contenteditable id="data8"></td>
   <td contenteditable id="data9"></td>
   <td><button type="button" name="insert" id="insert" class="btn btn-success btn-xs">Insert</button></td>
   </tr>
   `;
    $("#user_data tbody").prepend(html);
  });

You can write inside `` as you write in HTML


问:
How to make time ago from json in flutter
Is it possible if I have json with the timestamp like this

```<code>{
"modified": "2018-11-14T16:25:21",
}

</code>```

and I want to make time ago in flutter. eg.5 minutes ago

答:
```<code>import 'package:simple_moment/simple_moment.dart';

main() {
  var datetoCompare = new Duration(seconds: 21,minute : 25, hour:16); //And so with month, year and Day.
  var dateForComparison = new DateTime.now().add(datetoCompare);
  var moment = new Moment.now();
  print(moment.from(dateForComparison));
}
</code>```

This Package helps in showing relative time in flutter.

Simple Moment package -

https://pub.dev/packages/simple_moment#-readme-tab-

Body:
Is it possible if I have json with the timestamp like this

{
"modified": "2018-11-14T16:25:21",
}

and I want to make time ago in flutter. eg.5 minutes ago

Body:
import 'package:simple_moment/simple_moment.dart';

main() {
  var datetoCompare = new Duration(seconds: 21,minute : 25, hour:16); //And so with month, year and Day.
  var dateForComparison = new DateTime.now().add(datetoCompare);
  var moment = new Moment.now();
  print(moment.from(dateForComparison));
}

This Package helps in showing relative time in flutter.

Simple Moment package -

https://pub.dev/packages/simple_moment#-readme-tab-


问:
.transition modifier in SwiftUI
I want the second rectangle (green) come up and down over the first rectangle (red) when I press the button

```<code>struct ContentView: View {

    @State var visible = false

    var body: some View {
        return HStack {
            Button("button") {
                self.visible.toggle()
            }
            ZStack {

                Rectangle()
                    .frame(width: 100, height: 100)
                    .foregroundColor(Color.red)

                if visible {
                    Rectangle()
                        .frame(width: 100, height: 100)
                        .foregroundColor(Color.green)
                        .transition(.move(edge: .bottom))
                        .animation(.linear(duration: 2))
                }

            }
        }
    }
}
</code>```

When the green rectangle appears it comes up over the red rectangle, but when it disappears the the moving transition appears behind the red rectangle.

答:
Just add the zIndex:

```<code>struct ContentView: View {

    @State var visible = false

    var body: some View {
        return HStack {
            Button("button") {
                self.visible.toggle()
            }
            ZStack {

                Rectangle()
                    .frame(width: 100, height: 100)
                    .foregroundColor(Color.red)

                if visible {
                    Rectangle()
                        .frame(width: 100, height: 100)
                        .foregroundColor(Color.green)
                        .transition(.move(edge: .bottom))
                        .animation(.linear(duration: 2))
                        .zIndex(1)
                }

            }
        }
    }
}
</code>```

Title: .transition modifier in SwiftUI

Body:
I want the second rectangle (green) come up and down over the first rectangle (red) when I press the button

struct ContentView: View {

    @State var visible = false

    var body: some View {
        return HStack {
            Button("button") {
                self.visible.toggle()
            }
            ZStack {

                Rectangle()
                    .frame(width: 100, height: 100)
                    .foregroundColor(Color.red)

                if visible {
                    Rectangle()
                        .frame(width: 100, height: 100)
                        .foregroundColor(Color.green)
                        .transition(.move(edge: .bottom))
                        .animation(.linear(duration: 2))
                }

            }
        }
    }
}

When the green rectangle appears it comes up over the red rectangle, but when it disappears the the moving transition appears behind the red rectangle.

Body:
Just add the zIndex:

struct ContentView: View {

    @State var visible = false

    var body: some View {
        return HStack {
            Button("button") {
                self.visible.toggle()
            }
            ZStack {

                Rectangle()
                    .frame(width: 100, height: 100)
                    .foregroundColor(Color.red)

                if visible {
                    Rectangle()
                        .frame(width: 100, height: 100)
                        .foregroundColor(Color.green)
                        .transition(.move(edge: .bottom))
                        .animation(.linear(duration: 2))
                        .zIndex(1)
                }

            }
        }
    }
}


问:
Unknown Column in Where Clause When Using the Variable Created with AS
The question is about using a column (which is created in query) as where clause criteria.

There are 2 tables named transactions and transactionmovements.

In transaction, there are unique info for transaction like date, counterparty etc.

In transactionmovements, there are articles which is used in transaction. Such as product, quantity, price, etc. And transactionmovements has a 'transaction' column which references to transactions.id shows which transaction the movement belongs.

In the query, I created a totalPrice value with sum of quantity*price of each movement that belongs to a transaction.

Everything works perfectly but the last parameter of WHERE clause. If I delete "AND
totalPrice > 10" part, it gives me everything including totalPrice and totalQuantity of a transaction.
But if I place "AND totalPrice > 10" to the end, it returns following error:

-#1054 - Unknown column 'totalPrice' in 'where clause'

```<code>SELECT
`transactions`.id,
`transactions`.type,
`transactions`.date,
`transactions`.VAT,
`transactions`.currency,
`companies`.name AS counterparty,
COALESCE
(sum(`transactionmovements`.price*`transactionmovements`.quantity)
+(`transactions`.shippingQuantity*`transactions`.shippingPrice)) as totalPrice,
COALESCE
(sum(`transactionmovements`.quantity)) as totalQuantity
FROM
`transactions`
LEFT JOIN `companies` ON `transactions`.counterparty = `companies`.id
LEFT JOIN `transactionmovements` ON `transactions`.id=`transactionmovements`.transaction
WHERE ( `transactions`.type = 'p' OR `transactions`.type = 'r' OR `transactions`.type = 's' OR `transactions`.type = 't')
AND
(`transactions`.date BETWEEN IFNULL('','1900-01-01') AND IFNULL('2020-02-14',NOW()))
AND
totalPrice > 10
GROUP BY `transactions`.id
ORDER BY id desc
LIMIT 10
</code>```

I tried using the whole math operation in WHERE clause, but no gains. I tried to use HAVING with WHERE but couldn't manage it.

The last solution I have is running it without filtering by totalPrice and store it into a php array. Then filter in array, but there I can't use LIMIT so array will be very big.

答:
As Thomas Jeriko suggested in comments, creating a view was exactly what I need.
First I create a virtual table with Create View.

```<code>CREATE VIEW transactionreportview
    AS SELECT
        transactions.id id,
        transactions.type type,
        transactions.date date,
        transactions.VAT VAT,
        transactions.currency currency,
        transactions.counterparty counterparty,
        (SUM(transactionmovements.price*transactionmovements.quantity)+transactions.shippingQuantity*transactions.shippingPrice) totalPrice,
        SUM(transactionmovements.quantity) totalQuantity
    FROM transactions transactions, transactionmovements transactionmovements
    WHERE transactions.id = transactionmovements.transaction
    GROUP BY transactions.id;
</code>```

While the virtual table acts like a simple mysql table, I ran a new query in the table

```<code>SELECT * FROM transactionReportView WHERE ..."
</code>```

Then after finishing my work with the virtual table, drop it

```<code>DROP VIEW transactionreportview
</code>```

Body:
The question is about using a column (which is created in query) as where clause criteria.

There are 2 tables named transactions and transactionmovements.

In transaction, there are unique info for transaction like date, counterparty etc.

In transactionmovements, there are articles which is used in transaction. Such as product, quantity, price, etc. And transactionmovements has a 'transaction' column which references to transactions.id shows which transaction the movement belongs.

In the query, I created a totalPrice value with sum of quantity*price of each movement that belongs to a transaction.

Everything works perfectly but the last parameter of WHERE clause. If I delete "AND
totalPrice > 10" part, it gives me everything including totalPrice and totalQuantity of a transaction.
But if I place "AND totalPrice > 10" to the end, it returns following error:

-#1054 - Unknown column 'totalPrice' in 'where clause'

SELECT
`transactions`.id,
`transactions`.type,
`transactions`.date,
`transactions`.VAT,
`transactions`.currency,
`companies`.name AS counterparty,
COALESCE
(sum(`transactionmovements`.price*`transactionmovements`.quantity)
+(`transactions`.shippingQuantity*`transactions`.shippingPrice)) as totalPrice,
COALESCE
(sum(`transactionmovements`.quantity)) as totalQuantity
FROM
`transactions`
LEFT JOIN `companies` ON `transactions`.counterparty = `companies`.id
LEFT JOIN `transactionmovements` ON `transactions`.id=`transactionmovements`.transaction
WHERE ( `transactions`.type = 'p' OR `transactions`.type = 'r' OR `transactions`.type = 's' OR `transactions`.type = 't')
AND
(`transactions`.date BETWEEN IFNULL('','1900-01-01') AND IFNULL('2020-02-14',NOW()))
AND
totalPrice > 10
GROUP BY `transactions`.id
ORDER BY id desc
LIMIT 10

I tried using the whole math operation in WHERE clause, but no gains. I tried to use HAVING with WHERE but couldn't manage it.

The last solution I have is running it without filtering by totalPrice and store it into a php array. Then filter in array, but there I can't use LIMIT so array will be very big.

Body:
As Thomas Jeriko suggested in comments, creating a view was exactly what I need.
First I create a virtual table with Create View.

CREATE VIEW transactionreportview
    AS SELECT
        transactions.id id,
        transactions.type type,
        transactions.date date,
        transactions.VAT VAT,
        transactions.currency currency,
        transactions.counterparty counterparty,
        (SUM(transactionmovements.price*transactionmovements.quantity)+transactions.shippingQuantity*transactions.shippingPrice) totalPrice,
        SUM(transactionmovements.quantity) totalQuantity
    FROM transactions transactions, transactionmovements transactionmovements
    WHERE transactions.id = transactionmovements.transaction
    GROUP BY transactions.id;

While the virtual table acts like a simple mysql table, I ran a new query in the table

SELECT * FROM transactionReportView WHERE ..."

Then after finishing my work with the virtual table, drop it

DROP VIEW transactionreportview


问:
Jenkinsfile pipeline stage error in gcloud
I have the below pipeline.

```<code>pipeline {
    agent any

    environment {
        PROJECT_ID = "*****"
        IMAGE = "gcr.io/$PROJECT_ID/node-app"
        BRANCH_NAME_NORMALIZED = "${BRANCH_NAME.toLowerCase().replace(" / ", "
        _ ")}"
    }

    stages {
        stage('Build') {
            steps {
                sh ' docker build -t ${IMAGE}:${BRANCH_NAME_NORMALIZED} . '

            }
        }
        stage('Push') {
            steps {
                withCredentials([file(credentialsId: 'jenkins_secret', variable: 'GC_KEY')]) {
                    sh("gcloud auth activate-service-account --key-file=${GC_KEY}")
                }
                sh ' gcloud auth configure-docker  '
                sh ' docker push $IMAGE:${BRANCH_NAME_NORMALIZED} '
            }
        }
        stage('Deploy') {
            steps {
                withDockerContainer(image: "gcr.io/google.com/cloudsdktool/cloud-sdk", toolName: 'latest') {
                    withCredentials([file(credentialsId: 'jenkins_secret', variable: 'GC_KEY')]) {
                        sh("gcloud auth activate-service-account --key-file=${GC_KEY}")
                        sh("gcloud container clusters get-credentials k8s --region us-central1 --project ${DEV_PROJECT}")
                        sh("kubectl get pods")

                    }
                }
            }
        }
    }
}
</code>```

In Deploy stage it gives the following error :

gcloud auth activate-service-account --key-file=****
  WARNING: Could not setup log file in /.config/gcloud/logs, (Error: Could not create directory [/.config/gcloud/logs/2020.02.05]: Permission denied.

Please verify that you have permissions to write to the parent directory.)
  ERROR: (gcloud.auth.activate-service-account) Could not create directory [/.config/gcloud]: Permission denied.
  Please verify that you have permissions to write to the parent directory.

I can't understand where this command wants to create a directory, docker container or in Host machine?
Have you got any similar problem ?

答:
A better approach would be to Login to GKE via Kubernetes service account with token and using a kubeconfig file instead of activating a google service account. </p>

<p>This has several advantages including Kubernetes RBAC support, controlling blast radius should your credentials be compromised, etc. You can read more about using RBAC Authorization here. </p>

Body:
I have the below pipeline.

pipeline {
    agent any

    environment {
        PROJECT_ID = "*****"
        IMAGE = "gcr.io/$PROJECT_ID/node-app"
        BRANCH_NAME_NORMALIZED = "${BRANCH_NAME.toLowerCase().replace(" / ", "
        _ ")}"
    }

    stages {
        stage('Build') {
            steps {
                sh ' docker build -t ${IMAGE}:${BRANCH_NAME_NORMALIZED} . '

            }
        }
        stage('Push') {
            steps {
                withCredentials([file(credentialsId: 'jenkins_secret', variable: 'GC_KEY')]) {
                    sh("gcloud auth activate-service-account --key-file=${GC_KEY}")
                }
                sh ' gcloud auth configure-docker  '
                sh ' docker push $IMAGE:${BRANCH_NAME_NORMALIZED} '
            }
        }
        stage('Deploy') {
            steps {
                withDockerContainer(image: "gcr.io/google.com/cloudsdktool/cloud-sdk", toolName: 'latest') {
                    withCredentials([file(credentialsId: 'jenkins_secret', variable: 'GC_KEY')]) {
                        sh("gcloud auth activate-service-account --key-file=${GC_KEY}")
                        sh("gcloud container clusters get-credentials k8s --region us-central1 --project ${DEV_PROJECT}")
                        sh("kubectl get pods")

                    }
                }
            }
        }
    }
}

In Deploy stage it gives the following error :

gcloud auth activate-service-account --key-file=****
  WARNING: Could not setup log file in /.config/gcloud/logs, (Error: Could not create directory [/.config/gcloud/logs/2020.02.05]: Permission denied.

Please verify that you have permissions to write to the parent directory.)
  ERROR: (gcloud.auth.activate-service-account) Could not create directory [/.config/gcloud]: Permission denied.
  Please verify that you have permissions to write to the parent directory.

I can't understand where this command wants to create a directory, docker container or in Host machine?
Have you got any similar problem ?

Body:
A better approach would be to Login to GKE via Kubernetes service account with token and using a kubeconfig file instead of activating a google service account.

This has several advantages including Kubernetes RBAC support, controlling blast radius should your credentials be compromised, etc. You can read more about using RBAC Authorization here.


问:
setting div position before animation in react-reveal Fade in animation
I am trying to do a simple slide in and slide out animation using react-reveal. This is my code snippet:

```<code>{glanceDataFetching ? null : (<HelperBtn onClick={() => toggleShowHelper()}>{ showHelper ?  (<span>></span>) : (<span><</span>)}</HelperBtn>)}
    <Slide right duration={2000} when={showHelper}>
      <InfoBlockContainer>
        <Infotext>
          <span className="mr-1">🛈</span>
          <span>For viewing cataract/retina status, report or for updating call status/visit status, click on the respective cell</span>
        </Infotext>
      </InfoBlockContainer>
      </Slide>
</code>```

Here InfoBlockContainer is a styled component with following styles:

```<code>display: inline-block;
width: 250px;
height: 65px;
border: 1px solid #36A2EB;
background-color: lightblue;
border-radius: 4px;
position: absolute;
bottom: 0;
right: 5px;
padding: 5px;
</code>```

And this is the animation result I am getting (Intentionally added a duration of 2sec to show case the issue):

As it can be seen that after it slides in it moves downwards a bit as per the css and places itself to it's correct position and same when it slides out. Which doesn't look smoother at all. How can I fix it? Or start the animation of div with the position it is supposed to be?

答:
Most probably as InfoBlockContainer is absolute positioned at 0 from bottom, when sliding in and out it creates overflow on containing block. As a result scroll bars are produced. When InfoBlockContainer comes in, scrollbars are removed so it moves downward a bit.

To fix, I suggest to add overflow: hidden to nearest absolute positioned containing block. If all containers of the Slide are not absolute positioned, add overflow: hidden to the body.

Here is a sample. If you remove overflow: hidden from the body element, you'll see the same placement change like you're expecting.

Body:
I am trying to do a simple slide in and slide out animation using react-reveal. This is my code snippet:

{glanceDataFetching ? null : (<HelperBtn onClick={() => toggleShowHelper()}>{ showHelper ?  (>) : (<)}</HelperBtn>)}
    <Slide right duration={2000} when={showHelper}>
      <InfoBlockContainer>
        <Infotext>
          🛈
          For viewing cataract/retina status, report or for updating call status/visit status, click on the respective cell
        </Infotext>
      </InfoBlockContainer>
      </Slide>

Here InfoBlockContainer is a styled component with following styles:

display: inline-block;
width: 250px;
height: 65px;
border: 1px solid #36A2EB;
background-color: lightblue;
border-radius: 4px;
position: absolute;
bottom: 0;
right: 5px;
padding: 5px;

And this is the animation result I am getting (Intentionally added a duration of 2sec to show case the issue):

As it can be seen that after it slides in it moves downwards a bit as per the css and places itself to it's correct position and same when it slides out. Which doesn't look smoother at all. How can I fix it? Or start the animation of div with the position it is supposed to be?


问:
ASP.NET MVC3 Code-First Error- attempting to update entity
I've checked this question and it seems to be related to what I need, but does not answer it exactly.

I have an entity (Sql Compact using EF Code First via MVC3- if that wasn't clear from the title) for an "Issue" (generic issue tracking, just for my own education understanding of how MVC3 works).  The Issue class has a CreatedBy property (Int reference to a User who Created the Issue) and a CreatedDate property (DateTime).  When I use the scaffolded code to update (modified only to prevent some updated date fields from being modified by the user):

```<code>        if (ModelState.IsValid)
        {
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
</code>```

I receive the error mentioned in the linked question (conversion of a datetime2 data type to a datetime data type etc., etc.,)

When I step through the code, it appears my CreatedBy and CreatedDate properties are not contained in the instance of issue that the controller is passing around.  When I try to fix that by grabbing another copy of the issue from the db, and updating those to values:

```<code>        var startingIssue = db.Issues.Find(issue.IssueId);
        if (ModelState.IsValid)
        {
            if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
            if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
</code>```

I get the concurrency violation: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

So, how do I get EF to see the date which is already set in the DB (so it doesn't try to update the CreatedDate to 1/1/0001) without violating concurrency?

Edit
Okay... I found it.  I was, apparently, looking for @Html.HiddenFor(model => model.[property]) and adding the editor to the view anyway.  That seems a little silly and round-about to me, but it does work without having to add custom code to detach one object and substitute an updated one.

答:
The short answer is that you've already loaded the entity into the context with the Find and you cannot later attach another one.

You are left with two options:

Detach the first instance, then attach the second

Copy the fields from the second instance to the first

I'll share code for the first option. First, add a Detach method to your DbContext implementation:

```<code>public void Detach(object entity)
{
    var objectContext = ((IObjectContextAdapter)this).ObjectContext;
    objectContext.Detach(entity);
}
</code>```

Then call Detach instead of setting the variable to null

```<code>var startingIssue = db.Issues.Find(issue.IssueId);
if (ModelState.IsValid)
{
    if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
    if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
    issue.LastActivity = (DateTime?)DateTime.Now.Date;
    if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;

    // startingIssue = null;
    db.Detach(startingIssue);

    db.Entry(issue).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
}
</code>```

Body:
I've checked this question and it seems to be related to what I need, but does not answer it exactly.

I have an entity (Sql Compact using EF Code First via MVC3- if that wasn't clear from the title) for an "Issue" (generic issue tracking, just for my own education understanding of how MVC3 works).  The Issue class has a CreatedBy property (Int reference to a User who Created the Issue) and a CreatedDate property (DateTime).  When I use the scaffolded code to update (modified only to prevent some updated date fields from being modified by the user):

        if (ModelState.IsValid)
        {
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

I receive the error mentioned in the linked question (conversion of a datetime2 data type to a datetime data type etc., etc.,)

When I step through the code, it appears my CreatedBy and CreatedDate properties are not contained in the instance of issue that the controller is passing around.  When I try to fix that by grabbing another copy of the issue from the db, and updating those to values:

        var startingIssue = db.Issues.Find(issue.IssueId);
        if (ModelState.IsValid)
        {
            if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
            if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

I get the concurrency violation: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

So, how do I get EF to see the date which is already set in the DB (so it doesn't try to update the CreatedDate to 1/1/0001) without violating concurrency?

Edit
Okay... I found it.  I was, apparently, looking for @Html.HiddenFor(model => model.[property]) and adding the editor to the view anyway.  That seems a little silly and round-about to me, but it does work without having to add custom code to detach one object and substitute an updated one.

Body:
The short answer is that you've already loaded the entity into the context with the Find and you cannot later attach another one.

You are left with two options:

Detach the first instance, then attach the second

Copy the fields from the second instance to the first

I'll share code for the first option. First, add a Detach method to your DbContext implementation:

public void Detach(object entity)
{
    var objectContext = ((IObjectContextAdapter)this).ObjectContext;
    objectContext.Detach(entity);
}

Then call Detach instead of setting the variable to null

var startingIssue = db.Issues.Find(issue.IssueId);
if (ModelState.IsValid)
{
    if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
    if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
    issue.LastActivity = (DateTime?)DateTime.Now.Date;
    if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;

    // startingIssue = null;
    db.Detach(startingIssue);

    db.Entry(issue).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
}


问:
Passing data from router to server file node.js express
I am trying to build a web app using node.js and I would like to pass data from my router, file which processes a form, to my server file that will actually emit events to the other user connected.

router.js

```<code>module.exports=function(app) {
    const express = require('express');
    const User = require("./public/classes/User");
    const router = express.Router();
    const {check, validationResult} = require('express-validator');
    const {matchedData} = require('express-validator/filter');

    var userlist = new Array();

    router.get('/', (req, res) => {
        res.render('index', {
            data: {},
            errors: {}
        })
    });

    router.post('/enter', [
        check('username')
            .isLength({min: 1})
            .withMessage('Username is required').trim()   //implement personalized check
    ], (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.render('index', {
                data: req.body,
                errors: errors.mapped()
            })
        }
        const data = matchedData(req)

    });
    return router;

    //MOVE TO SUPPORT
    function find(name) {
        return 1;
    }

}
</code>```

server.js

```<code>const express = require('express');
const layout = require('express-layout');
const app = express();
var server = require('http').createServer(app);
var io=require('socket.io')(server);
const routes = require('./router')(app);
const bodyParser = require('body-parser');
var fs = require("fs");

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

const middleware = [
    layout(),
    express.static(path.join(__dirname, 'public')),
    bodyParser.urlencoded(),

];

app.use(middleware);

app.use('/', routes);

app.use((req, res, next) => {
    res.status(404).send("Sorry can't find that!");
});

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

io.on('connect', onConnect);

function onConnect(socket) {
    var contents = fs.readFileSync("./public/rooms.json");
    let rooms = JSON.parse(contents);
    socket.emit('parse',rooms);
    socket.on('join',function (name, room) {
        console.log(name+" "+ room);
        socket.join(room);
        socket.user=name;
        socket.room=room;
    })
}

server.listen(3000, () => {
    console.log(`App running at http://localhost:3000`);
});
</code>```

I would like to pass the processed data of my post request to the server, how do I do that?

答:
May be you have forgot to export routes from route.js .
Use module.export = route;
in route.js file.

Body:
I am trying to build a web app using node.js and I would like to pass data from my router, file which processes a form, to my server file that will actually emit events to the other user connected.

router.js

module.exports=function(app) {
    const express = require('express');
    const User = require("./public/classes/User");
    const router = express.Router();
    const {check, validationResult} = require('express-validator');
    const {matchedData} = require('express-validator/filter');

    var userlist = new Array();

    router.get('/', (req, res) => {
        res.render('index', {
            data: {},
            errors: {}
        })
    });

    router.post('/enter', [
        check('username')
            .isLength({min: 1})
            .withMessage('Username is required').trim()   //implement personalized check
    ], (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.render('index', {
                data: req.body,
                errors: errors.mapped()
            })
        }
        const data = matchedData(req)

    });
    return router;

    //MOVE TO SUPPORT
    function find(name) {
        return 1;
    }

}

server.js

const express = require('express');
const layout = require('express-layout');
const app = express();
var server = require('http').createServer(app);
var io=require('socket.io')(server);
const routes = require('./router')(app);
const bodyParser = require('body-parser');
var fs = require("fs");

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

const middleware = [
    layout(),
    express.static(path.join(__dirname, 'public')),
    bodyParser.urlencoded(),

];

app.use(middleware);

app.use('/', routes);

app.use((req, res, next) => {
    res.status(404).send("Sorry can't find that!");
});

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

io.on('connect', onConnect);

function onConnect(socket) {
    var contents = fs.readFileSync("./public/rooms.json");
    let rooms = JSON.parse(contents);
    socket.emit('parse',rooms);
    socket.on('join',function (name, room) {
        console.log(name+" "+ room);
        socket.join(room);
        socket.user=name;
        socket.room=room;
    })
}

server.listen(3000, () => {
    console.log(`App running at http://localhost:3000`);
});

I would like to pass the processed data of my post request to the server, how do I do that?


问:
How can I check my svn connection?
How can I check my svn connection?

I just want to try to connect to server and check the status of my connection.. After that I will do something like check out and etc. well may be another way to get it?

答:
Just call http get on any SVN url like:</p>

```<code>https://username:password@server/repo
</code>```

ContentLicense: CC BY-SA 2.5

Title: How can I check my svn connection?

Body:
Just call http get on any SVN url like:

https://username:password@server/repo


问:
Why the if statement is executed in ` if [ ''=1 ] ; then echo "true"; else echo "false"; fi`?
```<code>if test-commands; then
  consequent-commands;
[elif more-test-commands; then
  more-consequents;]
[else alternate-consequents;]
fi
</code>```

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed.

Show  status of ''=1 in bash.

```<code>''=1
bash: =1: command not found
echo $?
127
</code>```

The value of status is 127, not zero. A strange statement:

```<code>if [ ''=1 ] ; then echo "true"; else echo "false"; fi
true
</code>```

Why value of status 127, not zero invoke then statement? Why can't get false in bash?

@Дмитрий Шатов

```<code>=1
bash: =1: command not found
echo $?
127
</code>```

答:
This is because it is a string comparison operation.

```<code>if [ "$a" = "$b" ]
then
    echo 'true'
else
    echo 'false'
fi
</code>```

You need to use != rather than = when comparing the two strings. This will act as the opposite of the comparison [ "$a" = "$b" ]

```<code>if [ "$a" != "$b" ]
then
    echo 'false'
else
    echo 'true'
fi
</code>```

Body:
if test-commands; then
  consequent-commands;
[elif more-test-commands; then
  more-consequents;]
[else alternate-consequents;]
fi

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed.

Show  status of ''=1 in bash.

''=1
bash: =1: command not found
echo $?
127

The value of status is 127, not zero. A strange statement:

if [ ''=1 ] ; then echo "true"; else echo "false"; fi
true

Why value of status 127, not zero invoke then statement? Why can't get false in bash?

@Дмитрий Шатов

=1
bash: =1: command not found
echo $?
127

Body:
This is because it is a string comparison operation.

if [ "$a" = "$b" ]
then
    echo 'true'
else
    echo 'false'
fi

You need to use != rather than = when comparing the two strings. This will act as the opposite of the comparison [ "$a" = "$b" ]

if [ "$a" != "$b" ]
then
    echo 'false'
else
    echo 'true'
fi


问:
Checkbox that submits form on click
I'm using Codeigniter and wants to know how I can make a checkbox that submits the form on click?

Secondly, this checkbox will be one of several checkboxes that will act as a filter like products > $20, products < $30, how do i pass it in the url? I'm thinking /1+2+3

答:
This has nothing to do with PHP, nor CodeIgniter. The solution is to submit the form in the onclick event of the element.

```<code><input type="checkbox" name="filterx" onclick="document.forms[0].submit()" />
</code>```

You can use the OnSubmit event of the form to nicely format the url, if you like.

To do this, you can

get the values of all desired elements,

build a nice url from it,

set the url using location.href = yourniceurl,

cancel the regular submit by returning false.

Note that both solutions require javascript to be enabled. So it is a good thing to have other means of submitting the form (submit button). Don't rely on submitting by pressing Enter. Opera will use the Enter key for toggling the checkbox instead of submitting the form.
If you like, you can hide the submit button using Javascript, that way, users having Javascript will have their form auto-submitted, while users without can use the button.
You will need to make sure that your server side form validator not only accepts the nice url, but the ugly url (which posts values like ?filterx=on) too.

Title: Checkbox that submits form on click

Body:
This has nothing to do with PHP, nor CodeIgniter. The solution is to submit the form in the onclick event of the element.

<input type="checkbox" name="filterx" onclick="document.forms[0].submit()" />

You can use the OnSubmit event of the form to nicely format the url, if you like.

To do this, you can

get the values of all desired elements,

build a nice url from it,

set the url using location.href = yourniceurl,

cancel the regular submit by returning false.

Note that both solutions require javascript to be enabled. So it is a good thing to have other means of submitting the form (submit button). Don't rely on submitting by pressing Enter. Opera will use the Enter key for toggling the checkbox instead of submitting the form.
If you like, you can hide the submit button using Javascript, that way, users having Javascript will have their form auto-submitted, while users without can use the button.
You will need to make sure that your server side form validator not only accepts the nice url, but the ugly url (which posts values like ?filterx=on) too.


问:
Angular 9 access component in directive
I upgraded an angular 8 app to an agular 9 app.
In one of my directives I access the component trough the viewcontainer _data attribute. This no longer seems to exist in angular 9. How can I access the component in angular 9 ?

I have multiple inputs with an viewchild 'errorContainer'. They all inherit from Abstractinput. This way when I have a formcontroll, trough the directive I can put errors on the components.

```<code>@Directive({
    selector: '[formControl], [formControlName]'
})
export class DefaultControlErrorDirective implements OnDestroy, OnInit {

    constructor(private vcr: ViewContainerRef) {
      const component = this.vcr['_data'].componentView.component
    }
}
</code>```

Abstract input:

```<code>@Component({
    template: ``
})
export class InputAbstractComponent implements ControlValueAccessor, OnInit {
    @ViewChild('errorContainer', {read: ViewContainerRef}) errorContainerRef: ViewContainerRef;
}
</code>```

Implementation of abstract input

```<code>@Component({
    selector: 'tg-form-input',
    templateUrl: 'input.html',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => InputComponent),
            multi: true
        }
    ]
})
export class InputComponent extends InputAbstractComponent implements AfterViewInit {
}
</code>```

Input.html

```<code><div #errorContainer></div>
</code>```

答:
just inject your component

```<code>constructor(myComponent: MyComponent) {
}
</code>```

if the component isn't always the same component you could do this through providing it with some token

```<code>@Component({
providers: [{provide: COMPONENT_FOR_DIRECTIVE_TOKEN, useExisting: AnyComponent}]
})
class AnyComponent {
}
</code>```

Title: Angular 9 access component in directive

Body:
I upgraded an angular 8 app to an agular 9 app.
In one of my directives I access the component trough the viewcontainer _data attribute. This no longer seems to exist in angular 9. How can I access the component in angular 9 ?

I have multiple inputs with an viewchild 'errorContainer'. They all inherit from Abstractinput. This way when I have a formcontroll, trough the directive I can put errors on the components.

@Directive({
    selector: '[formControl], [formControlName]'
})
export class DefaultControlErrorDirective implements OnDestroy, OnInit {

    constructor(private vcr: ViewContainerRef) {
      const component = this.vcr['_data'].componentView.component
    }
}

Abstract input:

@Component({
    template: ``
})
export class InputAbstractComponent implements ControlValueAccessor, OnInit {
    @ViewChild('errorContainer', {read: ViewContainerRef}) errorContainerRef: ViewContainerRef;
}

Implementation of abstract input

@Component({
    selector: 'tg-form-input',
    templateUrl: 'input.html',
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => InputComponent),
            multi: true
        }
    ]
})
export class InputComponent extends InputAbstractComponent implements AfterViewInit {
}

Input.html

Body:
just inject your component

constructor(myComponent: MyComponent) {
}

if the component isn't always the same component you could do this through providing it with some token

@Component({
providers: [{provide: COMPONENT_FOR_DIRECTIVE_TOKEN, useExisting: AnyComponent}]
})
class AnyComponent {
}


问:
GOOGLE MAPS API - How to get my position without map.setMyLocationEnabled(boolean)?
I'm confused about how to get my location when clicking a button.

I was trying with my code below:

private void showMyLocation() {
    FusedLocationProviderApi fusedLocationApi = LocationServices.FusedLocationApi;
    Location location = fusedLocationApi.getLastLocation(googleApiClient);

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(latLng);

    map.animateCamera(cameraUpdate);
}
```

and the result is a force close app. I can't read logcat , because logcat is gone when the app crashes.

Are there any suggestions?

答:
Firstly create Location mLocation as globally then inside onLocationChanged

    @Override
    public void onLocationChanged(Location location) {
    mLastLocation = location;}
```

<p>then  </p>

<pre class="lang-java prettyprint-override"><code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    btn = findViewById(R.id.btn);
    // add code
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mLastLocation != null) {
                LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                lat = mLastLocation.getLatitude();
                Log.d("MapActivity", "lat of current" + lat);
                lng = mLastLocation.getLongitude();
                Log.d("MapActivity", "lng of current" + lng);

                if (marker != null) {
                    marker.remove();
                }

                marker = mMap.addMarker(new MarkerOptions()
                    .position(latLng)
                    .title("You are here!!!")
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.a1)));
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
            }
        }
    }
});
</code>```

Body:
I'm confused about how to get my location when clicking a button.

I was trying with my code below:

private void showMyLocation() {
    FusedLocationProviderApi fusedLocationApi = LocationServices.FusedLocationApi;
    Location location = fusedLocationApi.getLastLocation(googleApiClient);

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(latLng);

    map.animateCamera(cameraUpdate);
}

and the result is a force close app. I can't read logcat , because logcat is gone when the app crashes.

Are there any suggestions?

Body:
Firstly create Location mLocation as globally then inside onLocationChanged

    @Override
    public void onLocationChanged(Location location) {
    mLastLocation = location;}

then

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    btn = findViewById(R.id.btn);
    // add code
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mLastLocation != null) {
                LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                lat = mLastLocation.getLatitude();
                Log.d("MapActivity", "lat of current" + lat);
                lng = mLastLocation.getLongitude();
                Log.d("MapActivity", "lng of current" + lng);

                if (marker != null) {
                    marker.remove();
                }

                marker = mMap.addMarker(new MarkerOptions()
                    .position(latLng)
                    .title("You are here!!!")
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.a1)));
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
            }
        }
    }
});


问:
Click to change grid cells colors
I'm trying to make an interactive grid but the colors won't change when I click on the squares. The grid has to be multicolored and when one clicks on the grid, the boxes inside of it should change color to a random color of five colors. The grid isn't changing colors however, and I'm not sure how to make each object carry its own color.

I have a square class that constructs an object to be a rectangle

```<code>public class square extends JPanel {

    private int sizeOfSquare = 10;
    private Color theColor;
    private int theXindexcode;
    private int theYindexcode;

    public void constructSquare (Graphics g){

            g.setColor(theColor);
            g.drawRect(theXindexcode, theYindexcode, sizeOfSquare, sizeOfSquare);
            g.fillRect(theXindexcode, theYindexcode, sizeOfSquare, sizeOfSquare);
    }

    square (int theXindex, int theYindex ){
        sizeOfSquare = 10;
        theXindexcode = theXindex;
        theYindexcode = theYindex;
    }

    public void setTheColor(Color theColor) {
        this.theColor = theColor;
    }
}

</code>```

I also have a drawing panel with this code inside it.

```<code>import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.JPanel;

public class DrawingPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener {
    private final int rows = 50;
    private final int columns = 50;
    private final int pixelsize = 10;
    private final int rowIndex = 0;
    private final int colIndex = 0;
    private final boolean thisSquare = false;
    int trackX;
    int trackY;
    private boolean setColor;
    int [][] theGrid = new int[rows][columns];
    square [][] squareArray = new square[50][50];
    private int setInitialColor;
    private Color either1;

    public  DrawingPanel() {
        super();
        //thisSquare = false;
        this.addMouseListener(this);

        //Creates a random number, if that number is greater than 5, the square in the grid will be red
        //if anything else the square will be black
        for (int i = 0; i < 50; i++){
            for (int i2 = 0; i2 < 50; i2++){
                square newSquareObject = new square(i2*10, i2*10);
                squareArray[rowIndex][colIndex] = newSquareObject;
            }
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {

        int whatisitX = e.getX()/10*10;
        int whatisitY = e.getY()/10*10;

        trackX = whatisitX;
        trackY = whatisitY;

        System.out.println(whatisitX +","+ whatisitY);

        if(trackX>= 0 && trackX <= 500 && trackY >=0 && trackY <=500){

            System.out.println(setColor);
            setColor = true;
        }
    }

    //Create 2D array for Grid
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        //Loop through grid with 2D array and nested for Loop.
        for (int rowIndex = 0; rowIndex <= 50; rowIndex++) {

            for (int colIndex = 0; colIndex < 50; colIndex++) {

                Random random = new Random();
                int j = random.nextInt();

                if (j >= 2) {
                    g.setColor(Color.white);
                }
                else {
                    g.setColor(Color.black);
                }

                g.drawRect(rowIndex * 10, colIndex * 10, pixelsize, pixelsize);
                g.fillRect(rowIndex * 10, colIndex * 10, pixelsize, pixelsize);

                //Creates border for grid
                g.setColor(Color.pink);
                g.drawRect(rowIndex * 10, colIndex * 10, pixelsize, pixelsize);
            }
        }

        if (setColor == true) {

            Random random = new Random();
            Color thecolorsetter = Color.orange;

            if (random.nextInt(5) == 0){
                thecolorsetter = Color.green;

            }

            else if (random.nextInt(5) == 1){
                thecolorsetter = Color.red;
            }

            else if (random.nextInt(5) == 2){
                thecolorsetter = Color.yellow;
            }

            if (random.nextInt(5) == 3){
                thecolorsetter = Color.CYAN;
            }
            if (random.nextInt(5) == 4){
                thecolorsetter = Color.MAGENTA;
            }

            squareArray[trackX][trackY].setTheColor(thecolorsetter);
            repaint();
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void mouseDragged(MouseEvent e) {

    }

    @Override
    public void mouseMoved(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    public int getRowIndex() {
        return rowIndex;
    }

    public int getColIndex() {
        return colIndex;
    }
}
</code>```

I attempted constructing the drawing panel with the rando

答:
The following is a one-file mre demonstrating the functionality described in the question.

Copy-paste the entire code into DrawingPanel.java and run.

Please read the comments and do not hesitate to ask for clarifications as needed:

```<code>import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class DrawingPanel extends JPanel{

    private static final int ROWS = 50, COLS = 50,  PIXLE_SIZE = 10,
                            GAP = 0; //change gap to 1 for example if you want to set a gap between squares

    public  DrawingPanel() {
        super();
        setBackground(Color.WHITE);
        setLayout(new GridLayout(ROWS, COLS, GAP, GAP));

        Random random = new Random();
        for (int i = 0; i < ROWS; i++){
            for (int i2 = 0; i2 < COLS; i2++){
                Square newSquareObject = new Square(PIXLE_SIZE);
                //if random number is greater than 5, the Square in the grid will be red
                //if anything else the Square will be black
                newSquareObject.setTheColor(random.nextInt(10)>5 ? Color.RED : Color.BLACK);
                //you need to add each square to get it painted
                add(newSquareObject);
            }
        }

        setPreferredSize(new Dimension(ROWS*(PIXLE_SIZE+GAP),COLS*(PIXLE_SIZE+GAP)));
    }

    public static void main(String[] args0) {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new DrawingPanel());
        frame.pack();
        frame.setVisible(true);
    }
}

class Square extends JPanel implements MouseListener {

    private final int sizeOfSquare;
    private static final Color DEFAULT_COLOR = Color.BLACK;
    private static final Color[] colors = {Color.ORANGE, Color.GREEN, Color.RED, Color.YELLOW, Color.CYAN, Color.MAGENTA};

    Square (int sizeOfSquare){
        this.sizeOfSquare = sizeOfSquare;
        setPreferredSize(new Dimension(sizeOfSquare , sizeOfSquare));
        setTheColor(DEFAULT_COLOR);
        addMouseListener(this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        setTheColor(colors[ new Random().nextInt(colors.length)]);
    }

    void setTheColor(Color theColor) {
        setBackground(theColor);
    }

    int getSizeOfSquare(){
        return sizeOfSquare;
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
    }
}
</code>```

Title: Click to change grid cells colors

Body:
I'm trying to make an interactive grid but the colors won't change when I click on the squares. The grid has to be multicolored and when one clicks on the grid, the boxes inside of it should change color to a random color of five colors. The grid isn't changing colors however, and I'm not sure how to make each object carry its own color.

I have a square class that constructs an object to be a rectangle

public class square extends JPanel {

    private int sizeOfSquare = 10;
    private Color theColor;
    private int theXindexcode;
    private int theYindexcode;

    public void constructSquare (Graphics g){

            g.setColor(theColor);
            g.drawRect(theXindexcode, theYindexcode, sizeOfSquare, sizeOfSquare);
            g.fillRect(theXindexcode, theYindexcode, sizeOfSquare, sizeOfSquare);
    }

    square (int theXindex, int theYindex ){
        sizeOfSquare = 10;
        theXindexcode = theXindex;
        theYindexcode = theYindex;
    }

    public void setTheColor(Color theColor) {
        this.theColor = theColor;
    }
}

I also have a drawing panel with this code inside it.

import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.JPanel;

public class DrawingPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener {
    private final int rows = 50;
    private final int columns = 50;
    private final int pixelsize = 10;
    private final int rowIndex = 0;
    private final int colIndex = 0;
    private final boolean thisSquare = false;
    int trackX;
    int trackY;
    private boolean setColor;
    int [][] theGrid = new int[rows][columns];
    square [][] squareArray = new square[50][50];
    private int setInitialColor;
    private Color either1;

    public  DrawingPanel() {
        super();
        //thisSquare = false;
        this.addMouseListener(this);

        //Creates a random number, if that number is greater than 5, the square in the grid will be red
        //if anything else the square will be black
        for (int i = 0; i < 50; i++){
            for (int i2 = 0; i2 < 50; i2++){
                square newSquareObject = new square(i2*10, i2*10);
                squareArray[rowIndex][colIndex] = newSquareObject;
            }
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {

        int whatisitX = e.getX()/10*10;
        int whatisitY = e.getY()/10*10;

        trackX = whatisitX;
        trackY = whatisitY;

        System.out.println(whatisitX +","+ whatisitY);

        if(trackX>= 0 && trackX <= 500 && trackY >=0 && trackY <=500){

            System.out.println(setColor);
            setColor = true;
        }
    }

    //Create 2D array for Grid
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        //Loop through grid with 2D array and nested for Loop.
        for (int rowIndex = 0; rowIndex <= 50; rowIndex++) {

            for (int colIndex = 0; colIndex < 50; colIndex++) {

                Random random = new Random();
                int j = random.nextInt();

                if (j >= 2) {
                    g.setColor(Color.white);
                }
                else {
                    g.setColor(Color.black);
                }

                g.drawRect(rowIndex * 10, colIndex * 10, pixelsize, pixelsize);
                g.fillRect(rowIndex * 10, colIndex * 10, pixelsize, pixelsize);

                //Creates border for grid
                g.setColor(Color.pink);
                g.drawRect(rowIndex * 10, colIndex * 10, pixelsize, pixelsize);
            }
        }

        if (setColor == true) {

            Random random = new Random();
            Color thecolorsetter = Color.orange;

            if (random.nextInt(5) == 0){
                thecolorsetter = Color.green;

            }

            else if (random.nextInt(5) == 1){
                thecolorsetter = Color.red;
            }

            else if (random.nextInt(5) == 2){
                thecolorsetter = Color.yellow;
            }

            if (random.nextInt(5) == 3){
                thecolorsetter = Color.CYAN;
            }
            if (random.nextInt(5) == 4){
                thecolorsetter = Color.MAGENTA;
            }

            squareArray[trackX][trackY].setTheColor(thecolorsetter);
            repaint();
        }

    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    @Override
    public void mouseDragged(MouseEvent e) {

    }

    @Override
    public void mouseMoved(MouseEvent e) {

    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    public int getRowIndex() {
        return rowIndex;
    }

    public int getColIndex() {
        return colIndex;
    }
}

I attempted constructing the drawing panel with the rando

Body:
The following is a one-file mre demonstrating the functionality described in the question.

Copy-paste the entire code into DrawingPanel.java and run.

Please read the comments and do not hesitate to ask for clarifications as needed:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class DrawingPanel extends JPanel{

    private static final int ROWS = 50, COLS = 50,  PIXLE_SIZE = 10,
                            GAP = 0; //change gap to 1 for example if you want to set a gap between squares

    public  DrawingPanel() {
        super();
        setBackground(Color.WHITE);
        setLayout(new GridLayout(ROWS, COLS, GAP, GAP));

        Random random = new Random();
        for (int i = 0; i < ROWS; i++){
            for (int i2 = 0; i2 < COLS; i2++){
                Square newSquareObject = new Square(PIXLE_SIZE);
                //if random number is greater than 5, the Square in the grid will be red
                //if anything else the Square will be black
                newSquareObject.setTheColor(random.nextInt(10)>5 ? Color.RED : Color.BLACK);
                //you need to add each square to get it painted
                add(newSquareObject);
            }
        }

        setPreferredSize(new Dimension(ROWS*(PIXLE_SIZE+GAP),COLS*(PIXLE_SIZE+GAP)));
    }

    public static void main(String[] args0) {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new DrawingPanel());
        frame.pack();
        frame.setVisible(true);
    }
}

class Square extends JPanel implements MouseListener {

    private final int sizeOfSquare;
    private static final Color DEFAULT_COLOR = Color.BLACK;
    private static final Color[] colors = {Color.ORANGE, Color.GREEN, Color.RED, Color.YELLOW, Color.CYAN, Color.MAGENTA};

    Square (int sizeOfSquare){
        this.sizeOfSquare = sizeOfSquare;
        setPreferredSize(new Dimension(sizeOfSquare , sizeOfSquare));
        setTheColor(DEFAULT_COLOR);
        addMouseListener(this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        setTheColor(colors[ new Random().nextInt(colors.length)]);
    }

    void setTheColor(Color theColor) {
        setBackground(theColor);
    }

    int getSizeOfSquare(){
        return sizeOfSquare;
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
    }
}