问:
What is the best way to store app data and load it in app?
This is just a information question. I'm new to Android app development and currently I'm working on my first app and and it is ready for the release. Now I'm concerned about how to handle heap of users and where to save all their details my app is a service booking app so it needs to save all the order details products details and lots other stuff.

Currently I'm using cloud firestore to load and save all the data of app. But I'm having some issues like without authentication it won't allow users to access some of my data and other. I wonder how large apps save their data and load them perfectly.

I wish someone will help me how can I save all my app data and load them perfectly in app. And  suggest me for a best way to manage large user base. And other stuff.

答:
If you have lots of data from different users, maybe you should use a central server(DB), something like Postgres or MySQL should work fine.

At the same time, you can also do some sort of caching to accelerate the fetching process, like create a small database locally(you can use Room) to store some user specific data.


来源: stackexchange

问:
git - pushing only the top most commit to server
I have a situation where I:

(1) Merged a patch by user X

(2) Made some changes to some other code and committed.

Now I want to push my commit to the server. However, when I do

```<code>git push origin HEAD:refs/for/mybranch
</code>```

I get an error regarding the patch that I merged, saying that I am not the author. Is there a way to do what I'm trying to accomplish? If not, is there a way to save my commit, then revert everything and push my commit back in?

答:
Sounds like the repo has some hooks setup in it that prevent you from pushing any commits that you are not the author/commiter of.

You can attempt to cherry-pick the commit so that the commiter gets set to you. If that does not work then you need to ask whoever installed the repository hook because it breaks almost all git workflows because you will never be able to push a merge commit.

ContentLicense: CC BY-SA 3.0

Body:
I have a situation where I:

(1) Merged a patch by user X

(2) Made some changes to some other code and committed.

Now I want to push my commit to the server. However, when I do

git push origin HEAD:refs/for/mybranch

I get an error regarding the patch that I merged, saying that I am not the author. Is there a way to do what I'm trying to accomplish? If not, is there a way to save my commit, then revert everything and push my commit back in?


问:
FireDAC Conversion not supported for query parameter on Interbase timestamp column
I'm having a problem opening a query that uses a timestamp parameter to an interbase table.  After checking stackoverflow and implementing the conversion mappings for MapRules, I get a result of "Conversion is not supported" when opening the query.

Any help is deeply appreciated, Thanks!

Here is the code that sets the parameters:

    with FDQuery1 do
    begin
      Close;
      FDQuery1.FormatOptions.OwnMapRules := True;
      with FormatOptions.MapRules.Add do
      begin
        SourceDataType := dtDateTime;
        TargetDataType := dtDateTimeStamp;
      end;
      FDQuery1.Params.ParamByName('BalanceDate').AsDateTime := StrToDateTime('10/03/2017');
      FDQuery1.ParamByName('User').AsInteger := 1;
      FDQuery1.OpenOrExecute;
    end;```
</div>
</div>
</p>

<p>Here is the query:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>SELECT
 AC.ACCOUNT_ID,
 AC.ACCOUNT_NAME,
 ACT.ACCOUNT_TYPE_NAME,
 (Select Sum(P1.TOTAL_VAL) From PMNTDOCTRANS P1, DAYBATCH D1 Where
  (P1.ACCOUNT_ID=AC.ACCOUNT_ID)
  And (D1.DAY_BATCH_ID=P1.DAY_BATCH_ID)
  And (D1.DAY_BATCH_DATE <= :BalanceDate)
  And (D1.DAY_BATCH_STORE in (Select Id From ExtUserList Where List_Id=9 and User_Id =:User))
 ) As Val1,
 (Select Sum(P2.TOTAL_VAL) From PMNTDOCTRANS P2, DAYBATCH D2 Where
  (P2.OPOSIT_ACCOUNT=AC.ACCOUNT_ID)
  And (D2.DAY_BATCH_ID=P2.DAY_BATCH_ID)
  And (D2.DAY_BATCH_DATE <= :BalanceDate)
  And (D2.DAY_BATCH_STORE in (Select Id From ExtUserList Where List_Id=9 and User_Id =:User))
 ) As Val2
FROM
 ACCOUNT AC ,
 ACCOUNTTYPE ACT
WHERE
 (ACT.ACCOUNT_TYPE_ID = AC.ACCOUNT_TYPE_ID)
 And
 (AC.ACCOUNT_TYPE_ID in (Select Id From ExtUserList Where List_Id=3 and User_Id =:User))
ORDER BY ACCOUNT_TYPE_NAME</code>```

答:
this problem solves like this</p>

```<code>FDQuery1.Params.ParamByName('BalanceDate').Value:= StrToDateTime('10/03/2017');
</code>```

Body:
I'm having a problem opening a query that uses a timestamp parameter to an interbase table.  After checking stackoverflow and implementing the conversion mappings for MapRules, I get a result of "Conversion is not supported" when opening the query.

Any help is deeply appreciated, Thanks!

Here is the code that sets the parameters:

    with FDQuery1 do
    begin
      Close;
      FDQuery1.FormatOptions.OwnMapRules := True;
      with FormatOptions.MapRules.Add do
      begin
        SourceDataType := dtDateTime;
        TargetDataType := dtDateTimeStamp;
      end;
      FDQuery1.Params.ParamByName('BalanceDate').AsDateTime := StrToDateTime('10/03/2017');
      FDQuery1.ParamByName('User').AsInteger := 1;
      FDQuery1.OpenOrExecute;
    end;

Here is the query:

SELECT
 AC.ACCOUNT_ID,
 AC.ACCOUNT_NAME,
 ACT.ACCOUNT_TYPE_NAME,
 (Select Sum(P1.TOTAL_VAL) From PMNTDOCTRANS P1, DAYBATCH D1 Where
  (P1.ACCOUNT_ID=AC.ACCOUNT_ID)
  And (D1.DAY_BATCH_ID=P1.DAY_BATCH_ID)
  And (D1.DAY_BATCH_DATE <= :BalanceDate)
  And (D1.DAY_BATCH_STORE in (Select Id From ExtUserList Where List_Id=9 and User_Id =:User))
 ) As Val1,
 (Select Sum(P2.TOTAL_VAL) From PMNTDOCTRANS P2, DAYBATCH D2 Where
  (P2.OPOSIT_ACCOUNT=AC.ACCOUNT_ID)
  And (D2.DAY_BATCH_ID=P2.DAY_BATCH_ID)
  And (D2.DAY_BATCH_DATE <= :BalanceDate)
  And (D2.DAY_BATCH_STORE in (Select Id From ExtUserList Where List_Id=9 and User_Id =:User))
 ) As Val2
FROM
 ACCOUNT AC ,
 ACCOUNTTYPE ACT
WHERE
 (ACT.ACCOUNT_TYPE_ID = AC.ACCOUNT_TYPE_ID)
 And
 (AC.ACCOUNT_TYPE_ID in (Select Id From ExtUserList Where List_Id=3 and User_Id =:User))
ORDER BY ACCOUNT_TYPE_NAME

Body:
this problem solves like this

FDQuery1.Params.ParamByName('BalanceDate').Value:= StrToDateTime('10/03/2017');

ContentLicense: CC BY-SA 4.0


答: First of all, firestore is good option if you don't have complex backend logic on the database. For simple CRUD operations on data firestore is a good choice but as you said you have a bulk of data then you must go for the Backend database and then connect your database with Rest API. So that all your complex queries will be done on the backend and you can simply consume your API in the app.</p>

Title: What is the best way to store app data and load it in app?

Body:
This is just a information question. I'm new to Android app development and currently I'm working on my first app and and it is ready for the release. Now I'm concerned about how to handle heap of users and where to save all their details my app is a service booking app so it needs to save all the order details products details and lots other stuff.

Currently I'm using cloud firestore to load and save all the data of app. But I'm having some issues like without authentication it won't allow users to access some of my data and other. I wonder how large apps save their data and load them perfectly.

I wish someone will help me how can I save all my app data and load them perfectly in app. And  suggest me for a best way to manage large user base. And other stuff.


问:
Android Studio fails to generate databinding after 3.1.0 update
This morning I made an update to android studio from 3.0.1 to 3.1.0. After updating the gradle to latest version I still get build error regarding data binding.

