问:
how to optimize count(*)queries on tidb
I have a table with about 3000000 rows described as below.

```<code>Field             |Type        |Null|Key|Default|Extra         |
------------------|------------|----|---|-------|--------------|
id                |bigint(20)  |NO  |PRI|       |auto_increment|
entity_name       |varchar(50) |YES |   |       |              |
field_type        |varchar(50) |YES |MUL|       |              |
kv_key            |text        |YES |MUL|       |              |
kv_value          |text        |YES |MUL|       |              |
value_type        |int(11)     |YES |   |       |              |
dataset_id        |varchar(255)|YES |MUL|       |              |
dataset_version_id|varchar(255)|YES |MUL|       |              |
experiment_id     |varchar(255)|YES |MUL|       |              |
experiment_run_id |varchar(255)|YES |MUL|       |              |
job_id            |varchar(255)|YES |MUL|       |              |
project_id        |varchar(255)|YES |MUL|       |              |
</code>```

It has indexes as

```<code>Table   |Non_unique|Key_name     |Seq_in_index|Column_name       |Collation|Cardinality|Sub_part|Packed|Null|Index_type|Comment|Index_comment|
--------|----------|-------------|------------|------------------|---------|-----------|--------|------|----|----------|-------|-------------|
keyvalue|         0|PRIMARY      |           1|id                |A        |          0|        |      |    |BTREE     |       |             |
keyvalue|         1|kv_dsv_id    |           1|dataset_version_id|A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_p_id      |           1|project_id        |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_j_id      |           1|job_id            |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_e_id      |           1|experiment_id     |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_d_id      |           1|dataset_id        |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_er_id     |           1|experiment_run_id |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_field_type|           1|field_type        |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_kv_val    |           1|kv_value          |A        |          0|     255|      |YES |BTREE     |       |             |
keyvalue|         1|kv_kv_key    |           1|kv_key            |A        |          0|     255|      |YES |BTREE     |       |             |
</code>```

an Explain of select count(*) return in 178ms with a plan

```<code>id                |count     |task|operator info                                                                |
------------------|----------|----|-----------------------------------------------------------------------------|
StreamAgg_48      |1.00      |root|funcs:count(col_0)                                                           |
└─IndexReader_49  |1.00      |root|index:StreamAgg_8                                                            |
  └─StreamAgg_8   |1.00      |cop |funcs:count(1)                                                               |
    └─IndexScan_39|2964754.00|cop |table:keyvalue, index:dataset_version_id, range:[NULL,+inf], keep order:false|
</code>```

and the actual query takes about 2.6 sec.

trace format = 'row' select count(*) from keyvalue;

```<code>operation            |startTS        |duration    |
---------------------|---------------|------------|
session.getTxnFuture |20:21:00.074939|6.455µs     |
  ├─session.Execute  |20:21:00.074937|999.484µs   |
  ├─session.ParseSQL |20:21:00.074980|17.226µs    |
  ├─executor.Compile |20:21:00.075010|340.281µs   |
  ├─session.runStmt  |20:21:00.075370|525.307µs   |
  ├─session.CommitTxn|20:21:00.075882|3.542µs     |
  ├─recordSet.Next   |20:21:00.075946|2.585509798s|
  ├─streamAgg.Next   |20:21:00.075948|2.585497556s|
  ├─tableReader.Next |20:21:00.075950|2.585418751s|
  ├─tableReader.Next |20:21:02.661433|2.77µs      |
  ├─recordSet.Next   |20:21:02.661488|11.319µs    |
  └─streamAgg.Next   |20:21:02.661491|587ns       |
</code>```

My tidb setup is as follows

```<code>storage--tidb-discovery-f96cbd845-kgbvx                        1/1     Running   0          94d
storage--tidb-operator--controller-manager-fff86dd78-b7rmh     1/1     Running   0          3d19h
storage--tidb-pd-0                                             1/1     Running   0          3d18h
storage--tidb-pd-1                                             1/1     Running   0          3d18h
storage--tidb-pd-2                                             1/1     Running   0          3d18h
storage--tidb-tidb-0                                           2/2     Running   0          3d18h
storage--tidb-tidb-1                                           2/2     Running   0          3d18h
storage--tidb-tidb-initializer-9fff8f78d-gh4pr                 1/1     Running   0          3d22h
storage--tidb-tikv-0                                           1/1     Running   0          3d18h
storage--tidb-tikv-1                                           1/1     Running   0          3d18h
storage--tidb-tikv-2                                           1/1     Running   0          3d18h
storage--tidb-tikv-3                                           1/1     Running   0          3d18h

</code>```

TIDB version

```<code>version()         |
------------------|
5.7.25-TiDB-v3.0.4|
</code>```

How can I speed up the query? I am also curious why did the query pick the index it chose.

答:
I'm a developer of TiDB. For your questions:

How to speed up the query?

There are 3000000 rows in the table and SQL is a very simple one. The execution plan is already the best one (with the partial aggregation push to TiKV). So I suggest you increase some execution concurrency like follows:

```<code>tidb(localhost:4000) > show variables like "%concurrency%";
+------------------------------------+-------+
| Variable_name                      | Value |
+------------------------------------+-------+
| innodb_commit_concurrency          | 0     |
| innodb_concurrency_tickets         | 5000  |
| innodb_thread_concurrency          | 0     |
| thread_concurrency                 | 10    |
| tidb_build_stats_concurrency       | 4     |
| tidb_checksum_table_concurrency    | 4     |
| tidb_distsql_scan_concurrency      | 15    |
| tidb_hash_join_concurrency         | 5     |
| tidb_hashagg_final_concurrency     | 4     |
| tidb_hashagg_partial_concurrency   | 4     |
| tidb_index_lookup_concurrency      | 4     |
| tidb_index_lookup_join_concurrency | 4     |
| tidb_index_serial_scan_concurrency | 1     |
| tidb_opt_concurrency_factor        | 3     |
| tidb_projection_concurrency        | 4     |
| tidb_window_concurrency            | 4     |
+------------------------------------+-------+
16 rows in set (0.01 sec)
</code>```

For your SQL, the tidb_distsql_scan_concurrency maybe works. It's better to set it as your (number of CPU cores / 8 * 15). You can use set session/global tidb_distsql_scan_concurrency=? to change it.

Why did the query pick the index?

Because count(*) is equivalent to count(1), the bytes of an index key-value pair is smaller than the key-value pair scanned by TableScan plan. There are some blogs FYI:

TiDB Internal (I) - Data Storage

TiDB Internal (II) - Computing

TiDB Internal (III) - Scheduling

Title: how to optimize count(*)queries on tidb

Body:
I have a table with about 3000000 rows described as below.

Field             |Type        |Null|Key|Default|Extra         |
------------------|------------|----|---|-------|--------------|
id                |bigint(20)  |NO  |PRI|       |auto_increment|
entity_name       |varchar(50) |YES |   |       |              |
field_type        |varchar(50) |YES |MUL|       |              |
kv_key            |text        |YES |MUL|       |              |
kv_value          |text        |YES |MUL|       |              |
value_type        |int(11)     |YES |   |       |              |
dataset_id        |varchar(255)|YES |MUL|       |              |
dataset_version_id|varchar(255)|YES |MUL|       |              |
experiment_id     |varchar(255)|YES |MUL|       |              |
experiment_run_id |varchar(255)|YES |MUL|       |              |
job_id            |varchar(255)|YES |MUL|       |              |
project_id        |varchar(255)|YES |MUL|       |              |

It has indexes as

Table   |Non_unique|Key_name     |Seq_in_index|Column_name       |Collation|Cardinality|Sub_part|Packed|Null|Index_type|Comment|Index_comment|
--------|----------|-------------|------------|------------------|---------|-----------|--------|------|----|----------|-------|-------------|
keyvalue|         0|PRIMARY      |           1|id                |A        |          0|        |      |    |BTREE     |       |             |
keyvalue|         1|kv_dsv_id    |           1|dataset_version_id|A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_p_id      |           1|project_id        |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_j_id      |           1|job_id            |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_e_id      |           1|experiment_id     |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_d_id      |           1|dataset_id        |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_er_id     |           1|experiment_run_id |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_field_type|           1|field_type        |A        |          0|        |      |YES |BTREE     |       |             |
keyvalue|         1|kv_kv_val    |           1|kv_value          |A        |          0|     255|      |YES |BTREE     |       |             |
keyvalue|         1|kv_kv_key    |           1|kv_key            |A        |          0|     255|      |YES |BTREE     |       |             |

an Explain of select count(*) return in 178ms with a plan

id                |count     |task|operator info                                                                |
------------------|----------|----|-----------------------------------------------------------------------------|
StreamAgg_48      |1.00      |root|funcs:count(col_0)                                                           |
└─IndexReader_49  |1.00      |root|index:StreamAgg_8                                                            |
  └─StreamAgg_8   |1.00      |cop |funcs:count(1)                                                               |
    └─IndexScan_39|2964754.00|cop |table:keyvalue, index:dataset_version_id, range:[NULL,+inf], keep order:false|

and the actual query takes about 2.6 sec.

trace format = 'row' select count(*) from keyvalue;

operation            |startTS        |duration    |
---------------------|---------------|------------|
session.getTxnFuture |20:21:00.074939|6.455µs     |
  ├─session.Execute  |20:21:00.074937|999.484µs   |
  ├─session.ParseSQL |20:21:00.074980|17.226µs    |
  ├─executor.Compile |20:21:00.075010|340.281µs   |
  ├─session.runStmt  |20:21:00.075370|525.307µs   |
  ├─session.CommitTxn|20:21:00.075882|3.542µs     |
  ├─recordSet.Next   |20:21:00.075946|2.585509798s|
  ├─streamAgg.Next   |20:21:00.075948|2.585497556s|
  ├─tableReader.Next |20:21:00.075950|2.585418751s|
  ├─tableReader.Next |20:21:02.661433|2.77µs      |
  ├─recordSet.Next   |20:21:02.661488|11.319µs    |
  └─streamAgg.Next   |20:21:02.661491|587ns       |

My tidb setup is as follows

storage--tidb-discovery-f96cbd845-kgbvx                        1/1     Running   0          94d
storage--tidb-operator--controller-manager-fff86dd78-b7rmh     1/1     Running   0          3d19h
storage--tidb-pd-0                                             1/1     Running   0          3d18h
storage--tidb-pd-1                                             1/1     Running   0          3d18h
storage--tidb-pd-2                                             1/1     Running   0          3d18h
storage--tidb-tidb-0                                           2/2     Running   0          3d18h
storage--tidb-tidb-1                                           2/2     Running   0          3d18h
storage--tidb-tidb-initializer-9fff8f78d-gh4pr                 1/1     Running   0          3d22h
storage--tidb-tikv-0                                           1/1     Running   0          3d18h
storage--tidb-tikv-1                                           1/1     Running   0          3d18h
storage--tidb-tikv-2                                           1/1     Running   0          3d18h
storage--tidb-tikv-3                                           1/1     Running   0          3d18h

TIDB version

version()         |
------------------|
5.7.25-TiDB-v3.0.4|

How can I speed up the query? I am also curious why did the query pick the index it chose.

Body:
I'm a developer of TiDB. For your questions:

How to speed up the query?

There are 3000000 rows in the table and SQL is a very simple one. The execution plan is already the best one (with the partial aggregation push to TiKV). So I suggest you increase some execution concurrency like follows:

tidb(localhost:4000) > show variables like "%concurrency%";
+------------------------------------+-------+
| Variable_name                      | Value |
+------------------------------------+-------+
| innodb_commit_concurrency          | 0     |
| innodb_concurrency_tickets         | 5000  |
| innodb_thread_concurrency          | 0     |
| thread_concurrency                 | 10    |
| tidb_build_stats_concurrency       | 4     |
| tidb_checksum_table_concurrency    | 4     |
| tidb_distsql_scan_concurrency      | 15    |
| tidb_hash_join_concurrency         | 5     |
| tidb_hashagg_final_concurrency     | 4     |
| tidb_hashagg_partial_concurrency   | 4     |
| tidb_index_lookup_concurrency      | 4     |
| tidb_index_lookup_join_concurrency | 4     |
| tidb_index_serial_scan_concurrency | 1     |
| tidb_opt_concurrency_factor        | 3     |
| tidb_projection_concurrency        | 4     |
| tidb_window_concurrency            | 4     |
+------------------------------------+-------+
16 rows in set (0.01 sec)

For your SQL, the tidb_distsql_scan_concurrency maybe works. It's better to set it as your (number of CPU cores / 8 * 15). You can use set session/global tidb_distsql_scan_concurrency=? to change it.

Why did the query pick the index?

Because count(*) is equivalent to count(1), the bytes of an index key-value pair is smaller than the key-value pair scanned by TableScan plan. There are some blogs FYI:

TiDB Internal (I) - Data Storage

TiDB Internal (II) - Computing

TiDB Internal (III) - Scheduling


来源: stackexchange

问:
How to Constrain a Django Model Table to One Row
I want to create a table with only one row in MySQL database. It's for site settings. This is the SQL for it that I found in another question on this site:

```<code>CREATE TABLE T1(
Lock char(1) not null DEFAULT 'X',
/* Other columns */,
constraint PK_T1 PRIMARY KEY (Lock),
constraint CK_T1_Locked CHECK (Lock='X')
)
</code>```

Can I do this in a Django model program? So far, I have:

```<code>from django.db import models

class Settings(models.Model):
    lock = models.CharField(max_length=1, null=False, primary_key=True, default='X')
    employer_day_date = models.DateField

    class Meta:
        constraints = [CheckContraint()]
</code>```

I can add class Meta: to it, but PyCharm doesn't recognize CheckConstraint so I haven't gone any further with it. I have no problems doing it in SQL if that's the only way.

I was thinking of altering the database after the migration, but it seemed rather crude.

Solution

I used @ruddra code and some from the article he sited:

```<code>class SiteSettings(models.Model):
lock = models.CharField(max_length=1, null=False, primary_key=True, default='X')
employer_day_date = models.DateField()

def save(self, *args, **kwargs):
   self.pk = 'X'
   super().save(*args, **kwargs)

def delete(self, *args, **kwargs):
   pass

@classmethod
def load(cls):
    obj, created = cls.objects.get_or_create(pk='X')
    return obj
</code>```

After running migrate, I registered the Class in admin and then viewed the table in admin. There were no rows. I don't know if the load class method didn't work or load wasn't called. Once the row is set up, it's no longer needed. I tested the delete. I asked me if I was sure I wanted to delete it. I chose yes. The row was still there afterwards.

答:
Basically you are trying to achieve Singleton pattern in Django models. So, here you can override the save method here:

```<code>from django.db import models

class Settings(models.Model):
    lock = models.CharField(max_length=1, null=False, primary_key=True, default='X')
    employer_day_date = models.DateField()

    def save(self, *args, **kwargs):
       self.pk = 'X'
       super().save(*args, **kwargs)
</code>```

The answer is based on this article, there you can find some nice examples on how to use Singleton pattern in Django models.

ContentLicense: CC BY-SA 4.0

Body:
I want to create a table with only one row in MySQL database. It's for site settings. This is the SQL for it that I found in another question on this site:

CREATE TABLE T1(
Lock char(1) not null DEFAULT 'X',
/* Other columns */,
constraint PK_T1 PRIMARY KEY (Lock),
constraint CK_T1_Locked CHECK (Lock='X')
)

Can I do this in a Django model program? So far, I have:

from django.db import models

class Settings(models.Model):
    lock = models.CharField(max_length=1, null=False, primary_key=True, default='X')
    employer_day_date = models.DateField

    class Meta:
        constraints = [CheckContraint()]

I can add class Meta: to it, but PyCharm doesn't recognize CheckConstraint so I haven't gone any further with it. I have no problems doing it in SQL if that's the only way.

I was thinking of altering the database after the migration, but it seemed rather crude.

Solution

I used @ruddra code and some from the article he sited:

class SiteSettings(models.Model):
lock = models.CharField(max_length=1, null=False, primary_key=True, default='X')
employer_day_date = models.DateField()

def save(self, *args, **kwargs):
   self.pk = 'X'
   super().save(*args, **kwargs)

def delete(self, *args, **kwargs):
   pass

@classmethod
def load(cls):
    obj, created = cls.objects.get_or_create(pk='X')
    return obj

After running migrate, I registered the Class in admin and then viewed the table in admin. There were no rows. I don't know if the load class method didn't work or load wasn't called. Once the row is set up, it's no longer needed. I tested the delete. I asked me if I was sure I wanted to delete it. I chose yes. The row was still there afterwards.

Body:
Basically you are trying to achieve Singleton pattern in Django models. So, here you can override the save method here:

from django.db import models

class Settings(models.Model):
    lock = models.CharField(max_length=1, null=False, primary_key=True, default='X')
    employer_day_date = models.DateField()

    def save(self, *args, **kwargs):
       self.pk = 'X'
       super().save(*args, **kwargs)

The answer is based on this article, there you can find some nice examples on how to use Singleton pattern in Django models.


问:
Dynamicallly retrieve Spring Boot CORS Configuration from database for specific method in a Controller
I am trying to set the CORS configuration at Controller level using

```<code>@CrossOrigin on Controller and Handler Method

public class AccountController {

@CrossOrigin("retreive data from DB")
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
    // ...
}
</code>```

}

I have tried using below  but its set only when the spring boot starts and takes changes only when the service is restarted next time ...

```<code>@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
   // CorsConfiguration config = jHipsterProperties.getCors();

       CorsConfiguration config=CorsService.fetchCorsConfigFromDb;
    if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
        log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);
        source.registerCorsConfiguration("/management/**", config);
        source.registerCorsConfiguration("/v2/api-docs", config);
    }
    return new CorsFilter(source);
}
</code>```

fetchCorsConfigFromDb will fetch data from DB. Any changes from DB will be reflected only when Spring Boot App is restarted...

答:
For CorsService.fetchCorsConfigFromDb;
it should load from cache

then you can update your cache at run-time

you should implement CorsService.fetchCorsConfig();

this method should look for any cors configuration in cache first ,if there any configurations found load it directly from cache else you will retrive cors from db and update your cache

create update cors at runtime method CorsService.updateCorsConfig(); , this should update your cors in db and then update cache .

Body:
I am trying to set the CORS configuration at Controller level using

@CrossOrigin on Controller and Handler Method

public class AccountController {

@CrossOrigin("retreive data from DB")
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
    // ...
}

}