My gradle-wrapper.properties:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
</code>```

All my errors are like the one below:

```<code>/Users/mp/Documents/GitHub/projectx/app/build/generated/source/dataBinding/baseClasses/Staging/debug/me/projectx/asdasd/databinding/GridItemActivityTypeBinding.java:57: error: cannot find symbol
      @Nullable DataBindingComponent component) {
                ^
  symbol:   class DataBindingComponent
  location: class GridItemActivityTypeBinding
</code>```

Does anyone have any idea why would my data binding not generate after the android studio 3.1 update? Thanks in advance

Edit 1: Forgot to say, I tried clean/rebuild/invalidate cache & restart/deleted build folder.

答: Just connect to internet and sync project with gradle files. It'll do.</p>

Body:
This morning I made an update to android studio from 3.0.1 to 3.1.0. After updating the gradle to latest version I still get build error regarding data binding.

My gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

All my errors are like the one below:

/Users/mp/Documents/GitHub/projectx/app/build/generated/source/dataBinding/baseClasses/Staging/debug/me/projectx/asdasd/databinding/GridItemActivityTypeBinding.java:57: error: cannot find symbol
      @Nullable DataBindingComponent component) {
                ^
  symbol:   class DataBindingComponent
  location: class GridItemActivityTypeBinding

Does anyone have any idea why would my data binding not generate after the android studio 3.1 update? Thanks in advance

Edit 1: Forgot to say, I tried clean/rebuild/invalidate cache & restart/deleted build folder.


问:
Schema Merging not working when the s3 paths are given explicitly
When the s3 paths is explicitly given to read parquet files that are not in the same directory, the partitioning schemes aren't inferred and hence i dont get the partitioned column in my spark dataframe.

I have tried the option merge schema = True while reading the parquet files but that seems to work when given the root folder and not explicit paths.

My Current s3 directory structure.

```<code>bucket
    folder1
        .....|- col=val1/file1.parquet
        .....|- col=val2/file2.parquet
        .....|- col=val3/file3.parquet
        .....
    folder2
        .....|- col=val1/file4.parquet
        .....|- col=val2/file5.parquet
        .....|- col=val3/file6.parquet
        .....
    .....
</code>```

I want to read all the files that has the value val1 and val2 for the key col.
Hence, i get the s3 paths of those as a list and read them explicitly.

s3paths = ['s3://bucket/folder1/col=val1/file1.parquet',
's3://bucket/folder1/col=val2/file2.parquet',
's3://bucket/folder1/col=val1/file4.parquet',
's3://bucket/folder2/col=val2/file5.parquet']

df = spark.read.parquet(*s3paths)

# another option
df = spark.read.options("mergeSchema", True).parquet(*s3paths)
```

I am able to read the files but the column col doesn't appear in the spark dataframe.

I expect the colum 'col' to be present in my dataframe.

答:
```<code>This is the folder structure of my data.
    data
        .....|- period_id=201909/file1.csv
        .....|- period_id=201910/file2.csv
file1.csv
---------
Name,Age
Amit,28
Ashish,30
Swaraj,27

file2.csv
----------
Name,Age,Sal
Amit,28,10000
Ashish,30,20000
Swaraj,27,15000

from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from pyspark.sql.functions import input_file_name
spark = SparkSession.builder.appName("Test").getOrCreate()

current_period = "201910"
prev_period = "201909"
mergedDF = spark.read.format("csv").option("mergeSchema", "true").option("header", "true")\
    .option("inferSchema", "true")\
    .load(["data/period_id={current_period}/*".format(current_period=current_period),
           "data/period_id={prev_period}/*".format(prev_period=prev_period)]) \
    .withColumn("filename", input_file_name())

splitDF = mergedDF.withColumn("period_with_file_name", F.split(F.col("filename"), "=").getItem(1))\
    .withColumn("period_date_yyyymm",F.split(F.col("period_with_file_name"), "/").getItem(0).astype("int"))\
    .drop("filename", "period_with_file_name")

splitDF.printSchema()

splitDF.show(truncate=False)

Output
----------
root
 |-- Name: string (nullable = true)
 |-- Age: string (nullable = true)
 |-- Sal: integer (nullable = true)
 |-- period_date_yyyymm: integer (nullable = true)

+------+---+-----+------------------+
|Name  |Age|Sal  |period_date_yyyymm|
+------+---+-----+------------------+
|Amit  |28 |10000|201910            |
|Ashish|30 |20000|201910            |
|Swaraj|27 |15000|201910            |
|Amit  |28 |null |201909            |
|Ashish|30 |null |201909            |
|Swaraj|27 |null |201909            |
+------+---+-----+------------------+

The column 'col' i.e 201910, 201909 here is present in the dataframe.

This code is as per my case. Just change based on your requirement.
</code>```

Body:
When the s3 paths is explicitly given to read parquet files that are not in the same directory, the partitioning schemes aren't inferred and hence i dont get the partitioned column in my spark dataframe.

I have tried the option merge schema = True while reading the parquet files but that seems to work when given the root folder and not explicit paths.

My Current s3 directory structure.

bucket
    folder1
        .....|- col=val1/file1.parquet
        .....|- col=val2/file2.parquet
        .....|- col=val3/file3.parquet
        .....
    folder2
        .....|- col=val1/file4.parquet
        .....|- col=val2/file5.parquet
        .....|- col=val3/file6.parquet
        .....
    .....

I want to read all the files that has the value val1 and val2 for the key col.
Hence, i get the s3 paths of those as a list and read them explicitly.

s3paths = ['s3://bucket/folder1/col=val1/file1.parquet',
's3://bucket/folder1/col=val2/file2.parquet',
's3://bucket/folder1/col=val1/file4.parquet',
's3://bucket/folder2/col=val2/file5.parquet']

df = spark.read.parquet(*s3paths)

# another option
df = spark.read.options("mergeSchema", True).parquet(*s3paths)

I am able to read the files but the column col doesn't appear in the spark dataframe.

I expect the colum 'col' to be present in my dataframe.


问:
Why fgrep is acting weird?
I am trying to use grep to extract the matching words from file1 in file2 and directing to output file.

I have file1

```<code>Acetoanaerobium sticklandii
Acetobacter pasteurianus
</code>```

like >1000 species.

File2

```<code>>WP_013360383.1 ATP-dependent Clp protease ATP-binding subunit [Acetoanaerobium sticklandii]
>WP_013360396.1 ATP-dependent Clp protease ATP-binding subunit [Acetoanaerobium sticklandii]
>WP_003623694.1 multidrug efflux RND transporter permease subunit [Acetobacter pasteurianus]
>WP_003624003.1 superoxide dismutase [Acetobacter pasteurianus]
>WP_003624029.1 UDP-galactopyranose mutase [Acetobacter pasteurianus]
>WP_003624540.1 mannose-1-phosphate guanylyltransferase/mannose-6-phosphate isomerase [Acetobacter pasteurianus]
>WP_077905956.1 effector protein [Salmonella enterica]
>WP_077905962.1 type III secretion system YopJ family effector AvrA [Salmonella enterica]
>WP_005544680.1 3-deoxy-8-phosphooctulonate synthase [Aggregatibacter actinomycetemcomitans]
>WP_005545812.1 MFS transporter [Aggregatibacter actinomycetemcomitans]
>WP_005546163.1 UTP--glucose-1-phosphate uridylyltransferase GalU [Aggregatibacter actinomycetemcomitans]
</code>```

and so on..

when I am using the code

```<code>grep -f file1 file2 > output
</code>```

or

```<code>fgrep -f file1 file2 > output
</code>```

The resulting output is the list containing the last line of file1 and remaining input list is ignoring by grep. Even with -w option also the output is same.

Why the grep is behaving like this?
Is it problem with my shell?
I am using MacBook with Mojave OS version.

Please suggest me equivalent awk commands.

I tried

```<code>awk 'NR==FNR{a[$0];next}$NF in a{print}' file1 file2 > output
</code>```

but resulted empty file.

答:
The problem is with your match condition $NF in a, means to match sticklandii] to your full line content in first file.

A better approach would be to set delimiter to process the whole string inside [..] in second file against first file

```<code>awk 'NR == FNR{ a[$0]; next } $2 in a' f1 FS='[][]' f2
</code>```

The FS='[][]' before second file is to set the field separator to [] which means you can access the entries within [..] by column numbers which is $2 in your given case.

As for your original problem fgrep not working, you need to add the -F flag to make the strings from second file as "fixed" strings and not regex strings. So you can do

```<code>fgrep -Ff file1 file2
</code>```

Title: Why fgrep is acting weird?

Body:
I am trying to use grep to extract the matching words from file1 in file2 and directing to output file.

I have file1

Acetoanaerobium sticklandii
Acetobacter pasteurianus

like >1000 species.

File2

>WP_013360383.1 ATP-dependent Clp protease ATP-binding subunit [Acetoanaerobium sticklandii]
>WP_013360396.1 ATP-dependent Clp protease ATP-binding subunit [Acetoanaerobium sticklandii]
>WP_003623694.1 multidrug efflux RND transporter permease subunit [Acetobacter pasteurianus]
>WP_003624003.1 superoxide dismutase [Acetobacter pasteurianus]
>WP_003624029.1 UDP-galactopyranose mutase [Acetobacter pasteurianus]
>WP_003624540.1 mannose-1-phosphate guanylyltransferase/mannose-6-phosphate isomerase [Acetobacter pasteurianus]
>WP_077905956.1 effector protein [Salmonella enterica]
>WP_077905962.1 type III secretion system YopJ family effector AvrA [Salmonella enterica]
>WP_005544680.1 3-deoxy-8-phosphooctulonate synthase [Aggregatibacter actinomycetemcomitans]
>WP_005545812.1 MFS transporter [Aggregatibacter actinomycetemcomitans]
>WP_005546163.1 UTP--glucose-1-phosphate uridylyltransferase GalU [Aggregatibacter actinomycetemcomitans]

and so on..

when I am using the code

grep -f file1 file2 > output

or

fgrep -f file1 file2 > output

The resulting output is the list containing the last line of file1 and remaining input list is ignoring by grep. Even with -w option also the output is same.

Why the grep is behaving like this?
Is it problem with my shell?
I am using MacBook with Mojave OS version.

Please suggest me equivalent awk commands.

I tried

awk 'NR==FNR{a[$0];next}$NF in a{print}' file1 file2 > output

but resulted empty file.

Body:
The problem is with your match condition $NF in a, means to match sticklandii] to your full line content in first file.

A better approach would be to set delimiter to process the whole string inside [..] in second file against first file

awk 'NR == FNR{ a[$0]; next } $2 in a' f1 FS='[][]' f2

The FS='[][]' before second file is to set the field separator to [] which means you can access the entries within [..] by column numbers which is $2 in your given case.

As for your original problem fgrep not working, you need to add the -F flag to make the strings from second file as "fixed" strings and not regex strings. So you can do

fgrep -Ff file1 file2


问:
PHP timezone not set
First of all, i don't have access to the php.ini in the webserver.

In my local server I put date.timezone = "Europe/Lisbon" in my php.ini.

Is it possible to change this in .htaccess? or, what is the alternative?

At the moment I get this error in web server for phpmailer():

```<code>Strict Standards:  date(): It is not safe to rely on the system's timezone settings. ....
</code>```

答:
On second thought, ini_set may not be the best way to go. Apparently E_STRICT standards say that you should use date_default_timezone_set instead.

Try something like:

```<code>date_default_timezone_set('Europe/Lisbon');

$tz = date_default_timezone_get();
</code>```

More info can be found here about the issue:
http://answers.google.com/answers/threadview/id/739376.html

And here for the default_timezone functions:

http://us2.php.net/manual/en/function.date-default-timezone-set.php

Edit: I found this little gem while I was browsing github.

```<code>// has to be set to reach E_STRICT compatibility, does not affect system/app settings
date_default_timezone_set(date_default_timezone_get());
</code>```

This seems like the best solution.

Title: PHP timezone not set

Body:
First of all, i don't have access to the php.ini in the webserver.

In my local server I put date.timezone = "Europe/Lisbon" in my php.ini.

Is it possible to change this in .htaccess? or, what is the alternative?

At the moment I get this error in web server for phpmailer():

Strict Standards:  date(): It is not safe to rely on the system's timezone settings. ....

Body:
On second thought, ini_set may not be the best way to go. Apparently E_STRICT standards say that you should use date_default_timezone_set instead.

Try something like:

date_default_timezone_set('Europe/Lisbon');

$tz = date_default_timezone_get();

More info can be found here about the issue:
http://answers.google.com/answers/threadview/id/739376.html

And here for the default_timezone functions:

http://us2.php.net/manual/en/function.date-default-timezone-set.php