I have tried using below  but its set only when the spring boot starts and takes changes only when the service is restarted next time ...

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
   // CorsConfiguration config = jHipsterProperties.getCors();

       CorsConfiguration config=CorsService.fetchCorsConfigFromDb;
    if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
        log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);
        source.registerCorsConfiguration("/management/**", config);
        source.registerCorsConfiguration("/v2/api-docs", config);
    }
    return new CorsFilter(source);
}

fetchCorsConfigFromDb will fetch data from DB. Any changes from DB will be reflected only when Spring Boot App is restarted...


问:
Default Schema not being applied even after setting default schema and default DB
I have an interesting problem! Let me set the stage for you:

1) Windows Authentication

2) Default Schema identityiq has been set for the user with login XCORP\USERA

3) Default Database identityiq has been set for the user with login XCORP\USERA

4) XCORP\USERA does NOT have sysadmin

5) XCORP\USERA is the owner of the DB

6) Have attempted to run new database setup scripts (took down and rebuilt database)

Ok so as I mentioned - it is interesting for the following reasons - I have a DB account (which we will call IdentityIQUSER) which uses SQL Login authentication with the exact same setup that works just fine! (Exact same setup meaning things that I can check and uncheck in nice little boxes) I can make calls with no issues with the SQL account. Only when I use the windows account am I finding problems. After doing some soul searching I ran the following command that led me to the path that something was amiss (possible with the login) Select SCHEMA_NAME(); and interestingly enough what is returned is not identityiq but dbo so I did some more digging and came across a mountain of effective access. I can provide a list if that would be helpful. So here is my question which is three-fold.

Question 1: Is there any effective access that can be granted that would cause DBO to be the default schema (similar to what happens with sysadmin)

Question 2: Can AD groups control what effective access you are getting on a server? If the answer here is yes, does anyone know how I can track down what group in AD is granting these effective access rights?

Question 3: I have never been this deep in the DB - so I may not be looking at the right thing, so if this isn't the right direction to be marching where else should I look?

Also as a side note, I was looking to see if I could override the effective access with explicit access (since I believe Deny takes precedence) and annoyingly when I logged back in all of my access had been restored...I am probably the first person ever to complain about too much access. lol Thank you for taking the time to look.

答:
Ok after much troubleshooting and digging, we found our answer! We were aware that groups that are coming from AD can have sysadmin set and that will override anything that is natively set. However, what we didn't know is that if an account is created and added through the MSSQL interface that is connected to this group, it will also carry that server role, even if natively it is off. So let me explain more succinctly.

Step 1:
Group A is set to carry the sysadmin role and is an AD group and has been added to MSSQL.
Group A - Contains XCORP\USER1

Step2:
XCORP\USER1 adds XCORP\USER2 to MSSQL.

following this sequence XCORP\USER2 is now permanently part of the sysadmin role...I don't have any idea why this logic is followed, but it is the end result.

So to fix it:

Step 1: Use an account that is NOT part of the group that contains sysadmin role
Step 2: Add another domain user
Step 3: Celebrate that you have a normal account.


问:
Trying to perform selenium testing using chrome driver but facing issue with below error while executing in cli as headless browser

tests are performed in ubuntu machine (cli)

<<< FAILURE!

org.openqa.selenium.WebDriverException: unknown error: Chrome failed
  to start: exited abnormally   (unknown error: DevToolsActivePort file
  doesn't exist)   (The process started from chrome location
  /usr/bin/google-chrome is no longer running, so ChromeDriver is
  assuming that Chrome has crashed.)

Both google-chrome and chromedriver are installed under /usr/bin/

Code sample:

```<code>System.setProperty("webdriver.chrome.driver",
"/usr/bin/chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary(System.getProperty("user.dir") + "/usr/bin/chromedriver");
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--disable-dev-shm-usage");
chromeOptions.addArguments("--headless");
WebDriver driver = new ChromeDriver();
driver.get("file:///" + destFilePath);
</code>```

答: I found a workaround by starting chrome at --no-sandbox mode (which is not the best practice). So it's a permission issue.</p>

Body:
tests are performed in ubuntu machine (cli)

<<< FAILURE!

org.openqa.selenium.WebDriverException: unknown error: Chrome failed
  to start: exited abnormally   (unknown error: DevToolsActivePort file
  doesn't exist)   (The process started from chrome location
  /usr/bin/google-chrome is no longer running, so ChromeDriver is
  assuming that Chrome has crashed.)

Both google-chrome and chromedriver are installed under /usr/bin/

Code sample:

System.setProperty("webdriver.chrome.driver",
"/usr/bin/chromedriver");
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setBinary(System.getProperty("user.dir") + "/usr/bin/chromedriver");
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--disable-dev-shm-usage");
chromeOptions.addArguments("--headless");
WebDriver driver = new ChromeDriver();
driver.get("file:///" + destFilePath);