Edit: I found this little gem while I was browsing github.

// has to be set to reach E_STRICT compatibility, does not affect system/app settings
date_default_timezone_set(date_default_timezone_get());

This seems like the best solution.


问:
Can't give Gridview text another color with Jquery
I have this Jquery which changes the background of the row when the checkbox is checked:

```<code> $(document).ready(function () {

            $("[id*=CheckBox1]").live('click', function (event) {

                if (this.checked == true) {
                    $(this).closest('tr').css("background-color", "#6c42a6");

                }
                if (this.checked == false) {
                    $(this).closest('tr').css("background-color", "#ffffff");
                }
            });

            $('#GridView1 tr').live('click', function (event) {
                if ($(event.target).is(':checkbox')) {
                    return;
                }

                var chkboxSelection = $(this).find('input:checkbox')[0].checked;
                if (chkboxSelection == true) {
                    $(this).closest('tr').css("background-color", "white");
                    $(this).find('input:checkbox')[0].checked = false;

                }
                else if (chkboxSelection == false) {
                    $(this).closest('tr').css("background-color", "#6c42a6");
                    $(this).find('input:checkbox')[0].checked = true;

                }
            });

        });
</code>```

This works, but I can't change the color of the text that is in the gridview. I want this because black on purple is not really visible.
I tried adding this this:

```<code>
$(this).closest('td').css("color", "white");

</code>```

But this does not work, even though this is the class on which the color needs to be changed.

Any help would be much appreciated.

答:
Instead of using closest(..) use children(...). closest is searching in ancestors of an element, starting with itself - that's why it works for the tr. But the td is a child of tr, so closest will not find it.

Try it like this:

```<code>            $('#GridView1 tr').live('click', function (event) {
                if ($(event.target).is(':checkbox')) {
                    return;
                }

                var chkboxSelection = $(this).find('input:checkbox')[0].checked;
                if (chkboxSelection == true) {
                    $(this).closest('tr').css("background-color", "white");
                    $(this).find('input:checkbox')[0].checked = false;

                }
                else if (chkboxSelection == false) {
                    $(this).children('td').css("color", "white");
                    $(this).closest('tr').css("background-color", "#6c42a6");
                    $(this).find('input:checkbox')[0].checked = true;
                }
            });
</code>```

Get familiar with the jQuery Api

Body:
I have this Jquery which changes the background of the row when the checkbox is checked:

 $(document).ready(function () {

            $("[id*=CheckBox1]").live('click', function (event) {

                if (this.checked == true) {
                    $(this).closest('tr').css("background-color", "#6c42a6");

                }
                if (this.checked == false) {
                    $(this).closest('tr').css("background-color", "#ffffff");
                }
            });

            $('#GridView1 tr').live('click', function (event) {
                if ($(event.target).is(':checkbox')) {
                    return;
                }

                var chkboxSelection = $(this).find('input:checkbox')[0].checked;
                if (chkboxSelection == true) {
                    $(this).closest('tr').css("background-color", "white");
                    $(this).find('input:checkbox')[0].checked = false;

                }
                else if (chkboxSelection == false) {
                    $(this).closest('tr').css("background-color", "#6c42a6");
                    $(this).find('input:checkbox')[0].checked = true;

                }
            });

        });

This works, but I can't change the color of the text that is in the gridview. I want this because black on purple is not really visible.
I tried adding this this:

$(this).closest('td').css("color", "white");

But this does not work, even though this is the class on which the color needs to be changed.

Any help would be much appreciated.

Body:
Instead of using closest(..) use children(...). closest is searching in ancestors of an element, starting with itself - that's why it works for the tr. But the td is a child of tr, so closest will not find it.

Try it like this:

            $('#GridView1 tr').live('click', function (event) {
                if ($(event.target).is(':checkbox')) {
                    return;
                }

                var chkboxSelection = $(this).find('input:checkbox')[0].checked;
                if (chkboxSelection == true) {
                    $(this).closest('tr').css("background-color", "white");
                    $(this).find('input:checkbox')[0].checked = false;

                }
                else if (chkboxSelection == false) {
                    $(this).children('td').css("color", "white");
                    $(this).closest('tr').css("background-color", "#6c42a6");
                    $(this).find('input:checkbox')[0].checked = true;
                }
            });

Get familiar with the jQuery Api


问:
Python, loops with changeable parts of filenames
I have a bunch of very similar commands which all look like this (df means pandas dataframe):

```<code>df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...
</code>```

I would like to make a loop for it, as follows:

```<code>for i in range(1,5):
for j in range(1,5):
df%i_part%j=...
</code>```

Of course, it doesn't work with %. But is has to be some easy way to do it, I suppose.
Could You help me please?

答:
Assuming that this process is part of data preparation, I would like to mention that you should try to work with "data preparation pipelines" whenever it is possible. Otherwise, the code will be a huge mess to read after a couple of months.

There are several ways to deal with this problem.

A dictionary is the most straightforward way to deal with this.

df_parts = {
            'df1' : {'part1': df1_part1, 'part2': df1_part2,...,'partN': df1_partN},
            'df2' : {'part1': df1_part1, 'part2': df1_part2,...,'partN': df2_partN},
            '...' : {'part1': ..._part1, 'part2': ..._part2,...,'partN': ..._partN},
            'dfN' : {'part1': dfN_part1, 'part2': dfN_part2,...,'partN': dfN_partN},
           }

# print parts from `dfN`
for val in for df_parts['dfN'].values():
    print(val)

# print part1 for all dfs
for df in df_parts.values():
    print(df['part1'])

# print everything
for df in df_parts:
    for val in df_parts[df].values():
        print(val)
```

<p>The good thing with this approach is that you can iterate through the whole dictionary, but you don't include <code>range</code> which may be confusing later. Also, it is better to assign every df_part directly to a dict instead of assigning <code>N*N</code> variables which may be used once or twice. In this case you can just use <em>1 variable</em> and re-assign it as you progress:</p>

<pre class="lang-py prettyprint-override"><code># code using df1_partN
df1 = df_parts['df1']['partN']
# stuff to do
# happy? checkpoint
df_parts['df1']['partN'] = df1
</code>```

Body:
I have a bunch of very similar commands which all look like this (df means pandas dataframe):

df1_part1=...
df1_part2=...
...
df1_part5=...
df2_part1=...

I would like to make a loop for it, as follows:

for i in range(1,5):
for j in range(1,5):
df%i_part%j=...

Of course, it doesn't work with %. But is has to be some easy way to do it, I suppose.
Could You help me please?

Body:
Assuming that this process is part of data preparation, I would like to mention that you should try to work with "data preparation pipelines" whenever it is possible. Otherwise, the code will be a huge mess to read after a couple of months.

There are several ways to deal with this problem.

A dictionary is the most straightforward way to deal with this.

df_parts = {
            'df1' : {'part1': df1_part1, 'part2': df1_part2,...,'partN': df1_partN},
            'df2' : {'part1': df1_part1, 'part2': df1_part2,...,'partN': df2_partN},
            '...' : {'part1': ..._part1, 'part2': ..._part2,...,'partN': ..._partN},
            'dfN' : {'part1': dfN_part1, 'part2': dfN_part2,...,'partN': dfN_partN},
           }

# print parts from `dfN`
for val in for df_parts['dfN'].values():
    print(val)

# print part1 for all dfs
for df in df_parts.values():
    print(df['part1'])

# print everything
for df in df_parts:
    for val in df_parts[df].values():
        print(val)

The good thing with this approach is that you can iterate through the whole dictionary, but you don't include range which may be confusing later. Also, it is better to assign every df_part directly to a dict instead of assigning N*N variables which may be used once or twice. In this case you can just use 1 variable and re-assign it as you progress:

# code using df1_partN
df1 = df_parts['df1']['partN']
# stuff to do
# happy? checkpoint
df_parts['df1']['partN'] = df1


问:
How to check my firebaseUser contains any displayName or not?
Neither (if firebaseUser.getDisplayName()!=null) this nor the below one is working for me:</p>

```<code>@Override
protected void onStart() {
    super.onStart();
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if (firebaseUser.getDisplayName() == null || firebaseUser.getDisplayName().trim().length() == 0){
        startActivity(new Intent(SecondActivity.this, MainActivity.class));
        finish();
    }
}
</code>```

答:
According to your comment:

No, FirebaseUser contains the UID but do the UID contains the DisplayName is my concern

Yes, FirebaseUser object contains the UID, as well as the name. The getDisplayName() will always return the name, as well as the getUid() returns the UID. There is no way in which getDisplayName() can return the UID as it is not possible that the getUid() method to return the name.

Body:
Neither (if firebaseUser.getDisplayName()!=null) this nor the below one is working for me:

@Override
protected void onStart() {
    super.onStart();
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    if (firebaseUser.getDisplayName() == null || firebaseUser.getDisplayName().trim().length() == 0){
        startActivity(new Intent(SecondActivity.this, MainActivity.class));
        finish();
    }
}


问:
onPageScrollStateChanged(int state): what does state represent
Whenever I set .registerOnPageChangeCallback on my viewpager 3 methods are called, one of them is onPageScrollStateChanged, I want to know what is the variable state represents?</p>

答:
From documentation:

public static final int SCROLL_STATE_DRAGGING

Indicates that the ViewPager2 is currently being dragged by the user,
  or programmatically via fake drag functionality.

Constant Value: 1 (0x00000001)

public static final int SCROLL_STATE_IDLE

Indicates that the ViewPager2 is in an idle, settled state. The
  current page is fully in view and no animation is in progress.

Constant Value: 0 (0x00000000)

public static final int SCROLL_STATE_SETTLING

Indicates that the ViewPager2 is in the process of settling to a final
  position.

Constant Value: 2 (0x00000002)

For more check Documentation


问:
Difference between these two requests
Request One  (Not working)

```<code>{
    "AddNewRequest":{
        "Patient":{
            "PrimaryPhoneNumber":" ",
            "DateOfBirth":" ",
            "CellPhoneNumber1":" ",
            "ResidentialAddress":{
                "AddressLine1":" ",
                "State":" ",
                "City":" ",
                "PostalCode":" "
            },
            "PhoneNumber1":" ",
            "SSN":" ",
            "FullName":"John",
            "Religion":" ",
            "Gender":" ",
            "Race":" ",
            "Firstname":"Vinoth",
            "EmailAddress1":" ",
            "LastName":"Cooper"
        },
        "Header":{
            "SourceSiteID":"300242",
            "DestinationSiteID":"300242",
            "PrimeSuiteUserID":"1"
        },
        "Credentials":{
            "VendorCredential":{
                "VendorLogin":"testGUID",
                "VendorPassword":"testGUID"
            },
            "PrimeSuiteCredential":{
                "PrimeSuiteUserPassword":"password",
                "PrimeSuiteSiteId":"1",
                "PrimeSuiteUserName":"Admin"
            }
        }
    }
}
</code>```

Request Two (Working)

```<code>{
    "PatientAddNewRequest":{
        "Credentials":{
            "PrimeSuiteCredential":{
                "PrimeSuiteSiteId":"300242",
                "PrimeSuiteUserName":"Admin",
                "PrimeSuiteUserPassword":"password"
            },
            "VendorCredential":{
                "VendorLogin":"testGUID",
                "VendorPassword":"testGUID"
            }
        },
        "Header":{
            "DestinationSiteID":"300242",
            "PrimeSuiteUserID":"1",
            ":SourceSiteID":"300242"
        },
        "Patient":{
            "CellPhoneNumber1":"206-567-2222",
            "DateOfBirth":"/Date(1306348200000)/",
            "EmailAddress1":"JohnDoe@yahoo.com",
            "Firstname":"TestMan1",
            "FullName":"TestFullMan1",
            "Gender":"2",
            "LastName":"Testlastname1",
            "PhoneNumber1":"205-567-1111",
            "PrimaryPhoneNumber":"205-456-4545",
            "Race":"2",
            "Religion":"3",
            "ResidentialAddress":{
                "City":"Carrollton",
                "PostalCode":"35209",
                "State":"10"
            },
            "SSN":"911-91-9191"
        }
    }
}
</code>```

I am just not able to figure out why the first request is not working and the second one gives response. Can anyone identify what i am doing wrong.

Does Order Matter?

Update

The First one throws me Bad Request and the second one responds as expected.

答:
We do not know your code that is processing these "requests", but to answer your question:

Yes, order of elements in JSON can matter

...unless your code processes it in a way that is not influenced by the order of them.

For example, if you have two objects:

{prop1: 'abc', prop2: 'xyz'}

{prop2: 'xyz', prop1: 'abc'}

and you process them in the following way in PHP for example:

```<code>$data = json_decode($request_string);
foreach ($data as $key => $value) {
    echo '['.$value.']';
}
</code>```

you should receive following results:

for the first request: [abc][xyz]

for the second request: [xyz][abc]

but if you do it like that:

```<code>$data = json_decode($request_string);
echo '['.$data['prop1'].']['.$data['prop1'].']';
</code>```

you will receive same result in both cases, that is:

```<code>[abc][xyz]
</code>```

Hope that clarifies something.

Title: Difference between these two requests

Body:
Request One  (Not working)

{
    "AddNewRequest":{
        "Patient":{
            "PrimaryPhoneNumber":" ",
            "DateOfBirth":" ",
            "CellPhoneNumber1":" ",
            "ResidentialAddress":{
                "AddressLine1":" ",
                "State":" ",
                "City":" ",
                "PostalCode":" "
            },
            "PhoneNumber1":" ",
            "SSN":" ",
            "FullName":"John",
            "Religion":" ",
            "Gender":" ",
            "Race":" ",
            "Firstname":"Vinoth",
            "EmailAddress1":" ",
            "LastName":"Cooper"
        },
        "Header":{
            "SourceSiteID":"300242",
            "DestinationSiteID":"300242",
            "PrimeSuiteUserID":"1"
        },
        "Credentials":{
            "VendorCredential":{
                "VendorLogin":"testGUID",
                "VendorPassword":"testGUID"
            },
            "PrimeSuiteCredential":{
                "PrimeSuiteUserPassword":"password",
                "PrimeSuiteSiteId":"1",
                "PrimeSuiteUserName":"Admin"
            }
        }
    }
}

Request Two (Working)

{
    "PatientAddNewRequest":{
        "Credentials":{
            "PrimeSuiteCredential":{
                "PrimeSuiteSiteId":"300242",
                "PrimeSuiteUserName":"Admin",
                "PrimeSuiteUserPassword":"password"
            },
            "VendorCredential":{
                "VendorLogin":"testGUID",
                "VendorPassword":"testGUID"
            }
        },
        "Header":{
            "DestinationSiteID":"300242",
            "PrimeSuiteUserID":"1",
            ":SourceSiteID":"300242"
        },
        "Patient":{
            "CellPhoneNumber1":"206-567-2222",
            "DateOfBirth":"/Date(1306348200000)/",
            "EmailAddress1":"JohnDoe@yahoo.com",
            "Firstname":"TestMan1",
            "FullName":"TestFullMan1",
            "Gender":"2",
            "LastName":"Testlastname1",
            "PhoneNumber1":"205-567-1111",
            "PrimaryPhoneNumber":"205-456-4545",
            "Race":"2",
            "Religion":"3",
            "ResidentialAddress":{
                "City":"Carrollton",
                "PostalCode":"35209",
                "State":"10"
            },
            "SSN":"911-91-9191"
        }
    }
}

I am just not able to figure out why the first request is not working and the second one gives response. Can anyone identify what i am doing wrong.

Does Order Matter?

Update

The First one throws me Bad Request and the second one responds as expected.

Body:
We do not know your code that is processing these "requests", but to answer your question:

Yes, order of elements in JSON can matter

...unless your code processes it in a way that is not influenced by the order of them.

For example, if you have two objects:

{prop1: 'abc', prop2: 'xyz'}

{prop2: 'xyz', prop1: 'abc'}

and you process them in the following way in PHP for example:

$data = json_decode($request_string);
foreach ($data as $key => $value) {
    echo '['.$value.']';
}

you should receive following results:

for the first request: [abc][xyz]

for the second request: [xyz][abc]

but if you do it like that:

$data = json_decode($request_string);
echo '['.$data['prop1'].']['.$data['prop1'].']';

you will receive same result in both cases, that is:

[abc][xyz]

Hope that clarifies something.


问:
Oracle-Apex Switch Item value
I have column which is data type number(1,0), I decide to use switch item for this column.
I set custom settings. 1 for On and 0 for off.

When I try to edit column, and use off(0) I get error - Column_name must match the values 1 and 0.
When I use On value all works fine.

答:
Goku, in apex, the best way to learn (you said yourself you're a beginner) is to write a lot of small apps in a dev environment that only perform one thing. That way you can isolate issues and study behavior in detail. I suggest you do the same for this switch item issue to figure out what the problem is. You have not provided enough information for anyone to answer it so users are giving you their best guesses.
So this is what I did. Create test table </p>

```<code>create table so_test_with_switch (
    so_test_with_switch_id         number generated by default on null as identity
                                   constraint so_test_with_switc_id_pk primary key,
    name                           varchar2(255),
    switchval                      number
);
</code>```

<p>Create a report and form in apex, change the form item for switchval page item (P32_SWITCHVAL) to "Switch" with custom settings: 1 for On and 0 for off. I tested and my form worked fine. The error message indicates that the value apex is getting does not match either 1 or 0 so it must get that value from somewhere else. In my case I added an after submit computation to set the value of P32_SWITCHVAL to 'Y'. Saved my changes, ran the form, clicked "Apply Changes" and I got the same error as you.
It is up to you to figure out where your page item is getting the other value from. Go through your page, investigate and debug. The key to finding the solution is in your code.
--Koen </p>

Title: Oracle-Apex Switch Item value

Body:
Goku, in apex, the best way to learn (you said yourself you're a beginner) is to write a lot of small apps in a dev environment that only perform one thing. That way you can isolate issues and study behavior in detail. I suggest you do the same for this switch item issue to figure out what the problem is. You have not provided enough information for anyone to answer it so users are giving you their best guesses.
So this is what I did. Create test table

create table so_test_with_switch (
    so_test_with_switch_id         number generated by default on null as identity
                                   constraint so_test_with_switc_id_pk primary key,
    name                           varchar2(255),
    switchval                      number
);

Create a report and form in apex, change the form item for switchval page item (P32_SWITCHVAL) to "Switch" with custom settings: 1 for On and 0 for off. I tested and my form worked fine. The error message indicates that the value apex is getting does not match either 1 or 0 so it must get that value from somewhere else. In my case I added an after submit computation to set the value of P32_SWITCHVAL to 'Y'. Saved my changes, ran the form, clicked "Apply Changes" and I got the same error as you.
It is up to you to figure out where your page item is getting the other value from. Go through your page, investigate and debug. The key to finding the solution is in your code.
--Koen


问:
How does listeners in Provider work in Flutter?
I am using Provider package to work with data from different locations. For this question, I have created a sample project which consists of a Welcome Screen which shows a Login button, upon click, it redirects to Login Screen where one would have login text field but for now, I have placed a button which on click calls the login function and that login function notifies the listeners. I also have a logout function and boolean value which keeps track of the logged in status.

These functions and values reside in a file called auth.provider.dart in providers directory in lib folder.

import 'package:flutter/foundation.dart';

class Auth with ChangeNotifier {
  var _loggedIn = false;

  bool get loggedIn => _loggedIn;

  void loginUser() {
    _loggedIn = true;
    print('Logged in');
    notifyListeners();
  }

  void logout() {
    _loggedIn = false;
    print('Logged out');
    notifyListeners();
  }
}
```

<p>I am providing the provider in main.dart and also using Consumer:</p>

```class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Auth>(
      create: (_) => Auth(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Consumer<Auth>(
          builder: (_, auth, __) {
            print('main.dart logged in: ${auth.loggedIn}');
            if(auth.loggedIn) return HomeScreen();
            return WelcomeScreen();
          },
        ),
        routes: {
          LoginScreen.routeName: (ctx) => LoginScreen(),
          HomeScreen.routeName: (ctx) => HomeScreen(),
        },
      ),
    );
  }
}
```

<p>In the above file, I simply check whether <code>loggedIn</code> is true or not. If it is not then show the welcome screen so the user can login but if the user is logged in then directly show the home screen. Have also put a print statement in Consumer's builder so it prints the status whenever it gets notified of any changes in auth data. This runs once when the app starts and never again.</p>

<p>There is not much in the login screen, just a scaffold and a login button which calls the login function.</p>

```RaisedButton(
    child: Text('Click to Login'),
    onPressed: () {
      Provider.of<Auth>(context, listen: false).loginUser();
    },
),
```

Now on login button click, it sets the loggedIn boolean to true and notifies the listener which should be Consumer but Consumer in main.dart is never notified of it. It does not trigger the change, there is a condition which checks if logged in is true then show home screen but screen does not change at all. One has to manually use Navigator to move to home screen and on home screen there is a logout button which simply sets loggedIn to false, once that happens it should notify the Consumer but it once again doesn't.

Which now brings me to the question: How does listeners in Provider work? When does it notify the listeners for changes? Will it not notify if the changes occur more than a level down like in the above example, Consumer is in main.dart and the changes occur 2 levels down main.dart > WelcomeScreen > LoginScreen. How to let the Consumer in main.dart know that the underlying data it is using has changed?

If you want to quickly get started with the above example, here is the repository link.

答:
I went through your github code.

With pushReplacementNamed to go to login screen

Initially->main.dart->welcomeScreen->(on-clicking-loginbtn)->LoginScreen

Here,

1)Consumer is not listening(because your initial main.dart screen is replaced by login page and doesnt exist on a page currently to listen)

2)There is no navigator to go back(because page is replaced not in a stack)

With pushNamed to go to login screen

Initially->main.dart->welcomeScreen->(on-clicking-loginbtn)->LoginScreen

Here,

1)Consumer is listening(because your initial main.dart screen is not replaced and exist on a page currently.But you are not seeing the changes because you have covered your main intial page with login screen above in the stack )

2)There is navigator to go back to HomeScreen(Now you can go back to see changes using back arrow)

Conclusion Page will not able to listen to changed Provider Value if the page is replaced by other page. It should be there in a screen listening.

Pattern that can be used

main.dart(home argument)

```<code>home: Consumer<Auth>(
          builder: (_, auth, __) {
            print('main.dart logged in: ${auth.loggedIn}');
            if(auth.loggedIn) return HomeScreen();
            return WelcomeScreen();
          },
        )