问:
Why include when you can require in PHP?
What is the point of attempting to include or include_once a library in PHP if you often have to use require or require_once instead (as they're usually critically important)?

答:
Difference just in error handling, when required file doesn't exists: in case of include you can easily handle warning, change execution to show normal 'Sorry, error' page, send notification to site's admin.

In case of require your script will just stopped, fatal error is more difficult to handle, and you can't show any message to user.

ContentLicense: CC BY-SA 3.0


问:
React Native: Unable to center Text in View component
I am unable to center a Text component in a View component in React Native both on android as well as ios.

As you can see the + sign in not centred in the white circle.

This is my component:

```<code>
<TouchableOpacity
    style={styles.blueButton}
>
    <View style={styles.addButton}>
        <Text style={styles.plus}>+</Text>
    </View>
</TouchableOpacity>
</code>```

This is my stylesheet:

```<code>blueButton: {
    height: 40,
    width: 40,
    borderRadius: 3,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#3498DB',
},
addButton: {
    width: 15,
    height: 15,
    borderRadius: 30,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
},
plus: {
    color: '#3498DB',
    fontSize: 20,
},
</code>```

答:
Can you try my below code:

Compnent code:

```<code><View style={styles.addButtonBlue}>
  <View style={styles.addButton}>
    <Text style={styles.plus}>+</Text>
  </View>
</View>
</code>```

Stylesheet Code

```<code>addButtonBlue: {
  width: 70,
  height: 70,
  borderRadius: 10,
  justifyContent: 'center',
  alignContent: 'center',
  alignItems: 'center',
  backgroundColor: '#3498db',
},
addButton: {
  width: 30,
  height: 30,
  borderRadius: 30,
  justifyContent: 'center',
  alignContent: 'center',
  alignItems: 'center',
  backgroundColor: '#fff',
},
plus: {
    color: '#3498DB',
},
</code>```

Body:
I am unable to center a Text component in a View component in React Native both on android as well as ios.

As you can see the + sign in not centred in the white circle.

This is my component:

<TouchableOpacity
    style={styles.blueButton}
>
    <View style={styles.addButton}>
        <Text style={styles.plus}>+</Text>
    </View>
</TouchableOpacity>

This is my stylesheet:

blueButton: {
    height: 40,
    width: 40,
    borderRadius: 3,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#3498DB',
},
addButton: {
    width: 15,
    height: 15,
    borderRadius: 30,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'white',
},
plus: {
    color: '#3498DB',
    fontSize: 20,
},

Body:
Can you try my below code:

Compnent code:

<View style={styles.addButtonBlue}>
  <View style={styles.addButton}>
    <Text style={styles.plus}>+</Text>
  </View>
</View>

Stylesheet Code

addButtonBlue: {
  width: 70,
  height: 70,
  borderRadius: 10,
  justifyContent: 'center',
  alignContent: 'center',
  alignItems: 'center',
  backgroundColor: '#3498db',
},
addButton: {
  width: 30,
  height: 30,
  borderRadius: 30,
  justifyContent: 'center',
  alignContent: 'center',
  alignItems: 'center',
  backgroundColor: '#fff',
},
plus: {
    color: '#3498DB',
},


问:
Writing to file a list where a unique string from column 1 gets multiple strings from column 2
I am totally new to python and need help.  I have a table that has 2 columns.  Column 1 contains the Genus and Column 2 contains Species.  I can iterate through the columns using SearchCursor and print out each row with a genus and a species.  What I need to do is print out a unique genus with all of its associated species.  So for example I have:

```<code>Acer    Maple
Acer    Sugar Maple
Acer    Purple Maple
Abies   Jack Pine
Abies    Spruce
</code>```

I want

```<code>Acer|Maple|Sugar Maple|Purple Maple
Abies|Jack Pine|Spruce
</code>```

I have tried but I can not figure out if I need a while loop, and if loop or a for loop.  When I try while and if my loops go on forever.

Here one attempt:

```<code>myCursor1=arcpy.da.SearchCursor(FreqGISTable,["Genus","Species"])
for row in myCursor1:
    gisfile.write((row[0]).upper())
    if (row[0] == row[0]):
          gisfile.write(row[1])
    else:
         if (row[0] != row[0]):
            gisfile.write("END\n")

gisfile.close()
return gisfile
</code>```

So thank you for the help. I had to tweak it a bit. The code works for the most part however, I need it to print all of the col2 items then print "END_OPTIONS|\n" at the very end of the line.

I have tried numerous ways to set it up but it doesn't work. The line = row['col2'] + "|" will not recognize the "|" and when I try to insert the final End Options it places it right after each col2 item.  Any suggestions to fix that?

答:
Here is one of the approach which answered by my friend Kavish:

```<code>df = pd.DataFrame({'col1': ['Acer','Acer','Acer','Abies','Abies'], 'col2' : ['Maple','Sugar Maple','Purple Maple','Jack Pine','Spruce']})
df
</code>```

```<code>col1    col2
0   Acer    Maple
1   Acer    Sugar Maple
2   Acer    Purple Maple
3   Abies   Jack Pine
4   Abies   Spruce
</code>```

```<code>line = ""
classes = df['col1'].unique()
for c in classes:
    line = line + c + "|"
    for index, row in df.iterrows():
        if(row['col1'] == c):
            line = line + row['col2'] + "|"
    line = line[:-1]
    line = line + '\n'

print(line)

Acer|Maple|Sugar Maple|Purple Maple
Abies|Jack Pine|Spruce
</code>```

Credit to https://stackoverflow.com/users/12910033/kavish

Body:
I am totally new to python and need help.  I have a table that has 2 columns.  Column 1 contains the Genus and Column 2 contains Species.  I can iterate through the columns using SearchCursor and print out each row with a genus and a species.  What I need to do is print out a unique genus with all of its associated species.  So for example I have:

Acer    Maple
Acer    Sugar Maple
Acer    Purple Maple
Abies   Jack Pine
Abies    Spruce

I want

Acer|Maple|Sugar Maple|Purple Maple
Abies|Jack Pine|Spruce

I have tried but I can not figure out if I need a while loop, and if loop or a for loop.  When I try while and if my loops go on forever.

Here one attempt:

myCursor1=arcpy.da.SearchCursor(FreqGISTable,["Genus","Species"])
for row in myCursor1:
    gisfile.write((row[0]).upper())
    if (row[0] == row[0]):
          gisfile.write(row[1])
    else:
         if (row[0] != row[0]):
            gisfile.write("END\n")

gisfile.close()
return gisfile

So thank you for the help. I had to tweak it a bit. The code works for the most part however, I need it to print all of the col2 items then print "END_OPTIONS|\n" at the very end of the line.

I have tried numerous ways to set it up but it doesn't work. The line = row['col2'] + "|" will not recognize the "|" and when I try to insert the final End Options it places it right after each col2 item.  Any suggestions to fix that?

Body:
Here is one of the approach which answered by my friend Kavish:

df = pd.DataFrame({'col1': ['Acer','Acer','Acer','Abies','Abies'], 'col2' : ['Maple','Sugar Maple','Purple Maple','Jack Pine','Spruce']})
df

col1    col2
0   Acer    Maple
1   Acer    Sugar Maple
2   Acer    Purple Maple
3   Abies   Jack Pine
4   Abies   Spruce

line = ""
classes = df['col1'].unique()
for c in classes:
    line = line + c + "|"
    for index, row in df.iterrows():
        if(row['col1'] == c):
            line = line + row['col2'] + "|"
    line = line[:-1]
    line = line + '\n'

print(line)

Acer|Maple|Sugar Maple|Purple Maple
Abies|Jack Pine|Spruce

Credit to https://stackoverflow.com/users/12910033/kavish


问:
How to remove all extra spaces while keeping the lines
I need to remove white-spaces while keeping the lines

Before:

```<code>I brought           a            Banana
I sold                a Banana
I           brought a Apple
</code>```

After: NO WHITE SPACES or big space at the begining of the line

```<code>I brought a Banana
I sold a Banana
I brought a Apple
</code>```

All of the tutorials removes the white space but it didn't keep me the lines so it became all the words in one line:

I need to do this because after I use the .replace method in JavaScript, I get a bunch of white spaces but need to keep the lines so I can reorder the words.

答:
Simply split the data by the space, filter them out and then add a single space.</p>

```<code>var str = `I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;

str.split(' ').filter(String).join(' ');
</code>```

Body:
I need to remove white-spaces while keeping the lines

Before:

I brought           a            Banana
I sold                a Banana
I           brought a Apple

After: NO WHITE SPACES or big space at the begining of the line

I brought a Banana
I sold a Banana
I brought a Apple

All of the tutorials removes the white space but it didn't keep me the lines so it became all the words in one line:

I need to do this because after I use the .replace method in JavaScript, I get a bunch of white spaces but need to keep the lines so I can reorder the words.

Body:
Simply split the data by the space, filter them out and then add a single space.

var str = `I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;

str.split(' ').filter(String).join(' ');


问:
Should I process a JSON in the frontend or Backend, which is faster?
I am getting a response from an API as a json response.
I am coding in python for backend.

The frontend team needs information from the raw json response for populating a UI so we have to order the json and make it more easier for them to fetch information.

Now I can order the json in a specific format and push to the frontend team or I can pass the raw json response*to the frontend team and let them handle ordering the json and further use for their UI.

Remember my json file size is 15MB.

Which is faster and a better design principle?

Process in the backend then push to frontend or process in the frontend?

答:
As others have noted, there are quite a few good reasons to prefer processing on the back end:

if you can remove all unnecessary data from the JSON being sent to the front-end, it will reduce load on the end-user device both in terms of transfer but also in parsing time

it may be possible to cache the remote API call, so you don't need to make as many calls out to the remote APIs (which will usually be very slow compared to cache retrieval). You can also potentially cache the after-processing data, so you can just serve that up repeatedly

You can detect errors that happen in processing the JSON, whereas that is less visible if it is happening on the client device

One other big advantage to processing the API response on the back-end is that you can choose the structure you send to the front end. That way, if the API you are consuming changes over time (or you change which service you're using to retrieve data) you can handle that change on the back end without it ever affecting the front-end code.


问:
Type of triangle in MySQL
Problem statement:

Write a query identifying the type of each record in the TRIANGLES
table using its three side lengths. Output one of the following
statements for each record in the table:

Not A Triangle: The given values of A, B, and C don't form a triangle.

Equilateral: It's a triangle with  sides of equal length.

Isosceles: It's a triangle with  sides of equal length.

Scalene: It's a triangle with  sides of differing lengths. Input Format

The TRIANGLES table is described as follows:

Each row in the table denotes the lengths of each of a triangle's
three sides.

```<code>Sample Input
------------
A  B  C
20 20 23
20 20 20
20 21 22
13 14 30

Sample Output
-------------
Isosceles
Equilateral
Scalene
Not A Triangle
</code>```

Attempt that did not work:

```<code>select
    case
        when A+B < C or A+C < B or B+C < A then "Not A Triangle"
        when A=B and B=C then "Equilateral"
        when A=B or A=C or B=C then "Isosceles"
        when A<>B and B<>C then "Scalene"

    end as triangles_type
    from TRIANGLES;
</code>```

答:
The below code will check all the possible cases of a triangle. this code will work 100%</p>
```<code>select case
    when A+B<=C OR A+C<=B OR C+B<=A THEN "Not A Triangle"
    when (A<>B AND A+B>C) AND (B<>C AND B+C>A) AND (A<>C AND A+C>B) THEN
        "Scalene"
    when (A=B AND B<>C AND A+B>C) OR (B=C AND B<>A AND B+C>A) OR (A=C AND C<>B
          AND A+C>B) THEN "Isosceles"
    when A=B AND B=C THEN "Equilateral"
end as triangle
from TRIANGLES;
</code>```

Title: Type of triangle in MySQL

Body:
Problem statement:

Write a query identifying the type of each record in the TRIANGLES
table using its three side lengths. Output one of the following
statements for each record in the table:

Not A Triangle: The given values of A, B, and C don't form a triangle.

Equilateral: It's a triangle with  sides of equal length.

Isosceles: It's a triangle with  sides of equal length.

Scalene: It's a triangle with  sides of differing lengths. Input Format

The TRIANGLES table is described as follows:

Each row in the table denotes the lengths of each of a triangle's
three sides.

Sample Input
------------
A  B  C
20 20 23
20 20 20
20 21 22
13 14 30

Sample Output
-------------
Isosceles
Equilateral
Scalene
Not A Triangle

Attempt that did not work:

select
    case
        when A+B < C or A+C < B or B+C < A then "Not A Triangle"
        when A=B and B=C then "Equilateral"
        when A=B or A=C or B=C then "Isosceles"
        when A<>B and B<>C then "Scalene"

    end as triangles_type
    from TRIANGLES;

Body:
The below code will check all the possible cases of a triangle. this code will work 100%

select case
    when A+B<=C OR A+C<=B OR C+B<=A THEN "Not A Triangle"
    when (A<>B AND A+B>C) AND (B<>C AND B+C>A) AND (A<>C AND A+C>B) THEN
        "Scalene"
    when (A=B AND B<>C AND A+B>C) OR (B=C AND B<>A AND B+C>A) OR (A=C AND C<>B
          AND A+C>B) THEN "Isosceles"
    when A=B AND B=C THEN "Equilateral"
end as triangle
from TRIANGLES;


问:
How to Hide MPCommandCenter manually?
I am currently working on one Podcast app, in which we are using MPCommandCenter to enhance user experience to initialise MPCommandCenter I am using following code

```<code>let remoteCommands = MPRemoteCommandCenter.shared()

remoteCommands.playCommand.addTarget { event in
    // Perform play action
    return .success
}

remoteCommands.pauseCommand.addTarget { event in
    // Perform pause action
    return .success
}
</code>```

After using this code MPCommandCenter properly display remote controls. But we have functionality that allow users to Close currently playing podcast. And I am not able to figure out the way to unregister commandcenter manually. Can anyone help me to figure this one out.

答:
```<code>remoteCommands.playCommand.removeTarget(self)
remoteCommands.pauseCommand.removeTarget(self)
MPNowPlayingInfoCenter.default().nowPlayingInfo = nil

try? AVAudioSession.sharedInstance().setActive(false)
</code>```

Title: How to Hide MPCommandCenter manually?

Body:
I am currently working on one Podcast app, in which we are using MPCommandCenter to enhance user experience to initialise MPCommandCenter I am using following code

let remoteCommands = MPRemoteCommandCenter.shared()

remoteCommands.playCommand.addTarget { event in
    // Perform play action
    return .success
}

remoteCommands.pauseCommand.addTarget { event in
    // Perform pause action
    return .success
}

After using this code MPCommandCenter properly display remote controls. But we have functionality that allow users to Close currently playing podcast. And I am not able to figure out the way to unregister commandcenter manually. Can anyone help me to figure this one out.


问:
How would you programmatically test a file for viruses?
I want to programmatically test a file for viruses.

I'm aware of this thread, which didn't get a satisfactory answer in my opinion, but I'm not looking for an API here. Any kind of workaround to make it possible to test a file would be fine.

Of course, an API would probably be the best solution (I'm using .net on a Windows platform), but maybe it's possible to drop the file in the folder, and to then check whether I can still open it or if it's been quarantined by the antivirus software.

Has someone run into the same sort of situation?

答:
Maybe you could use this web service, assuming the file is less than 1MB:

http://www.kaspersky.com/scanforvirus

If you discover a suspicious file on
  your machine, or suspect that a
  program you downloaded from the
  Internet might be malicious, you can
  check the files here.

Indicate the file to be checked; it
  will automatically be uploaded from
  your computer to a dedicated server,
  where it will be scanned using
  Kaspersky Anti-Virus. Multiple
  independent tests and publications
  acknowledge the solution to have
  exceptional detection rates. Updates
  every three hours ensure that even the
  very newest viruses can be detected.

Only one file of up to 1 MB can be
  checked at any one time. If the file
  is too large, a window with an error
  message will be displayed. Type the
  name of the file in the window at the
  top of this page, or find the file
  using 'Browse'. Then click on
  'Submit'.

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: amdfan


问:
Identifying a dateformat and change it into another
I am working with the following piece of data which has a different format of dates and which creates confusion later in the process. The data is like:

S. No        DateTime               Area
1         03/05/2019 6:33            A
2         06/03/2019 07:23:45 AM     B```
</div>
</div>
</p>

<p>The first row is the format %m/%d/%Y h: mm and the second row is the format of %d/%m/%Y hh:mm: ss AM/PM. The first date value can be confusing though, is it 5th march or 3rd May. So to make everything of the same format, I want that my code detects the date format and changes in the desired format.</p>

<p>I have tried doing this:</p>

```
df['Detection Date'] = pd.to_datetime(df['Detection Date & Time'], errors = 'coerce').dt.datetime
col = df['Detection Date'].apply(str)

for i in df.index:
    if datetime.datetime.strptime(col, '%m/%d/%Y h:mm'):
       ColDate = datetime.datetime.strftime(col, '%d/%m/%Y hh:mm:ss AM/PM')
```

<p>But i am getting an error saying:</p>

<pre class="lang-py prettyprint-override"><code>TypeError: strptime() argument 1 must be str, not Series

</code>```

How it should be conducted.

Thanks

答:
If it is ok to install a dependency then you can use dateparser link

```<code>import pandas as pd
import dateparser

df = pd.DataFrame({'Detection Date & Time': ['03/05/2019 6:33', '06/03/2019 07:23:45 AM']})
df['Date & time'] =  df['Detection Date & Time'].apply(dateparser.parse)
</code>```

Body:
I am working with the following piece of data which has a different format of dates and which creates confusion later in the process. The data is like:

S. No        DateTime               Area
1         03/05/2019 6:33            A
2         06/03/2019 07:23:45 AM     B

The first row is the format %m/%d/%Y h: mm and the second row is the format of %d/%m/%Y hh:mm: ss AM/PM. The first date value can be confusing though, is it 5th march or 3rd May. So to make everything of the same format, I want that my code detects the date format and changes in the desired format.

I have tried doing this:

df['Detection Date'] = pd.to_datetime(df['Detection Date & Time'], errors = 'coerce').dt.datetime
col = df['Detection Date'].apply(str)

for i in df.index:
    if datetime.datetime.strptime(col, '%m/%d/%Y h:mm'):
       ColDate = datetime.datetime.strftime(col, '%d/%m/%Y hh:mm:ss AM/PM')

But i am getting an error saying:

TypeError: strptime() argument 1 must be str, not Series

How it should be conducted.

Thanks

Body:
If it is ok to install a dependency then you can use dateparser link

import pandas as pd
import dateparser

df = pd.DataFrame({'Detection Date & Time': ['03/05/2019 6:33', '06/03/2019 07:23:45 AM']})
df['Date & time'] =  df['Detection Date & Time'].apply(dateparser.parse)


问:
typescript custom component function param throwing warning
I have this piece of code

```<code><GoogleLogin
  onSuccess={responseGoogle => {
    const { email, name } = responseGoogle.profileObj; // error: Property 'profileObj' does not exist on type 'GoogleLoginResponse | GoogleLoginResponseOffline'.
  }}
/>
</code>```

The library is here https://www.npmjs.com/package/react-google-login

What should I do? I tried (responseGoogle:any) it doesn't work.

答:
Try this

```<code>  <GoogleLogin
    onSuccess={(responseGoogle: GoogleLoginResponse ) => {
      const { email, name } = responseGoogle.profileObj

    }}
  />
</code>```

Or you can also use the as keyword to let the typescript know that it is of type GoogleLoginResponse and not misinterpret it as GoogleLoginResponseOffline.

Body:
I have this piece of code

<GoogleLogin
  onSuccess={responseGoogle => {
    const { email, name } = responseGoogle.profileObj; // error: Property 'profileObj' does not exist on type 'GoogleLoginResponse | GoogleLoginResponseOffline'.
  }}
/>

The library is here https://www.npmjs.com/package/react-google-login

What should I do? I tried (responseGoogle:any) it doesn't work.

Body:
Try this

  <GoogleLogin
    onSuccess={(responseGoogle: GoogleLoginResponse ) => {
      const { email, name } = responseGoogle.profileObj

    }}
  />

Or you can also use the as keyword to let the typescript know that it is of type GoogleLoginResponse and not misinterpret it as GoogleLoginResponseOffline.


问:
Waited 30 seconds for com.google.common.util.concurrent.SettableFuture@1e023601[status=PENDING]
I have been encountering an error I that I have never seen before and it started showing up when my project couldnt find the bilder .jar file and redownload it and and it show the error below even in a new project after adding any kind of dependency and I'm using Android studio 3.2.0 Please help

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeDebugResources'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:103)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:256)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:249)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:238)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:663)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:597)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.internal.UncheckedException: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0: Daemon startup failed
This should not happen under normal circumstances, please file an issue if it does.
    at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:63)
    at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:40)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:76)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:124)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:113)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:95)
    ... 33 more