</code>```

WelcomeScreen(login code)

```<code> RaisedButton(
              child: Text('Login'),
              onPressed: () => Navigator.of(context).pushReplacementNamed(LoginScreen.routeName),
            )
</code>```

LoginScreen(login button)

```<code>RaisedButton(
          child: Text('Click to Login'),
          onPressed: () {
            Provider.of<Auth>(context, listen: false).loginUser();
            Navigator.of(context).pushReplacementNamed('/');
          },
        )
</code>```

HomeScreen(signout btn)

```<code>RaisedButton(
          child: Text('Logout'),
         onPressed: () {
            Provider.of<Auth>(context, listen: false).logout();
            Navigator.of(context).pushReplacementNamed('/');
          }
</code>```

Body:
I am using Provider package to work with data from different locations. For this question, I have created a sample project which consists of a Welcome Screen which shows a Login button, upon click, it redirects to Login Screen where one would have login text field but for now, I have placed a button which on click calls the login function and that login function notifies the listeners. I also have a logout function and boolean value which keeps track of the logged in status.

These functions and values reside in a file called auth.provider.dart in providers directory in lib folder.

import 'package:flutter/foundation.dart';

class Auth with ChangeNotifier {
  var _loggedIn = false;

  bool get loggedIn => _loggedIn;

  void loginUser() {
    _loggedIn = true;
    print('Logged in');
    notifyListeners();
  }

  void logout() {
    _loggedIn = false;
    print('Logged out');
    notifyListeners();
  }
}

I am providing the provider in main.dart and also using Consumer:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Auth>(
      create: (_) => Auth(),
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
          visualDensity: VisualDensity.adaptivePlatformDensity,
        ),
        home: Consumer<Auth>(
          builder: (_, auth, __) {
            print('main.dart logged in: ${auth.loggedIn}');
            if(auth.loggedIn) return HomeScreen();
            return WelcomeScreen();
          },
        ),
        routes: {
          LoginScreen.routeName: (ctx) => LoginScreen(),
          HomeScreen.routeName: (ctx) => HomeScreen(),
        },
      ),
    );
  }
}

In the above file, I simply check whether loggedIn is true or not. If it is not then show the welcome screen so the user can login but if the user is logged in then directly show the home screen. Have also put a print statement in Consumer's builder so it prints the status whenever it gets notified of any changes in auth data. This runs once when the app starts and never again.

There is not much in the login screen, just a scaffold and a login button which calls the login function.

RaisedButton(
    child: Text('Click to Login'),
    onPressed: () {
      Provider.of<Auth>(context, listen: false).loginUser();
    },
),

Now on login button click, it sets the loggedIn boolean to true and notifies the listener which should be Consumer but Consumer in main.dart is never notified of it. It does not trigger the change, there is a condition which checks if logged in is true then show home screen but screen does not change at all. One has to manually use Navigator to move to home screen and on home screen there is a logout button which simply sets loggedIn to false, once that happens it should notify the Consumer but it once again doesn't.

Which now brings me to the question: How does listeners in Provider work? When does it notify the listeners for changes? Will it not notify if the changes occur more than a level down like in the above example, Consumer is in main.dart and the changes occur 2 levels down main.dart > WelcomeScreen > LoginScreen. How to let the Consumer in main.dart know that the underlying data it is using has changed?

If you want to quickly get started with the above example, here is the repository link.

Body:
I went through your github code.

With pushReplacementNamed to go to login screen

Initially->main.dart->welcomeScreen->(on-clicking-loginbtn)->LoginScreen

Here,

1)Consumer is not listening(because your initial main.dart screen is replaced by login page and doesnt exist on a page currently to listen)

2)There is no navigator to go back(because page is replaced not in a stack)

With pushNamed to go to login screen

Initially->main.dart->welcomeScreen->(on-clicking-loginbtn)->LoginScreen

Here,

1)Consumer is listening(because your initial main.dart screen is not replaced and exist on a page currently.But you are not seeing the changes because you have covered your main intial page with login screen above in the stack )

2)There is navigator to go back to HomeScreen(Now you can go back to see changes using back arrow)

Conclusion Page will not able to listen to changed Provider Value if the page is replaced by other page. It should be there in a screen listening.

Pattern that can be used

main.dart(home argument)

home: Consumer<Auth>(
          builder: (_, auth, __) {
            print('main.dart logged in: ${auth.loggedIn}');
            if(auth.loggedIn) return HomeScreen();
            return WelcomeScreen();
          },
        )

WelcomeScreen(login code)

 RaisedButton(
              child: Text('Login'),
              onPressed: () => Navigator.of(context).pushReplacementNamed(LoginScreen.routeName),
            )

LoginScreen(login button)

RaisedButton(
          child: Text('Click to Login'),
          onPressed: () {
            Provider.of<Auth>(context, listen: false).loginUser();
            Navigator.of(context).pushReplacementNamed('/');
          },
        )

HomeScreen(signout btn)

RaisedButton(
          child: Text('Logout'),
         onPressed: () {
            Provider.of<Auth>(context, listen: false).logout();
            Navigator.of(context).pushReplacementNamed('/');
          }


问:
Referencing .NET dll when compiliation(with mono)
I asked a question to install F# powerpack and use it here.

```<code>error FS0078: Unable to find the file 'FSharp.PowerPack.Linq.dll' in any of
 /Library/Frameworks/Mono.framework/Versions/2.10.2/lib/mono/2.0
 /Users/smcho/Desktop/fs/powerpack
 /Users/smcho/smcho/bin/FSharp-2.0.0.0/bin
</code>```

When I run this command fsc linq.fs /r:FSharp.PowerPack.Linq.dll, I got this error message with mono.

It seems that with /r:, the mono F# compiler seems to find the dll in

/Library/Frameworks/Mono.framework/Versions/2.10.2/lib/mono/2.0 <-- mono directory

/Users/smcho/smcho/bin/FSharp-2.0.0.0/bin <-- F# directory

/Users/smcho/Desktop/fs/powerpack <-- current directory.

However, I don't want to copy all the dll's in the current directory, is there any way to let mono F# or C# compiler know where to find the dll other than those two directory?

It seems that MONO_PATH and gacutil -i is for finding the dll at runtime, not compile time.

ADDED

/I: option is available with fsc compiler.

```<code>fsc linq.fs /I:/bin/FSharpPowerPack-1.9.9.9/bin/gac /r:FSharp.PowerPack.Linq.dll
</code>```

答:
Can't you just use

-r:/full/path/to/the/reference/assembly

?  (You are right that gacutil is for runtime assemblies, whereas -r is for design-time reference assemblies, which may or may not be the same.)

Body:
I asked a question to install F# powerpack and use it here.

error FS0078: Unable to find the file 'FSharp.PowerPack.Linq.dll' in any of
 /Library/Frameworks/Mono.framework/Versions/2.10.2/lib/mono/2.0
 /Users/smcho/Desktop/fs/powerpack
 /Users/smcho/smcho/bin/FSharp-2.0.0.0/bin

When I run this command fsc linq.fs /r:FSharp.PowerPack.Linq.dll, I got this error message with mono.

It seems that with /r:, the mono F# compiler seems to find the dll in

/Library/Frameworks/Mono.framework/Versions/2.10.2/lib/mono/2.0 <-- mono directory

/Users/smcho/smcho/bin/FSharp-2.0.0.0/bin <-- F# directory

/Users/smcho/Desktop/fs/powerpack <-- current directory.

However, I don't want to copy all the dll's in the current directory, is there any way to let mono F# or C# compiler know where to find the dll other than those two directory?

It seems that MONO_PATH and gacutil -i is for finding the dll at runtime, not compile time.

ADDED

/I: option is available with fsc compiler.

fsc linq.fs /I:/bin/FSharpPowerPack-1.9.9.9/bin/gac /r:FSharp.PowerPack.Linq.dll


问:
docker-compose python: can't open file './main.py': [Errno 2] No such file or directory
This is my Dockerfile:

```<code>FROM python:3.8-slim

WORKDIR /proxy-scraper-checker-master

RUN apt-get update && \
    apt-get install -y --no-install-recommends libc-dev

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . /proxy-scraper-checker-master
CMD [ "python", "main.py" ]
</code>```

This is my docker-compose.yml:

```<code>version: "3.3"

services:
    proxy-app:
        build:
            context: .
            dockerfile: Dockerfile
        container_name: proxy-app
</code>```

This is structure of my project dir (from which I run my docker commands):

```<code>├── docker-compose.yml
├── Dockerfile
├── requirements.txt
├── proxy-scraper-checker-master
     └── main.py
</code>```

When I run the following command in the above directory:

docker-compose up

I get the following error message:

```<code>C:\Projects\myprojects\docker-example>docker-compose up
Creating proxy-app ... done
Attaching to proxy-app
proxy-app    | python: can't open file './main.py': [Errno 2] No such file or directory
proxy-app exited with code 2
</code>```

Could someone guide me on what I am doing wrong?

答:
The problem is in the lines.

```<code>COPY . /proxy-scraper-checker-master
CMD [ "python", "main.py" ]
</code>```

You are copying the entire directory into /proxy-scraper-checker-master, so then your main.py file would be /proxy-scraper-checker-master/proxy-scraper-checker-master/main.py.

To debug this, you can enter a bash terminal within the container and look around the directory structure to find main.py. docker-compose will have built the image, so you can find the image name with docker images, or you can rebuild it.

```<code>jakub@dash:/tmp/so$ docker build --tag my_python .
jakub@dash:/tmp/so$ docker run --rm -it my_python bash
# At this point, we are inside the Docker container.
root@924a7f854119:/proxy-scraper-checker-master# pwd
/proxy-scraper-checker-master
root@924a7f854119:/proxy-scraper-checker-master# ls
Dockerfile  docker-compose.yml  proxy-scraper-checker-master  requirements.txt
root@924a7f854119:/proxy-scraper-checker-master# realpath proxy-scraper-checker-master/main.py
/proxy-scraper-checker-master/proxy-scraper-checker-master/main.py
</code>```

At this point, we have found the path to main.py. To fix the original issue, we can change the CMD in the Dockerfile to the following:

```<code>CMD [ "python", "/proxy-scraper-checker-master/proxy-scraper-checker-master/main.py" ]
</code>```

We can improve the Dockerfile to remove redundant COPY instructions. Using the below Dockerfile, the absolute path to main.py is /app/proxy-scraper-checker-master/main.py. We can reference it with the relative path proxy-scraper-checker-master/main.py because we are currently in /app (thanks to the WORKDIR instruction). We could also reference it with the absolute path.

```<code>FROM python:3.8-slim

RUN apt-get update && \
    apt-get install -y --no-install-recommends libc-dev

WORKDIR /app

COPY . .

RUN pip install --no-cache-dir -r requirements.txt

CMD [ "python", "proxy-scraper-checker-master/main.py" ]
</code>```

I recommend reading the COPY documentation to understand its behavior.

Body:
This is my Dockerfile:

FROM python:3.8-slim

WORKDIR /proxy-scraper-checker-master

RUN apt-get update && \
    apt-get install -y --no-install-recommends libc-dev

COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt

COPY . /proxy-scraper-checker-master
CMD [ "python", "main.py" ]

This is my docker-compose.yml:

version: "3.3"

services:
    proxy-app:
        build:
            context: .
            dockerfile: Dockerfile
        container_name: proxy-app

This is structure of my project dir (from which I run my docker commands):

├── docker-compose.yml
├── Dockerfile
├── requirements.txt
├── proxy-scraper-checker-master
     └── main.py

When I run the following command in the above directory:

docker-compose up

I get the following error message:

C:\Projects\myprojects\docker-example>docker-compose up
Creating proxy-app ... done
Attaching to proxy-app
proxy-app    | python: can't open file './main.py': [Errno 2] No such file or directory
proxy-app exited with code 2

Could someone guide me on what I am doing wrong?

Body:
The problem is in the lines.

COPY . /proxy-scraper-checker-master
CMD [ "python", "main.py" ]

You are copying the entire directory into /proxy-scraper-checker-master, so then your main.py file would be /proxy-scraper-checker-master/proxy-scraper-checker-master/main.py.

To debug this, you can enter a bash terminal within the container and look around the directory structure to find main.py. docker-compose will have built the image, so you can find the image name with docker images, or you can rebuild it.

jakub@dash:/tmp/so$ docker build --tag my_python .
jakub@dash:/tmp/so$ docker run --rm -it my_python bash
# At this point, we are inside the Docker container.
root@924a7f854119:/proxy-scraper-checker-master# pwd
/proxy-scraper-checker-master
root@924a7f854119:/proxy-scraper-checker-master# ls
Dockerfile  docker-compose.yml  proxy-scraper-checker-master  requirements.txt
root@924a7f854119:/proxy-scraper-checker-master# realpath proxy-scraper-checker-master/main.py
/proxy-scraper-checker-master/proxy-scraper-checker-master/main.py

At this point, we have found the path to main.py. To fix the original issue, we can change the CMD in the Dockerfile to the following:

CMD [ "python", "/proxy-scraper-checker-master/proxy-scraper-checker-master/main.py" ]

We can improve the Dockerfile to remove redundant COPY instructions. Using the below Dockerfile, the absolute path to main.py is /app/proxy-scraper-checker-master/main.py. We can reference it with the relative path proxy-scraper-checker-master/main.py because we are currently in /app (thanks to the WORKDIR instruction). We could also reference it with the absolute path.

FROM python:3.8-slim

RUN apt-get update && \
    apt-get install -y --no-install-recommends libc-dev

WORKDIR /app

COPY . .

RUN pip install --no-cache-dir -r requirements.txt

CMD [ "python", "proxy-scraper-checker-master/main.py" ]

I recommend reading the COPY documentation to understand its behavior.


问:
Post HttpClient returns either body was null or body was object
Trying to use HttpClient to post data I get two different errors:

With booking being an object I get Backend returned code 400, body was: [object Object].

Using JSON.stringify(booking) I get Backend returned code 415, body was: null.

How so?

```<code>public addBooking(booking): Observable<any[]> {
  return this.http.post<any[]>(`${this.url}bookings`, booking)
    .pipe(
      catchError(this.handleError)
    );
}
</code>```

Object:
Using the following as a test object in swagger works.

```<code>{
  "firstDate": "2020-05-29",
  "secondDate": "2020-05-29",
  "productId": 0,
  "userId": 0
}
</code>```

答:
Try to add Content-Type and Accept headers.

```<code>import {HttpHeaders} from '@angular/common/http';

public addBooking(booking): Observable<any[]> {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    })
  };

  return this.http.post<any[]>(`${this.url}bookings`, booking, httpOptions)
    .pipe(
      catchError(this.handleError)
    );
}
</code>```

It seems, you data is not valid, because 400 is Bad Request. Also, your server respond with the error with [Object object] so I suggest you have to use smth like JSON.stringify on your server to respond with correct errors text

Body:
Trying to use HttpClient to post data I get two different errors:

With booking being an object I get Backend returned code 400, body was: [object Object].

Using JSON.stringify(booking) I get Backend returned code 415, body was: null.

How so?

public addBooking(booking): Observable<any[]> {
  return this.http.post<any[]>(`${this.url}bookings`, booking)
    .pipe(
      catchError(this.handleError)
    );
}

Object:
Using the following as a test object in swagger works.

{
  "firstDate": "2020-05-29",
  "secondDate": "2020-05-29",
  "productId": 0,
  "userId": 0
}

Body:
Try to add Content-Type and Accept headers.

import {HttpHeaders} from '@angular/common/http';

public addBooking(booking): Observable<any[]> {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    })
  };

  return this.http.post<any[]>(`${this.url}bookings`, booking, httpOptions)
    .pipe(
      catchError(this.handleError)
    );
}

It seems, you data is not valid, because 400 is Bad Request. Also, your server respond with the error with [Object object] so I suggest you have to use smth like JSON.stringify on your server to respond with correct errors text


问:
Cant test if a database boolean is true in Laravel
I am trying to query our database to see if users can log in based on whether the organisation they belong to have logins enabled.

LoginController.php

```<code>protected function redirectTo()
{
    $user = Auth::user()->id;
    $userOrg = UserOrganization::where('user_id', $user)->first();
    $org = Organization::where('id', $userOrg->org_id)->first();

    if ($org->allow_org_login == 0) {

        return '/login';
    } else {
        if(Auth::user()->has_changed_temp_password == false)
        {
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/user/password/change';
        } else {
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/overview';
        }
    }
}
</code>```

trying to log in as a user belonging to an organisation with allow_org_login = 0 should redirect to the '/login' page, but instead it either logs the user in or prompts for a password change for a new user.

What am I doing wrong?

Edit: Debug contents of $org (allow_org_login on the bottom line)

答:
since there is many to many relation between user and organization.
i suppose this relation is defined in User & Organization  as in documentation:

https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

considering that:

user may have more than an organization, and if any of the organization allowed log_in the user should login to your system

```<code>$user = Auth::user();
$userOranization=$user->organizations()->get();
$allowUserToLogin=false;
if($userOranization->where('allow_org_login',1)->first()!=null)
$allowUserToLogin=true;
</code>```

and then:

```<code>if ($allowUserToLogin == 0) {

        return '/login';
    } else {  ....
</code>```

Body:
I am trying to query our database to see if users can log in based on whether the organisation they belong to have logins enabled.

LoginController.php

protected function redirectTo()
{
    $user = Auth::user()->id;
    $userOrg = UserOrganization::where('user_id', $user)->first();
    $org = Organization::where('id', $userOrg->org_id)->first();

    if ($org->allow_org_login == 0) {

        return '/login';
    } else {
        if(Auth::user()->has_changed_temp_password == false)
        {
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/user/password/change';
        } else {
            DB::table('users')->where('id', $user)->update(['last_login' => Carbon::now()]);
            DB::table('users')->where('id', $user)->increment('total_logins');
            return '/overview';
        }
    }
}

trying to log in as a user belonging to an organisation with allow_org_login = 0 should redirect to the '/login' page, but instead it either logs the user in or prompts for a password change for a new user.

What am I doing wrong?

Edit: Debug contents of $org (allow_org_login on the bottom line)

Body:
since there is many to many relation between user and organization.
i suppose this relation is defined in User & Organization  as in documentation:

https://laravel.com/docs/7.x/eloquent-relationships#many-to-many

considering that:

user may have more than an organization, and if any of the organization allowed log_in the user should login to your system

$user = Auth::user();
$userOranization=$user->organizations()->get();
$allowUserToLogin=false;
if($userOranization->where('allow_org_login',1)->first()!=null)
$allowUserToLogin=true;

and then:

if ($allowUserToLogin == 0) {

        return '/login';
    } else {  ....


问:
How to play a wav file and make your code continue running in python?
I have this code that plays a video, and detects something on it. Whenever it detects something in the video, I want to hear something, here is the code:

```<code>import cv2
import os
video_capture = cv2.VideoCapture('video')
while True:
    _, frame = video_capture.read()
    found = detect_something(frame)
    if found :
        os.system("aplay 'alarm'")
    cv2.imshow('Video',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()
</code>```

The problem is that, whenever it plays the alarm, the video freezes. I want the alarm to be played as a background sound. How can I do that?

答:
What it needs is a tread:</p>

```<code>import cv2
import os
from threading import Thread # Import Thread here
video_capture = cv2.VideoCapture('video')

def music(): # Define a function to go in the Thread
    os.system("aplay 'alarm'")

while True:
    _, frame = video_capture.read()
    found = detect_something(frame)
    if found :
        mus = Thread(target=music) # Create a Thread each time found
        mus.start() # Start the Thread as soon as created
    cv2.imshow('Video',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()
</code>```

Body:
I have this code that plays a video, and detects something on it. Whenever it detects something in the video, I want to hear something, here is the code:

import cv2
import os
video_capture = cv2.VideoCapture('video')
while True:
    _, frame = video_capture.read()
    found = detect_something(frame)
    if found :
        os.system("aplay 'alarm'")
    cv2.imshow('Video',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()

The problem is that, whenever it plays the alarm, the video freezes. I want the alarm to be played as a background sound. How can I do that?

Body:
What it needs is a tread:

import cv2
import os
from threading import Thread # Import Thread here
video_capture = cv2.VideoCapture('video')

def music(): # Define a function to go in the Thread
    os.system("aplay 'alarm'")

while True:
    _, frame = video_capture.read()
    found = detect_something(frame)
    if found :
        mus = Thread(target=music) # Create a Thread each time found
        mus.start() # Start the Thread as soon as created
    cv2.imshow('Video',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video_capture.release()
cv2.destroyAllWindows()


问:
How to avoid application crashing when launching AlertDialog using AsyncTask() in ANDROID?
In an Android application, by clicking a button, in a fragment, I want to show an AlertDialog using AsynTask() method. I have put, in onPreExecute(), the function which called the AlertDialog. In doInBackground(), there is a task running, and in onPostExecute(), I dismiss the AlertDialog.
The crash occurs just when I click the button. And it refers to line code in the LoadingDialog class, which is dialog.show();. I have tried many suggestions given on the site, but, the issue occurs again.
Could anyone help me?

This is the LoadingDialog.java

```<code>
    public class LoadingDialog {

    private Activity activity;
    private AlertDialog dialog;

    LoadingDialog(Activity myActivity){
        activity = myActivity;
    }

    public void startLoadingDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        LayoutInflater inflater = activity.getLayoutInflater();
        builder.setView(inflater.inflate(R.layout.custom_dialog, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    public void dismissDialog(){
        dialog.dismiss();
    }
    }
</code>```

This is my Fragment class

```<code>
public class MyFragment extends Fragment {

    View view ;
    private Button btn_;
    private Activity activity;
    private AlertDialog dialog;
    private LoadingDialog loadingDialog;

    public MyFragment(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.view = inflater.inflate(R.layout.fragment_, container, false);

        loadingDialog = new LoadingDialog(getActivity());

        btn_ = this.view.findViewById(R.id._button);
        eventListnerReinitialiser();
        return this.view;
    }

    public void eventListnerReinitialiser() {
        this.btn_.setOnClickListener(v -> {
             new ShowDialogAsyncTask().execute();
        });
    }

    public class ShowDialogAsyncTask extends AsyncTask<Void, Void, Void> {
        int s = 0;
        @Override
        protected void onPreExecute() {
            loadingDialog.startLoadingDialog();
            super.onPreExecute();
        }
        @Override
        protected Void doInBackground(Void... params) {
            for(int i=0;i<1000000;i++)
                s = s + i;
            Toast.makeText(view.getContext(), "Valeur de s = "+ s, Toast.LENGTH_LONG).show() ;
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            loadingDialog.dismissDialog();
            super.onPostExecute(result);
        }
    }

}
</code>```

And I have this error log in my console of Android studio

```<code>
    E/WindowManager: android.view.WindowLeaked: Activity com.example.myproject.Menu2Activity has leaked window DecorView@96c506[] that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:511)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:338)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
        at android.app.Dialog.show(Dialog.java:322)
</code>```

答:
In addition to what Vivek said also:

Change the ShowDialogAsyncTask to static class

pass the dialog as WeakReference then use weakReference.get() in each place where it is
used

To show dialog pass context.getApplicationContext() as weak reference.

Currently your Activity is leaking through AsyncTask.

Body:
In an Android application, by clicking a button, in a fragment, I want to show an AlertDialog using AsynTask() method. I have put, in onPreExecute(), the function which called the AlertDialog. In doInBackground(), there is a task running, and in onPostExecute(), I dismiss the AlertDialog.
The crash occurs just when I click the button. And it refers to line code in the LoadingDialog class, which is dialog.show();. I have tried many suggestions given on the site, but, the issue occurs again.
Could anyone help me?

This is the LoadingDialog.java

    public class LoadingDialog {

    private Activity activity;
    private AlertDialog dialog;

    LoadingDialog(Activity myActivity){
        activity = myActivity;
    }

    public void startLoadingDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);

        LayoutInflater inflater = activity.getLayoutInflater();
        builder.setView(inflater.inflate(R.layout.custom_dialog, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }

    public void dismissDialog(){
        dialog.dismiss();
    }
    }

This is my Fragment class

public class MyFragment extends Fragment {

    View view ;
    private Button btn_;
    private Activity activity;
    private AlertDialog dialog;
    private LoadingDialog loadingDialog;

    public MyFragment(){

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.view = inflater.inflate(R.layout.fragment_, container, false);

        loadingDialog = new LoadingDialog(getActivity());

        btn_ = this.view.findViewById(R.id._button);
        eventListnerReinitialiser();
        return this.view;
    }

    public void eventListnerReinitialiser() {
        this.btn_.setOnClickListener(v -> {
             new ShowDialogAsyncTask().execute();
        });
    }

    public class ShowDialogAsyncTask extends AsyncTask<Void, Void, Void> {
        int s = 0;
        @Override
        protected void onPreExecute() {
            loadingDialog.startLoadingDialog();
            super.onPreExecute();
        }
        @Override
        protected Void doInBackground(Void... params) {
            for(int i=0;i<1000000;i++)
                s = s + i;
            Toast.makeText(view.getContext(), "Valeur de s = "+ s, Toast.LENGTH_LONG).show() ;
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            loadingDialog.dismissDialog();
            super.onPostExecute(result);
        }
    }

}

And I have this error log in my console of Android studio

    E/WindowManager: android.view.WindowLeaked: Activity com.example.myproject.Menu2Activity has leaked window DecorView@96c506[] that was originally added here
        at android.view.ViewRootImpl.<init>(ViewRootImpl.java:511)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:338)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
        at android.app.Dialog.show(Dialog.java:322)


问:
Check if packet contains Ethernet layer or a Raw IP packet using DPKT python
I have a some pcap files that I need to extract some information from, those packets are mixed, some are Raw IP and others contains ethernet frames.

I need to conditionally check for the type of packet before parsing as the packets with ethernet frames could be parsed with:

```<code>for ts, buf in pkts:
    if buf contains_ethernet:
        eth = dpkt.ethernet.Ethernet(buf)
        if eth.type == dpkt.ethernet.ETH_TYPE_IP:
            ip = eth.data
        else:
            continue
    else:
        ip = dpkt.ip.IP(buf)
</code>```

How can I define the contains_ethernet as a boolean or a condition?

答:
The pcap header file defines the link type of the capture (Ethernet, Raw IP, ...)

Before processing the packet, you shoud use datalink() of your dpkt.pcap.Reader() object to get the link type of your pcap file. According to your script example :

if <<dpkt.pcap.Reader>>.datalink() == LINKTYPE_ETHERNET:
   ## Process Ethernet frame
elif <<dpkt.pcap.Reader>>.datalink() == LINKTYPE_RAW:
   ## Processs Raw IP datagram
else:
   ## Other link types

Here is the list of link types : http://www.tcpdump.org/linktypes.html

With values LINKTYPE_ETHERNET for Ethernet and LINKTYPE_RAW for Raw IP

Body:
I have a some pcap files that I need to extract some information from, those packets are mixed, some are Raw IP and others contains ethernet frames.

I need to conditionally check for the type of packet before parsing as the packets with ethernet frames could be parsed with:

for ts, buf in pkts:
    if buf contains_ethernet:
        eth = dpkt.ethernet.Ethernet(buf)
        if eth.type == dpkt.ethernet.ETH_TYPE_IP:
            ip = eth.data
        else:
            continue
    else:
        ip = dpkt.ip.IP(buf)

How can I define the contains_ethernet as a boolean or a condition?


问:
Orbit Controls is not a constructor
I followed a tutorial of 2018 in order to add OrbitControls in an existing working project.

These are the lines of code i added:

```<code><script type="text/javascript" src="../libs/OrbitControls.js"></script>

var controls;  // AS A GLOBAL VARIABLE

//following three lines are inside the init()
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.minDistance = 1;
controls.maxDistance = 1000;

//at the animate() function
controls.update();
</code>```

However, nothing is rendered at the browser. When i take a look at the console, i see that:

```<code>Uncaught SyntaxError: Unexpected token '<'     at OrbitControls.js:6
test.html:130 Uncaught TypeError: THREE.OrbitControls is not a constructor
    at init (test.html:130)
</code>```

I found another question with a similar problem but it did not help me.
The only scripts i include are three.js, OrbitControls.js, dat.gui.min.js.

FULL CODE:

```<code><!DOCTYPE html>

<html>

<head>
    <title>Example 01.02 - First Scene</title>
    <script type="text/javascript" src="../libs/three.js"></script>
    <script type="text/javascript" src="../libs/OrbitControls.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
    <style>
        body {
            /* set margin to 0 and overflow to hidden, to go fullscreen */
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>

<!-- Div which will hold the Output -->
<div id="WebGL-output">
</div>

<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">

    window.onload = init();
    animate(); //calling function that does all the rendering

    //GLOBAL VARS
    var scene, camera, renderer;
    var cube;
    var raycaster, mouse;
    var INTERSECTED;

    //global flag
    var isClicked = false;

    //for the camera
    var controls;

//creating and rendering the GUI
params = {
  yAxis: "0.00001"
}
var gui = new dat.GUI();
gui.add(params, "yAxis").onFinishChange(val => {
  cube.scale.y = parseFloat(val);
});

//we make sure to make it hidden
 let vis = gui.domElement.style.visibility;
 gui.domElement.style.visibility = vis == "" ? "hidden" : "";

    // once everything is loaded, we run our Three.js stuff.
    function init() {

        // create a scene, that will hold all our elements such as objects, cameras and lights.
        scene = new THREE.Scene();

        //SET CAMERA
        camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
        camera.position.z = 5;

        // create a render and set the size
        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setClearColor("#e5e5e5"); //background color
        renderer.setSize(window.innerWidth,window.innerHeight); //size of renderer

        //bind rendered to the dom element
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        //RAYCASTER
        raycaster = new THREE.Raycaster();
        mouse = new THREE.Vector2(1,1);

        // create a cube
        var cubeGeometry = new THREE.BoxGeometry(20, 20, 20);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xffff00 }); //0xF7F7F7 = gray
        cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.scale.y = 0.00001;
        cube.userData.originalColor = 0xffff00;

        // position the cube
        cube.position.x = 0;
        cube.position.y = 3;
        cube.position.z = 0;
        /*
        //USEFUL METHODS
        cube.rotation.x +=0.5
        cube.scale.x +=0.5
        */
        // add the cube to the scene
        scene.add(cube);

        /*  RENDERING A PLANE
        var geometry = new THREE.PlaneGeometry( 20, 20);
        var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
        var plane = new THREE.Mesh( geometry, material );
        plane.rotation.set(80,0,0);
        scene.add( plane );
        //plane.position.x = 2;
        */

        //ADDING LIGHTS
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // position and point the camera to the center of the scene
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        //camera
        controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.minDistance = 1;
        controls.maxDistance = 1000;

        // when the mouse moves, call the given function
        document.addEventListener('mousemove', onDocumentMouseMove, false);

        //when the mouse is clicked, call the given function
        document.addEventListener('click', onDocumentMouseClick, false);
    }

    function onDocumentMouseMove(event)
    {
      // the following line would stop any other event handler from firing
      // (such as the mouse's TrackballControls)
      event.preventDefault();

      // update the mouse variable
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //TRY THIS
        // intersects = raycaster.intersectObject(cube); // to get the cube only

        //if the mouse hovers over the cube mesh, change its color to red
        //when mouse leaves the mesh, change it back to its original color
        //ONLY MAKE THESE MODIFICATION IF THE MESH IS NOT CLICKED
        //BECAUSE IF IT IS CLICKED, YOU HAVE TO PAINT THE MESH ACCORDING TO THE onDocumentMouseClick()
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            cube.material.color.set( 0xff0000 );
        }
        else if (isClicked === false)
        {
            cube.material.color.set( cube.userData.originalColor );
        }

    }

    function onDocumentMouseClick(event) //if we detect a click event
    {
        // the following line would stop any other event handler from firing
        // (such as the mouse's TrackballControls)
        event.preventDefault();

        // update the mouse variable
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //if mouse is on top of the mesh when the click occurs, change color of mesh and render GUI
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            isClicked = true;
            cube.material.color.set( 0xF7F7F7 );

/*
            var params = {
                textField: "Enter value:"
            }

                 var item =  gui.add(params, "textField").onFinishChange(function (value) {
                //Do something with the new value
                //console.log(value);
                cube.scale.y +=value;
            });

*/

//when its clicked, change the visibily of the GUI
 vis = gui.domElement.style.visibility;
    gui.domElement.style.visibility = vis == "" ? "hidden" : "";

        }
        //if mouse is on top of the mesh when the click occurs, but it already marked as 'clicked', now mark it as 'unclicked'
        else if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === true)
        {
            isClicked = false;
            cube.material.color.set( cube.userData.originalColor );
            //when its clicked, change the visibily of the GUI
            vis = gui.domElement.style.visibility;
            gui.domElement.style.visibility = vis == "" ? "hidden" : "";
   //         gui.__proto__.constructor.toggleHide()
            //dat.GUI.toggleHide();
            //gui.toggleHide()
        }

    }

    function render()
    {
        // update the picking ray with the camera and mouse position
        raycaster.setFromCamera( mouse, camera );
        renderer.render(scene, camera); //render the scene
    }

    function animate()
    {
        requestAnimationFrame( animate ); //pauses when user switches tab
        controls.update();
        render();
    }