Caused by: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0: Daemon startup failed
This should not happen under normal circumstances, please file an issue if it does.
    at java.util.concurrent.ForkJoinTask.get(ForkJoinTask.java:1006)
    at com.android.ide.common.workers.ExecutorServiceAdapter.close(ExecutorServiceAdapter.kt:56)
    at com.android.build.gradle.internal.aapt.WorkerExecutorResourceCompilationService.close(WorkerExecutorResourceCompilationService.kt:67)
    at com.android.build.gradle.tasks.MergeResources.doFullTaskAction(MergeResources.java:324)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:106)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    ... 43 more
Caused by: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0: Daemon startup failed
This should not happen under normal circumstances, please file an issue if it does.
    at com.android.builder.internal.aapt.v2.Aapt2Daemon.handleError(Aapt2Daemon.kt:148)
    at com.android.builder.internal.aapt.v2.Aapt2Daemon.checkStarted(Aapt2Daemon.kt:57)
    at com.android.builder.internal.aapt.v2.Aapt2Daemon.compile(Aapt2Daemon.kt:79)
    at com.android.builder.internal.aapt.v2.Aapt2DaemonManager$LeasedAaptDaemon.compile(Aapt2DaemonManager.kt:170)
    at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable$run$1.invoke(Aapt2CompileWithBlameRunnable.kt:37)
    at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable$run$1.invoke(Aapt2CompileWithBlameRunnable.kt:28)
    at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.useAaptDaemon(Aapt2DaemonManagerService.kt:71)
    at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.useAaptDaemon$default(Aapt2DaemonManagerService.kt:69)
    at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable.run(Aapt2CompileWithBlameRunnable.kt:34)
    at com.android.ide.common.workers.ExecutorServiceAdapter$submit$submission$1.run(ExecutorServiceAdapter.kt:39)
    at java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1386)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.android.builder.internal.aapt.v2.Aapt2InternalException: Failed to start AAPT2 process AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0. Not ready within 30 seconds.
    at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.stopQuietly(Aapt2DaemonImpl.kt:122)
    at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.startProcess(Aapt2DaemonImpl.kt:102)
    at com.android.builder.internal.aapt.v2.Aapt2Daemon.checkStarted(Aapt2Daemon.kt:53)
    ... 13 more
    Suppressed: java.util.concurrent.TimeoutException: AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0: Failed to shut down within 30 seconds. Forcing shutdown
        at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.stopProcess(Aapt2DaemonImpl.kt:209)
        at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.stopQuietly(Aapt2DaemonImpl.kt:124)
        ... 15 more
Caused by: java.util.concurrent.TimeoutException: Waited 30 seconds for com.google.common.util.concurrent.SettableFuture@1e023601[status=PENDING]
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:442)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:90)
    at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.startProcess(Aapt2DaemonImpl.kt:100)
    ... 14 more
</code>```

This is the log the error it shows is just like the title

答:
Had a same problem, it's get resolved by
Bulid->Clean Project.
It's works for me.

Body:
I have been encountering an error I that I have never seen before and it started showing up when my project couldnt find the bilder .jar file and redownload it and and it show the error below even in a new project after adding any kind of dependency and I'm using Android studio 3.2.0 Please help

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:mergeDebugResources'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:103)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
    at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:91)
    at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:59)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:256)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:249)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:238)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:663)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:597)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.gradle.internal.UncheckedException: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0: Daemon startup failed
This should not happen under normal circumstances, please file an issue if it does.
    at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:63)
    at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:40)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:76)
    at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:124)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:113)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:95)
    ... 33 more
Caused by: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0: Daemon startup failed
This should not happen under normal circumstances, please file an issue if it does.
    at java.util.concurrent.ForkJoinTask.get(ForkJoinTask.java:1006)
    at com.android.ide.common.workers.ExecutorServiceAdapter.close(ExecutorServiceAdapter.kt:56)
    at com.android.build.gradle.internal.aapt.WorkerExecutorResourceCompilationService.close(WorkerExecutorResourceCompilationService.kt:67)
    at com.android.build.gradle.tasks.MergeResources.doFullTaskAction(MergeResources.java:324)
    at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:106)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    ... 43 more
Caused by: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0: Daemon startup failed
This should not happen under normal circumstances, please file an issue if it does.
    at com.android.builder.internal.aapt.v2.Aapt2Daemon.handleError(Aapt2Daemon.kt:148)
    at com.android.builder.internal.aapt.v2.Aapt2Daemon.checkStarted(Aapt2Daemon.kt:57)
    at com.android.builder.internal.aapt.v2.Aapt2Daemon.compile(Aapt2Daemon.kt:79)
    at com.android.builder.internal.aapt.v2.Aapt2DaemonManager$LeasedAaptDaemon.compile(Aapt2DaemonManager.kt:170)
    at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable$run$1.invoke(Aapt2CompileWithBlameRunnable.kt:37)
    at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable$run$1.invoke(Aapt2CompileWithBlameRunnable.kt:28)
    at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.useAaptDaemon(Aapt2DaemonManagerService.kt:71)
    at com.android.build.gradle.internal.res.namespaced.Aapt2DaemonManagerService.useAaptDaemon$default(Aapt2DaemonManagerService.kt:69)
    at com.android.build.gradle.internal.res.Aapt2CompileWithBlameRunnable.run(Aapt2CompileWithBlameRunnable.kt:34)
    at com.android.ide.common.workers.ExecutorServiceAdapter$submit$submission$1.run(ExecutorServiceAdapter.kt:39)
    at java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1386)
    at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
    at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
    at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
Caused by: com.android.builder.internal.aapt.v2.Aapt2InternalException: Failed to start AAPT2 process AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0. Not ready within 30 seconds.
    at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.stopQuietly(Aapt2DaemonImpl.kt:122)
    at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.startProcess(Aapt2DaemonImpl.kt:102)
    at com.android.builder.internal.aapt.v2.Aapt2Daemon.checkStarted(Aapt2Daemon.kt:53)
    ... 13 more
    Suppressed: java.util.concurrent.TimeoutException: AAPT2 aapt2-3.2.0-beta05-4818971-windows Daemon #0: Failed to shut down within 30 seconds. Forcing shutdown
        at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.stopProcess(Aapt2DaemonImpl.kt:209)
        at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.stopQuietly(Aapt2DaemonImpl.kt:124)
        ... 15 more
Caused by: java.util.concurrent.TimeoutException: Waited 30 seconds for com.google.common.util.concurrent.SettableFuture@1e023601[status=PENDING]
    at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:442)
    at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:90)
    at com.android.builder.internal.aapt.v2.Aapt2DaemonImpl.startProcess(Aapt2DaemonImpl.kt:100)
    ... 14 more

This is the log the error it shows is just like the title


问:
Using authenticate function for WHERE in Rails MongoDB throws an Error
I created a way to generate a password using secure password with 'has_secure_password'. I was able to generate a password_digest:

```<code>//this is the data in my mongo db

/* 1 */
{
    "_id" : ObjectId("5e4b43d55c260c07b48cbf38"),
    "username" : "admin",
    "password_digest" : "$2a$12$93GElGpXK2AcfRvhNsH23O2mPlTiV.sHLrtuesFO5HSllxDqEE796"
}

/* 2 */
{
    "_id" : ObjectId("5e4b46c95c260c07b48cbf3c"),
    "username" : "jenuel",
    "password_digest" : "$2a$12$6LPYNpAzCAT/k8HHFVJT7..E0GO2iuBJolY0TPHbklz0J58/OLkRm"
}
</code>```

this is my model in rails

```<code>class User
  include Mongoid::Document
  include ActiveModel::SecurePassword
  include ActiveModel::Validations

  field :username, type: String
  field :password_digest, type: String
  has_secure_password
  validates_confirmation_of :password
end
</code>```

I was able to create this users above using this function, inside my controller:

```<code>def create
    if check_username(params[:username]) == false
      @user = User.new(user_params)

      if @user.save
        render json: @user, status: :created, location: @user
      else
        render json: @user.errors, status: :unprocessable_entity
      end
    else
      render json: { error: "Username Already Exist" }, status: :unprocessable_entity
    end
  end
</code>```

And this is my login function:

```<code> def login
    user = User.where(username: params[:username])
    if user.exists? && user.authenticate(params[:password])
        render json: { message: "Logged In!" }, status: :ok
    else
      render json: { error: "unauthorized" }, status: :unauthorized
    end
  end