</script>
</body>
</html>
</code>```

答: Did you try removing the "type = text/javascript" when you import OrbitControls.js ?</p>

Title: Orbit Controls is not a constructor

Body:
I followed a tutorial of 2018 in order to add OrbitControls in an existing working project.

These are the lines of code i added:

var controls;  // AS A GLOBAL VARIABLE

//following three lines are inside the init()
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.minDistance = 1;
controls.maxDistance = 1000;

//at the animate() function
controls.update();

However, nothing is rendered at the browser. When i take a look at the console, i see that:

Uncaught SyntaxError: Unexpected token '<'     at OrbitControls.js:6
test.html:130 Uncaught TypeError: THREE.OrbitControls is not a constructor
    at init (test.html:130)

I found another question with a similar problem but it did not help me.
The only scripts i include are three.js, OrbitControls.js, dat.gui.min.js.

FULL CODE:

<!DOCTYPE html>

    <title>Example 01.02 - First Scene</title>


问:
check if the variable contains character a-z or A-Z in Groovy
I'm very new to Groovy and started learning with that.

My requirement is to validate if my input variable contains the character between a-z or A- then I have to remove this particular record.

I tried with

```<code>personIdExternal.text().contains('a-z')
</code>```

I also tried with

```<code>personIdExternal.text().matches("[a-zA-Z]")
</code>```

And neither is working.

Can you guys please help me out?

答:
You can do something like this:</p>

```<code>if(personIdExternal.text() ==~ /.*[A-Za-z].*/) {
   println 'it matches'
} else {
    println 'it does not match'
}
</code>```

Body:
I'm very new to Groovy and started learning with that.

My requirement is to validate if my input variable contains the character between a-z or A- then I have to remove this particular record.

I tried with

personIdExternal.text().contains('a-z')

I also tried with

personIdExternal.text().matches("[a-zA-Z]")

And neither is working.

Can you guys please help me out?

Body:
You can do something like this:

if(personIdExternal.text() ==~ /.*[A-Za-z].*/) {
   println 'it matches'
} else {
    println 'it does not match'
}


问:
Getting error "No templates matched the input template name: blazorwasm."
I'm trying to create a new .net core Blazor WebAssembly App with VS 2019 following this but so far I have had no luck.

As indicated in these docs, I've downloaded the latest preview VS 2019 Professional and typed this on a command window:

```<code>dotnet new blazorwasm --hosted
</code>```

But I keep getting the following error:

```<code>No templates matched the input template name: blazorwasm.
</code>```

This Blazor webAssembly feature is on preview -- it was only released very recently -- and hence understandably prone to errors, but still MS documentation normally is quite accurate, so I'm surprised this is not working as per their explanation.

I would appreciate any help with this.

答:
As mentioned in the comment please install

```<code>dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview9.19424.4
</code>```

Reference

Body:
I'm trying to create a new .net core Blazor WebAssembly App with VS 2019 following this but so far I have had no luck.

As indicated in these docs, I've downloaded the latest preview VS 2019 Professional and typed this on a command window:

dotnet new blazorwasm --hosted

But I keep getting the following error:

No templates matched the input template name: blazorwasm.

This Blazor webAssembly feature is on preview -- it was only released very recently -- and hence understandably prone to errors, but still MS documentation normally is quite accurate, so I'm surprised this is not working as per their explanation.

I would appreciate any help with this.

Body:
As mentioned in the comment please install

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview9.19424.4

Reference


问:
Facing issue " Failed to install the app. Make sure you have the Android development environment " in react native
Would you please help me, I am stuck to create a new project in react-native Like below screenshot. I have able to run old projects. but I am not able to run a new project

I have followed these steps:

react-native init projectName

cd projectName

react-native run-projectName

But I get the error below:

```<code>error Failed to install the app. Make sure you have the Android development environment set up:
</code>```

答: In my case, I was getting this error only when I try to run it on my physical device. Activating Install via USB from Developer Options fixed the problem.

Body:
Would you please help me, I am stuck to create a new project in react-native Like below screenshot. I have able to run old projects. but I am not able to run a new project

I have followed these steps:

react-native init projectName

cd projectName

react-native run-projectName

But I get the error below:

error Failed to install the app. Make sure you have the Android development environment set up:


问:
From python get value from an XML file
in Python, I'm trying to get a value from an XML file but i can't find any similar pattern in other questions.

```<code><Potts>
<!-- Basic properties of CPM (GGH) algorithm -->
<Dimensions z="1" y="150" x="150"/>
<Steps>10000</Steps>
<Temperature>10</Temperature>
</Potts>
<Plugin Name="Volume">
<VolumeEnergyParameters TargetVolume="9" LambdaVolume="5" CellType="cell"/>
</Plugin>
</code>```

I can easily get the value from steps and temperature, but I can't get the value from "LambdaVolume"

The part of my code dealing with this is

```<code>    tree = ET.parse(xmldoc)
    root = tree.getroot()

    for list in root.iter("Temperature"):
        Temperature_tmp = list.text

    for list in root.iter("Steps"):
        Step_tmp = list.text
</code>```

As a reminder, I'm coding in Python and only use the XML made by another software to get initial condition from a simulation. I've never dealt with XML before so I'm quite lost with the whole parents and children thing and its syntax.

Thanks in advance

答: I think your question is already answered here. Please feel free to ask in the comments section if you have any sort of difficulties.</p>

Title: From python get value from an XML file

Body:
in Python, I'm trying to get a value from an XML file but i can't find any similar pattern in other questions.

<Potts>

<Dimensions z="1" y="150" x="150"/>
<Steps>10000</Steps>
<Temperature>10</Temperature>
</Potts>
<Plugin Name="Volume">
<VolumeEnergyParameters TargetVolume="9" LambdaVolume="5" CellType="cell"/>
</Plugin>

I can easily get the value from steps and temperature, but I can't get the value from "LambdaVolume"

The part of my code dealing with this is

    tree = ET.parse(xmldoc)
    root = tree.getroot()

    for list in root.iter("Temperature"):
        Temperature_tmp = list.text

    for list in root.iter("Steps"):
        Step_tmp = list.text

As a reminder, I'm coding in Python and only use the XML made by another software to get initial condition from a simulation. I've never dealt with XML before so I'm quite lost with the whole parents and children thing and its syntax.

Thanks in advance