</code>```

My problem in the Login Function, when I use authenticate their is an error:

Please help. Is their other way to do this, to authenticate the password using Rails for MongoDB/mongoloid. Thank you So much :)

答:
As per the snippet shared in the post it seems like you are getting ActiveRecord::Relation as a result instead of active record object.
Refer to the line below

```<code>user = User.where(username: params[:username])
</code>```

change this to

```<code>user = User.where(username: params[:username]).last
</code>```

Also now changing to above mentioned code the following will not work

```<code>user.exists?
</code>```

Also change the above one to the one mentioned below

```<code>user.present?
</code>```

Now, you should be able to get it working.

Body:
I created a way to generate a password using secure password with 'has_secure_password'. I was able to generate a password_digest:

//this is the data in my mongo db

/* 1 */
{
    "_id" : ObjectId("5e4b43d55c260c07b48cbf38"),
    "username" : "admin",
    "password_digest" : "$2a$12$93GElGpXK2AcfRvhNsH23O2mPlTiV.sHLrtuesFO5HSllxDqEE796"
}

/* 2 */
{
    "_id" : ObjectId("5e4b46c95c260c07b48cbf3c"),
    "username" : "jenuel",
    "password_digest" : "$2a$12$6LPYNpAzCAT/k8HHFVJT7..E0GO2iuBJolY0TPHbklz0J58/OLkRm"
}

this is my model in rails

class User
  include Mongoid::Document
  include ActiveModel::SecurePassword
  include ActiveModel::Validations

  field :username, type: String
  field :password_digest, type: String
  has_secure_password
  validates_confirmation_of :password
end

I was able to create this users above using this function, inside my controller:

def create
    if check_username(params[:username]) == false
      @user = User.new(user_params)

      if @user.save
        render json: @user, status: :created, location: @user
      else
        render json: @user.errors, status: :unprocessable_entity
      end
    else
      render json: { error: "Username Already Exist" }, status: :unprocessable_entity
    end
  end

And this is my login function:

 def login
    user = User.where(username: params[:username])
    if user.exists? && user.authenticate(params[:password])
        render json: { message: "Logged In!" }, status: :ok
    else
      render json: { error: "unauthorized" }, status: :unauthorized
    end
  end

My problem in the Login Function, when I use authenticate their is an error:

Please help. Is their other way to do this, to authenticate the password using Rails for MongoDB/mongoloid. Thank you So much :)

Body:
As per the snippet shared in the post it seems like you are getting ActiveRecord::Relation as a result instead of active record object.
Refer to the line below

user = User.where(username: params[:username])

change this to

user = User.where(username: params[:username]).last

Also now changing to above mentioned code the following will not work

user.exists?

Also change the above one to the one mentioned below

user.present?

Now, you should be able to get it working.


问:
How do I know the Methods in AndroidJavaObject class in C# Unity
I've use this code

```<code>using (var activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"))
        {
            using (var wifiManager = activity.Call<AndroidJavaObject>("getSystemService", "wifi"))
            {
                tempSSID = wifiManager.Call<AndroidJavaObject>("getConnectionInfo").Call<string>("getSSID");
            }
        }
</code>```

So how do I know the Methods like "getConnectionInfo","getSSID","getSystemService" because I want to scan SSID nearby and connect to that.

答:
By looking into the Android API!

In the first line

```<code>var activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"))
</code>```

you get the current Activity

Then in the second line you use getSystemService

```<code>var wifiManager = activity.Call<AndroidJavaObject>("getSystemService", "wifi")
</code>```

to get a reference to the WifiManager service.

Then in

```<code>wifiManager.Call<AndroidJavaObject>("getConnectionInfo")
</code>```

you are calling getConnectionInfo on it which returns a WifiInfo on which you finally call getSSID

Body:
I've use this code

using (var activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"))
        {
            using (var wifiManager = activity.Call<AndroidJavaObject>("getSystemService", "wifi"))
            {
                tempSSID = wifiManager.Call<AndroidJavaObject>("getConnectionInfo").Call<string>("getSSID");
            }
        }

So how do I know the Methods like "getConnectionInfo","getSSID","getSystemService" because I want to scan SSID nearby and connect to that.

Body:
By looking into the Android API!

In the first line

var activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity"))

you get the current Activity

Then in the second line you use getSystemService

var wifiManager = activity.Call<AndroidJavaObject>("getSystemService", "wifi")

to get a reference to the WifiManager service.

Then in

wifiManager.Call<AndroidJavaObject>("getConnectionInfo")

you are calling getConnectionInfo on it which returns a WifiInfo on which you finally call getSSID


问:
How to use single component as page and MatDialog in angular
How to use the single component as page and open as component MatDialog
If call from MatDialog need two way data binding
If its open as page no need to bind data

Call from component
    ```var modal = this._dialog.open(SingleComponent, {
      data: { create: true }
    });'''</p>

<p>SingleComponent</p>

``````@Component({
  selector: 'single',
  templateUrl: './single.html',
  styleUrls: ['./single.scss'],
  providers: [{
     provide: MatDialogRef,
     useValue: {close: (dialogResult: any) => { }}
  },{ provide: MAT_DIALOG_DATA, useValue: {} }]
</code>```

})
    constructor(
        public dialogRef: MatDialogRef,
        @Optional() @Inject(MAT_DIALOG_DATA) public data: any) ```

This open in both as page and modal box, but cant bind data between component and single component, and cant close from code
    this.dialogRef.close(); not working

答:
declare  dialogRef: MatDialogRef<SingleComponent>;

```<code> this.dialogRef = this.dialog.open(SingleComponent, { data: { create: true } });

 this.dialogRef.afterClosed().subscribe(result => {
      this.dialogRef = null;
    });
</code>```

in single.component.ts add this

import {  MAT_DIALOG_DATA } from '@angular/material';

```<code>@Inject(MAT_DIALOG_DATA) public data: any
</code>```

you can use value in single component in
 data.

Body:
How to use the single component as page and open as component MatDialog
If call from MatDialog need two way data binding
If its open as page no need to bind data

Call from component
    ```var modal = this._dialog.open(SingleComponent, {
      data: { create: true }
    });'''</p>

<p>SingleComponent</p>

<pre><code>```@Component({
  selector: 'single',
  templateUrl: './single.html',
  styleUrls: ['./single.scss'],
  providers: [{
     provide: MatDialogRef,
     useValue: {close: (dialogResult: any) => { }}
  },{ provide: MAT_DIALOG_DATA, useValue: {} }]

})
    constructor(
        public dialogRef: MatDialogRef,
        @Optional() @Inject(MAT_DIALOG_DATA) public data: any) ```

This open in both as page and modal box, but cant bind data between component and single component, and cant close from code
    this.dialogRef.close(); not working

Body:
declare  dialogRef: MatDialogRef<SingleComponent>;

 this.dialogRef = this.dialog.open(SingleComponent, { data: { create: true } });

 this.dialogRef.afterClosed().subscribe(result => {
      this.dialogRef = null;
    });

in single.component.ts add this

import {  MAT_DIALOG_DATA } from '@angular/material';

@Inject(MAT_DIALOG_DATA) public data: any

you can use value in single component in
 data.


问:
jQuery .click() and .change() conflict?
I have problem with .click() and .change() functions. I don't know why, but I put them into the html code separately they works, but when I put them together like below they stop working. What is the problem?
The .change() function populates the fields of form in specific table row. The .click() functions add a row to and remove a row from the table within the form.</p>

```<code>$(document).ready(function() {
    $('select[name="produkt[]"]').change(function() {
        var id = $('select[name="produkt[]"] option:selected').val();
        var par = $(this).parent().parent().attr('id');
        $.getJSON(
            '<?php echo $head['site_link'];?>index.php/faktura/pobierzProdukt/'+id,
            function(data){
                alert(par);
                $('#'+par+' input[name="pkwiu[]"]').val(data.product_pkwiu);
                $('#'+par+' input[name="netto[]"]').val(data.product_netto);
                $('#'+par+' input[name="vat[]"]').val(data.product_vat);
                $('#'+par+' input[name="brutto[]"]').val(data.product_brutto);
                $('#'+par+' input[name="jedn[]"]').val(data.product_jedn);
            },
            'json'
        );
    });

    $('#dodajWiersz').click(function() {
        var liczba = $('#produkty tr').length;
        var f1  = '<?php echo form_dropdown('produkt[]',$lista,'');?></td>';
        var f2  = '<?php echo form_input(array('name'=>'pkwiu[]','class'=>'short','readonly'=>'readonly'));?>';
        var f3  = '<?php echo form_input(array('name'=>'netto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f4  = '<?php echo form_input(array('name'=>'vat[]','class'=>'mini','readonly'=>'readonly'));?>';
        var f5  = '<?php echo form_input(array('name'=>'brutto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f6  = '<?php echo form_input(array('name'=>'jedn[]','class'=>'mini','readonly'=>'readonly'));?>';
        var f7  = '<?php echo form_input(array('name'=>'ilosc[]','class'=>'short'));?>';
        var f8  = '<?php echo form_input(array('name'=>'knetto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f9  = '<?php echo form_input(array('name'=>'kvat[]','class'=>'short','readonly'=>'readonly'));?>';
        var f10 = '<?php echo form_input(array('name'=>'kbrutto[]','class'=>'short','readonly'=>'readonly'));?>';

        var row = '<tr id="wiersz-'+liczba+'"><td>'+liczba+'</td><td>'+f1+'</td><td>'+f2+'</td><td>'+f3+'</td><td>'+f4+'</td><td>'+f5+'</td><td>'+f6+'</td><td>'+f7+'</td><td>'+f8+'</td><td>'+f9+'</td><td>'+f10+'</td>';
        $('#produkty').find('tbody').append(row);
    });

    $('#usunWiersz').click(function() {
       $('#produkty').find('tbody tr:last').remove();
    });
});
</code>```

答:
Look at this:

```<code><?php echo $head['site_link'];?>
</code>```

I don't know what exactly you mean by "put them together". I suppose you mean, packing the functions into one .js-file. JS-Files however won't interpret PHP. So may be that is your mistake?

Title: jQuery .click() and .change() conflict?

Body:
I have problem with .click() and .change() functions. I don't know why, but I put them into the html code separately they works, but when I put them together like below they stop working. What is the problem?
The .change() function populates the fields of form in specific table row. The .click() functions add a row to and remove a row from the table within the form.

$(document).ready(function() {
    $('select[name="produkt[]"]').change(function() {
        var id = $('select[name="produkt[]"] option:selected').val();
        var par = $(this).parent().parent().attr('id');
        $.getJSON(
            '<?php echo $head['site_link'];?>index.php/faktura/pobierzProdukt/'+id,
            function(data){
                alert(par);
                $('#'+par+' input[name="pkwiu[]"]').val(data.product_pkwiu);
                $('#'+par+' input[name="netto[]"]').val(data.product_netto);
                $('#'+par+' input[name="vat[]"]').val(data.product_vat);
                $('#'+par+' input[name="brutto[]"]').val(data.product_brutto);
                $('#'+par+' input[name="jedn[]"]').val(data.product_jedn);
            },
            'json'
        );
    });

    $('#dodajWiersz').click(function() {
        var liczba = $('#produkty tr').length;
        var f1  = '<?php echo form_dropdown('produkt[]',$lista,'');?>	';
        var f2  = '<?php echo form_input(array('name'=>'pkwiu[]','class'=>'short','readonly'=>'readonly'));?>';
        var f3  = '<?php echo form_input(array('name'=>'netto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f4  = '<?php echo form_input(array('name'=>'vat[]','class'=>'mini','readonly'=>'readonly'));?>';
        var f5  = '<?php echo form_input(array('name'=>'brutto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f6  = '<?php echo form_input(array('name'=>'jedn[]','class'=>'mini','readonly'=>'readonly'));?>';
        var f7  = '<?php echo form_input(array('name'=>'ilosc[]','class'=>'short'));?>';
        var f8  = '<?php echo form_input(array('name'=>'knetto[]','class'=>'short','readonly'=>'readonly'));?>';
        var f9  = '<?php echo form_input(array('name'=>'kvat[]','class'=>'short','readonly'=>'readonly'));?>';
        var f10 = '<?php echo form_input(array('name'=>'kbrutto[]','class'=>'short','readonly'=>'readonly'));?>';

        var row = '
'+liczba+'	'+f1+'	'+f2+'	'+f3+'	'+f4+'	'+f5+'	'+f6+'	'+f7+'	'+f8+'	'+f9+'	'+f10+'	';
        $('#produkty').find('tbody').append(row);
    });

    $('#usunWiersz').click(function() {
       $('#produkty').find('tbody tr:last').remove();
    });
});

Body:
Look at this:

<?php echo $head['site_link'];?>

I don't know what exactly you mean by "put them together". I suppose you mean, packing the functions into one .js-file. JS-Files however won't interpret PHP. So may be that is your mistake?


问:
Three Javascript Accordions on one page Two working
Hi tried to have multiple accordion on one page. Like three or six.
But the second or fourth etc. is not working.
Have somebody an idea?

Link: https://www.w3schools.com/code/tryit.asp?filename=GBYOZDRRVKFA

Body:
Problem is you are duplicating the same script 3 times. Keep the last one only and remove other script blocks.

EDIT:
This javascript won't work with dynamically generated html.

I have updated code with jQuery. Follow <script> tag inside <head>

https://www.w3schools.com/code/tryit.asp?filename=GC1V1TGM6QHJ

Magic happens with just 4 lines of script

$(document).ready(function(){
//$(".accordion").click(function(){
  $(document).on("click", ".accordion" , function() {
    $(this).toggleClass("active");
    $(this).next(".panel").toggle();
  });
});

I suggest, once you are confident in JavaScript start learning jQuery alongside. It is very easy to learn and amazingly powerful. You can do a lot with less code.

Here is step by step jQuery tutorial with interactive examples.

And here is a Video tutorial


问:
Split function NoMethodErrorException as I am looping through each element using Gherkin (Ruby) but last element is invalid
I am getting "NoMethodErrorException"
" undefined method `split' for nil:NilClass (NoMethodError)
"

the issue seems to be because of the last element that I am using , but I am not finding a way to ignore the last element in the feature file

答:
If you want to reject the last element, then you may do something like this

```<code>a=[1,2,3,4,5,6]
a.pop
p a
</code>```

Output

```<code>[1, 2, 3, 4, 5]
</code>```

Once the last element is rejected then you can iterate the array and can perform your operation

```<code>a.each do |val|
  p val
end
</code>```

Body:
If you want to reject the last element, then you may do something like this

a=[1,2,3,4,5,6]
a.pop
p a

Output

[1, 2, 3, 4, 5]

Once the last element is rejected then you can iterate the array and can perform your operation

a.each do |val|
  p val
end


问:
Show all options selected by default in a dropdown list
I would like to know (by request of our client) if it is possible to modify the behavior of a drop-down list filter. The idea is to see all the options selected by default when the current value is All. Something like this:

答:
you can select all option as shown in the picture and by default it will select ALL values in the slicer.

Click on the Slicer you want to apply and go to  Visualizations menu --> Format Brush --> Seclection controls

You can do other method:

In Filters you can selet 'All'


问:
CSS Responsive image "shows up fully" on-screen no-stretch background with precise text placement

Testing

```

I'm trying to have an image fully show up based on the size of a screen, and to have text ("Testing" in the textbox class) show up in a precise designated area in the image, as shown above.

Trying to get the above to work with this codepen, but I am defeated to admit that after an hour of fiddling with css, I am nowhere close.

It is pretty frustrating that css doesn't seem to work as expected, where the image doesn't seem to want to nest to full height etc.

答:
Try this: </p>

```<code>background: url('path/to/img.jpg') no-repeat center center / cover;
</code>```

Body:
Testing

I'm trying to have an image fully show up based on the size of a screen, and to have text ("Testing" in the textbox class) show up in a precise designated area in the image, as shown above.

Trying to get the above to work with this codepen, but I am defeated to admit that after an hour of fiddling with css, I am nowhere close.

It is pretty frustrating that css doesn't seem to work as expected, where the image doesn't seem to want to nest to full height etc.

Body:
Try this:

background: url('path/to/img.jpg') no-repeat center center / cover;


问:
How do I create a List<T> from a SortedList<int, T>?
I'm working with .net 3.5, and I have this:

```<code>SortedList<int, BrainTickTransition>
</code>```

And I want one of these:

```<code>List<BrainTickTransition>
</code>```

Is there a quick way to do this without having to copy all of the values from the SortedList?

答:
This Works:

```<code>myList = new List<string>(mySortedList.Values);
</code>```

(Credit to the comment by @Jon).
The new List will never see subsequent changes to the sortedList. This is perfect for a scenario where SortedList was just for temp usage, or where the Sorted is for historic reference.

However, the answer by @CodesInChaos doesn't
 Does Not Work:

```<code>myList = mySortedList.Values.ToList();
</code>```

ToList() fails with with exception: IList<string> does not contain a definition for ToList

Body:
I'm working with .net 3.5, and I have this:

SortedList<int, BrainTickTransition>

And I want one of these:

List<BrainTickTransition>

Is there a quick way to do this without having to copy all of the values from the SortedList?

Body:
This Works:

myList = new List<string>(mySortedList.Values);

(Credit to the comment by @Jon).
The new List will never see subsequent changes to the sortedList. This is perfect for a scenario where SortedList was just for temp usage, or where the Sorted is for historic reference.

However, the answer by @CodesInChaos doesn't
 Does Not Work:

myList = mySortedList.Values.ToList();

ToList() fails with with exception: IList<string> does not contain a definition for ToList


问:
bash: /home/user/.bash_completion/alacritty: No such file or directory
whenever I open the terminal this line

```<code>bash: /home/user/.bash_completion/alacritty: No such file or directory
</code>```

is displayed. I tried to install alacritty terminal but it failed and there after I am seeing this line in the terminal. How to solve this problem?

答:
Looking at the install instructions here, you would have done:

```<code>echo "source ~/.bash_completion/alacritty" >> ~/.bashrc
</code>```

So, just edit ~/.bashrc and delete the line source ~/.bash_completion/alacritty.

Body:
whenever I open the terminal this line

bash: /home/user/.bash_completion/alacritty: No such file or directory

is displayed. I tried to install alacritty terminal but it failed and there after I am seeing this line in the terminal. How to solve this problem?

Body:
Looking at the install instructions here, you would have done:

echo "source ~/.bash_completion/alacritty" >> ~/.bashrc

So, just edit ~/.bashrc and delete the line source ~/.bash_completion/alacritty.


问:
Help with Undefined index and Undefined variable
Could somebody help me with this problem. I just trasferred my PHP/MYSQL program to another computer (both are running XAMPP and on localhost) and now I got a massive amount of Undefined index and Undefined variable ERRORS. Could somebody explain me why?

All the variables are checked with isset and all the values should be OK, but I can't get anything to work as it is supposed to and then there are the Undefined index and Undefined variable ERRORS.

Please Help!
Thanks

答: Probably your error_reporting in the PHP configuration file (php.ini) is set differently as on your old XAMPP configuration.</p>


问:
ListView items gone off screen

The problem is when I run the program the view cuts like what shown in the picture above
I don't know what the exact sort of problem, so if you need anything to show just ask
I am using kotlin by the way

EDIT 1:
result_row.xml this is the XML for the row that shows in the ListView

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/itemName"
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Name"
            android:textColor="#000000"
            android:textSize="16sp" />

        <View
            android:id="@+id/lineView2"
            android:layout_width="2dp"
            android:layout_height="40dp"
            android:background="#010101" />

        <TextView
            android:id="@+id/itemWeight"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Item Weight"
            android:textColor="#000000"
            android:textSize="16sp" />

        <View
            android:id="@+id/lineView1"
            android:layout_width="2dp"
            android:layout_height="40dp"
            android:background="#010101" />

        <TextView
            android:id="@+id/itemPrice"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Price"
            android:textColor="#000000"
            android:textSize="16sp" />

    </LinearLayout>

</FrameLayout>
</code>```

答:
in your layout xml file edit</p>

```<code>layout_width="0dp"
layoyt_height="0dp"
</code>```

Title: ListView items gone off screen

Body:
The problem is when I run the program the view cuts like what shown in the picture above
I don't know what the exact sort of problem, so if you need anything to show just ask
I am using kotlin by the way

EDIT 1:
result_row.xml this is the XML for the row that shows in the ListView

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/itemName"
            android:layout_width="200dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Name"
            android:textColor="#000000"
            android:textSize="16sp" />

        <View
            android:id="@+id/lineView2"
            android:layout_width="2dp"
            android:layout_height="40dp"
            android:background="#010101" />

        <TextView
            android:id="@+id/itemWeight"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Item Weight"
            android:textColor="#000000"
            android:textSize="16sp" />

        <View
            android:id="@+id/lineView1"
            android:layout_width="2dp"
            android:layout_height="40dp"
            android:background="#010101" />

        <TextView
            android:id="@+id/itemPrice"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Price"
            android:textColor="#000000"
            android:textSize="16sp" />

    </LinearLayout>

</FrameLayout>

Body:
in your layout xml file edit

layout_width="0dp"
layoyt_height="0dp"