问:
Error : " dictionary update sequence element #0 has length 1; 2 is required " in Unit test
I have two files : database_config.py used to  to check connection to database via DatabaseConfig.yml configuration file. I need to write some test cases for my config file includes several scenarios :

If the database is empty then the test case fails.

If the database is not Sqlite or Postgre, test case fails.

I have created a test file but while I try to implement it  I am getting error

ValueError: dictionary update sequence element #0 has length 1; 2 is required.

Could anyone please help me on this?

My DatabaseConfig.yml :

```<code>database:

dbopt:
   host: None
   port: 6313
   dbname: spam_eggs2

query:
   select * from manufacturing_product

</code>```

My database_config.py:

```<code>import yaml

class InvalidConfigError(Exception):
    pass

class DB():
    def __init__(self, dbconf):
        self._dbconf = dict(dbconf)
        # checking for database type
        dbtype = self.get_db_type()
        if dbtype != 'sqlite' and dbtype != 'postgres':
            raise InvalidConfigError(
                'E01001', 'Invalid database type, should be sqlite or postgres.')
        else:
            self.dbtype = dbtype

    def get_db_type(self):
        return self._dbconf['database']

with open('DatabaseConfig.yml') as f:
    data = yaml.full_load(f)

    for item, doc in data.items():
        print(item, ":", doc)

    database = DB(data)
</code>```

My test file test_db_type.py for database_config.py:

```<code>import yaml
import unittest
import database_config

class TestDBtype(unittest.TestCase):
    #setUpClass gets calls only once where as setUp gets called before every test
    @classmethod
    def setUpClass(cls):
        cls.init_db()

    @classmethod
    def init_db(cls):
        self.db_instance = database_config.DB('DatabaseConfig.yml')

    def test_missing_db(self):
        self.assertEqual(self.db_instance, None, "Connection returned None.")

    def test_db_type(self):
        with self.subTest():
            self.assertEqual(self.db_instance, 'postgres')
        with self.subTest():
            self.assertEqual(self.db_instance, 'sqlite')

if __name__ == '__main__':
    unittest.main()

</code>```

Error Traceback when I run test:

```<code>(base) D:\Python>python -u "d:\Python\TestDataSource\test_db_type.py"
database : postgres
dbopt : {'host': 'None', 'port': 6313, 'dbname': 'spam_eggs2'}
query : select * from manufacturing_product
E
======================================================================
ERROR: setUpClass (__main__.TestDBtype)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "d:\Python\TestDataSource\test_db_type.py", line 9, in setUpClass
    cls.init_db()
  File "d:\Python\TestDataSource\test_db_type.py", line 13, in init_db
    self.db_instance = database_config.DB('DatabaseConfig.yml')
  File "d:\Python\TestDataSource\database_config.py", line 8, in __init__
    self._dbconf = dict(dbconf)
ValueError: dictionary update sequence element #0 has length 1; 2 is required

----------------------------------------------------------------------
Ran 0 tests in 0.001s

FAILED (errors=1)

(base) D:\Python>C:/Users/duongnb/AppData/Local/Continuum/anaconda3/Scripts/activate

(base) D:\Python>conda activate base

(base) D:\Python>^A

</code>```

答:
Here:

```<code>self.db_instance = database_config.DB('DatabaseConfig.yml')
</code>```

you're passing a single string argument to DB constructor; this argument is passed here:

```<code>class DB():
    def __init__(self, dbconf):
        self._dbconf = dict(dbconf)
</code>```

but you cannot create a dict from a single argument - dict('DatabaseConfig.yml') raises error.

Body:
I have two files : database_config.py used to  to check connection to database via DatabaseConfig.yml configuration file. I need to write some test cases for my config file includes several scenarios :

If the database is empty then the test case fails.

If the database is not Sqlite or Postgre, test case fails.

I have created a test file but while I try to implement it  I am getting error

ValueError: dictionary update sequence element #0 has length 1; 2 is required.

Could anyone please help me on this?

My DatabaseConfig.yml :

database:

dbopt:
   host: None
   port: 6313
   dbname: spam_eggs2

query:
   select * from manufacturing_product

My database_config.py:

import yaml

class InvalidConfigError(Exception):
    pass

class DB():
    def __init__(self, dbconf):
        self._dbconf = dict(dbconf)
        # checking for database type
        dbtype = self.get_db_type()
        if dbtype != 'sqlite' and dbtype != 'postgres':
            raise InvalidConfigError(
                'E01001', 'Invalid database type, should be sqlite or postgres.')
        else:
            self.dbtype = dbtype

    def get_db_type(self):
        return self._dbconf['database']

with open('DatabaseConfig.yml') as f:
    data = yaml.full_load(f)

    for item, doc in data.items():
        print(item, ":", doc)

    database = DB(data)

My test file test_db_type.py for database_config.py:

import yaml
import unittest
import database_config

class TestDBtype(unittest.TestCase):
    #setUpClass gets calls only once where as setUp gets called before every test
    @classmethod
    def setUpClass(cls):
        cls.init_db()

    @classmethod
    def init_db(cls):
        self.db_instance = database_config.DB('DatabaseConfig.yml')

    def test_missing_db(self):
        self.assertEqual(self.db_instance, None, "Connection returned None.")

    def test_db_type(self):
        with self.subTest():
            self.assertEqual(self.db_instance, 'postgres')
        with self.subTest():
            self.assertEqual(self.db_instance, 'sqlite')

if __name__ == '__main__':
    unittest.main()

Error Traceback when I run test:

(base) D:\Python>python -u "d:\Python\TestDataSource\test_db_type.py"
database : postgres
dbopt : {'host': 'None', 'port': 6313, 'dbname': 'spam_eggs2'}
query : select * from manufacturing_product
E
======================================================================
ERROR: setUpClass (__main__.TestDBtype)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "d:\Python\TestDataSource\test_db_type.py", line 9, in setUpClass
    cls.init_db()
  File "d:\Python\TestDataSource\test_db_type.py", line 13, in init_db
    self.db_instance = database_config.DB('DatabaseConfig.yml')
  File "d:\Python\TestDataSource\database_config.py", line 8, in __init__
    self._dbconf = dict(dbconf)
ValueError: dictionary update sequence element #0 has length 1; 2 is required

----------------------------------------------------------------------
Ran 0 tests in 0.001s

FAILED (errors=1)

(base) D:\Python>C:/Users/duongnb/AppData/Local/Continuum/anaconda3/Scripts/activate

(base) D:\Python>conda activate base

(base) D:\Python>^A

Body:
Here:

self.db_instance = database_config.DB('DatabaseConfig.yml')

you're passing a single string argument to DB constructor; this argument is passed here:

class DB():
    def __init__(self, dbconf):
        self._dbconf = dict(dbconf)

but you cannot create a dict from a single argument - dict('DatabaseConfig.yml') raises error.


来源: stackexchange

问:
React Native: Module not found @react-native-community-cli
Project was working fine before I had to reinstall everything on my computer. I get the following error after I run npm install and then expo start

```<code>internal/modules/cjs/loader.js:296
      throw err;
      ^

Error: Cannot find module '/home/amber/Documents/GitKraken/school-notification-1/App/node_modules/@react-native-community/cli/build/index.js'. Please verify that the package.json has a valid "main" entry
    at tryPackage (internal/modules/cjs/loader.js:288:19)
    at Function.Module._findPath (internal/modules/cjs/loader.js:515:18)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:759:27)
    at Function.Module._load (internal/modules/cjs/loader.js:677:27)
    at Module.require (internal/modules/cjs/loader.js:830:19)
    at require (internal/modules/cjs/helpers.js:68:18)
    at Object.<anonymous> (/home/amber/Documents/GitKraken/school-notification-1/App/node_modules/react-native/local-cli/cli.js:12:11)
    at Module._compile (internal/modules/cjs/loader.js:936:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Module.load (internal/modules/cjs/loader.js:790:32) {
  code: 'MODULE_NOT_FOUND',
  path: '/home/amber/Documents/GitKraken/school-notification-1/App/node_modules/@react-native-community/cli/package.json',
  requestPath: '@react-native-community/cli'
}

Metro Bundler process exited with code 1
</code>```

This is my package.json

```<code>{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "test": "jest --watchAll"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/vector-icons": "^10.0.3",
    "@react-navigation/web": "^1.0.0-alpha.9",
    "axios": "^0.19.0",
    "expo": "^34.0.1",
    "expo-asset": "^6.0.0",
    "expo-constants": "^6.0.0",
    "expo-font": "~6.0.0",
    "expo-web-browser": "6.0.0",
    "navigationbar-react-native": "0.0.5",
    "qs": "^6.8.0",
    "react": "16.8.3",
    "react-dom": "^16.8.6",
    "react-native": "https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz",
    "react-native-action-button": "^2.8.5",
    "react-native-anchor-carousel": "^3.1.1",
    "react-native-app-intro-slider": "^3.0.0",
    "react-native-calendars": "^1.210.0",
    "react-native-circle-drawer": "^1.0.0",
    "react-native-drawer-menu": "^0.2.5",
    "react-native-elements": "^1.1.0",
    "react-native-gesture-handler": "^1.3.0",
    "react-native-global-props": "^1.1.5",
    "react-native-htmlview": "^0.15.0",
    "react-native-loading-spinner-overlay": "^1.0.1",
    "react-native-popup-dialog": "^0.18.3",
    "react-native-side-drawer": "^1.1.11",
    "react-native-side-menu": "^1.1.3",
    "react-native-sidebar": "^0.3.0",
    "react-native-web": "^0.11.4",
    "react-navigation": "^3.11.0"
  },
  "devDependencies": {
    "babel-preset-expo": "^6.0.0",
    "jest-expo": "^34.0.0"
  },
  "private": true
}
</code>```

答:
Install this package.</p>

```<code>npm i @react-native-community/cli
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Project was working fine before I had to reinstall everything on my computer. I get the following error after I run npm install and then expo start

internal/modules/cjs/loader.js:296
      throw err;
      ^

Error: Cannot find module '/home/amber/Documents/GitKraken/school-notification-1/App/node_modules/@react-native-community/cli/build/index.js'. Please verify that the package.json has a valid "main" entry
    at tryPackage (internal/modules/cjs/loader.js:288:19)
    at Function.Module._findPath (internal/modules/cjs/loader.js:515:18)
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:759:27)
    at Function.Module._load (internal/modules/cjs/loader.js:677:27)
    at Module.require (internal/modules/cjs/loader.js:830:19)
    at require (internal/modules/cjs/helpers.js:68:18)
    at Object.<anonymous> (/home/amber/Documents/GitKraken/school-notification-1/App/node_modules/react-native/local-cli/cli.js:12:11)
    at Module._compile (internal/modules/cjs/loader.js:936:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Module.load (internal/modules/cjs/loader.js:790:32) {
  code: 'MODULE_NOT_FOUND',
  path: '/home/amber/Documents/GitKraken/school-notification-1/App/node_modules/@react-native-community/cli/package.json',
  requestPath: '@react-native-community/cli'
}

Metro Bundler process exited with code 1

This is my package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "test": "jest --watchAll"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/vector-icons": "^10.0.3",
    "@react-navigation/web": "^1.0.0-alpha.9",
    "axios": "^0.19.0",
    "expo": "^34.0.1",
    "expo-asset": "^6.0.0",
    "expo-constants": "^6.0.0",
    "expo-font": "~6.0.0",
    "expo-web-browser": "6.0.0",
    "navigationbar-react-native": "0.0.5",
    "qs": "^6.8.0",
    "react": "16.8.3",
    "react-dom": "^16.8.6",
    "react-native": "https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz",
    "react-native-action-button": "^2.8.5",
    "react-native-anchor-carousel": "^3.1.1",
    "react-native-app-intro-slider": "^3.0.0",
    "react-native-calendars": "^1.210.0",
    "react-native-circle-drawer": "^1.0.0",
    "react-native-drawer-menu": "^0.2.5",
    "react-native-elements": "^1.1.0",
    "react-native-gesture-handler": "^1.3.0",
    "react-native-global-props": "^1.1.5",
    "react-native-htmlview": "^0.15.0",
    "react-native-loading-spinner-overlay": "^1.0.1",
    "react-native-popup-dialog": "^0.18.3",
    "react-native-side-drawer": "^1.1.11",
    "react-native-side-menu": "^1.1.3",
    "react-native-sidebar": "^0.3.0",
    "react-native-web": "^0.11.4",
    "react-navigation": "^3.11.0"
  },
  "devDependencies": {
    "babel-preset-expo": "^6.0.0",
    "jest-expo": "^34.0.0"
  },
  "private": true
}

Body:
Install this package.

npm i @react-native-community/cli


问:
Getting the Data as a CSV file directly instead of a List of object from spring-data-jpa
Is it possible to get the data from spring-data JPA in the form of CSV data instaed of ArrayList of pojos like

Below is the interface extending JpaRepository.

```<code>public interface FactAggRepository extends JpaRepository<FactAggRepository,Integer> {

@Query("select p from FactAggRepository as p where p.pId=:pId and p.periodStart=:periodStart")
public List<FactAggRepository> getAggregates(@Param("pId") Long pId,@Param("periodStart")LocalDateTime periodStart);

@Query("select p from UsageAgg as p where p.pId=:pId")
public List<UsageAgg> UsageAggregates(@Param("pId") Long pId);

}
</code>```

Autowiring the repository to use the same methods as follows.

```<code>fetchedRecord = AggRepo.getAggregates(pId, periodStart);
</code>```

Now the above the code returnd the List. Is it possible to get the CSV file with the data in the List without any conversion.please let me know. Thanks in advance.

答:
Spring Data is here to handle communication with data sources layers. Unfortunately, CSV is not a data store handled natively.

You have to use a third-party dependency such as OpenCSV to transform those POJOs to CSV.

Body:
Is it possible to get the data from spring-data JPA in the form of CSV data instaed of ArrayList of pojos like

Below is the interface extending JpaRepository.

public interface FactAggRepository extends JpaRepository<FactAggRepository,Integer> {

@Query("select p from FactAggRepository as p where p.pId=:pId and p.periodStart=:periodStart")
public List<FactAggRepository> getAggregates(@Param("pId") Long pId,@Param("periodStart")LocalDateTime periodStart);

@Query("select p from UsageAgg as p where p.pId=:pId")
public List<UsageAgg> UsageAggregates(@Param("pId") Long pId);

}

Autowiring the repository to use the same methods as follows.

fetchedRecord = AggRepo.getAggregates(pId, periodStart);

Now the above the code returnd the List. Is it possible to get the CSV file with the data in the List without any conversion.please let me know. Thanks in advance.


问:
How to spread component props inside passed node element?
My question might be confusing but let me explain with an example here, let's say I have Button component and it has 5 different props like (type, href, appearance...) and if we want to do following:

```<code><Button type='button' href='<a { ...buttonProps }>Test Link</a>'/>
</code>```

Basically attach all Button props to a tag easily.

I found something similar over here but didn't get it. Any suggestions?

答:
You need to change your button component and it should accept tag as property.

```<code>
export default function Button({ Tag = "button", children, ...props }) {
  return <Tag {...props}>{children}</Tag>;
}
</code>```

use button like this.

```<code><Button>Test</Button>
<Button Tag="a" href="https://stackoverflow.com/" target="_blank">
  Test Link
</Button>
</code>```

working codesandbox:

Body:
My question might be confusing but let me explain with an example here, let's say I have Button component and it has 5 different props like (type, href, appearance...) and if we want to do following:

<Button type='button' href='Test Link'/>

Basically attach all Button props to a tag easily.

I found something similar over here but didn't get it. Any suggestions?

Body:
You need to change your button component and it should accept tag as property.

export default function Button({ Tag = "button", children, ...props }) {
  return <Tag {...props}>{children}</Tag>;
}

use button like this.

<Button>Test</Button>
<Button Tag="a" href="https://stackoverflow.com/" target="_blank">
  Test Link
</Button>

working codesandbox:


问:
Jenkins Job Can't find JDK but JDK configured in Jenkins
I have been trying to create a test job on Jenkins but I've been getting JRE error. Idea is simple:

1)job will run a simple test command "mvn clean test"
2)Allure report plug-in will generate test based on test results.

I can't get results generated on Jenkins job.

However when I run "mvn clean test" command on command line. I don't get any errors, test results are generated. I can see maven and JDK path is correct when I run following pipeline.

```<code>node('master') {
    stage ('Run tests')
    dir ('C:/Program Files (x86)/Jenkins/ProjectDirectory') {
        try {
            bat '''mvn -version'''
        }
        catch (Exception ex) { currentBuild.result = 'UNSTABLE' }
        finally {
            stage ('Publish report')
            step([$class: 'AllureReportPublisher', includeProperties: false, jdk: 'jdk-1.8', results: [[path: '/target/surefire-reports']]])
        }
    }
}
</code>```

Outputs:

```<code>C:\Program Files (x86)\Jenkins\ProjectDirectory>mvn -version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: C:\3rd_party\apache-maven-3.6.3\bin\..
Java version: 1.8.0_191, vendor: Oracle Corporation, runtime: C:\Program Files (x86)\Java\jre1.8.0_191
Default locale: en_US, platform encoding: Cp1252
OS name: "windows server 2016", version: "10.0", arch: "x86", family: "windows"
</code>```

If I run tests in the Jenkins pipeline, I get following error.

```<code>[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.942 s
[INFO] Finished at: 2020-02-07T14:51:07Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile (default-testCompile) on project restassuredcourse: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
</code>```

I have correct JDK path in Manage Jenkins > Configure System.

If I execute "mvn -version" in Jenkins pipeline. I can see Jenkins machine can access correct path.

答: Just to check I generated gradle.build file and instead of executing "mvn clean test" . I used "gradlew clean test" and it worked. The problem is with maven but I couldn't understand why maven does not use system JDK.</p>

Body:
I have been trying to create a test job on Jenkins but I've been getting JRE error. Idea is simple:

1)job will run a simple test command "mvn clean test"
2)Allure report plug-in will generate test based on test results.

I can't get results generated on Jenkins job.

However when I run "mvn clean test" command on command line. I don't get any errors, test results are generated. I can see maven and JDK path is correct when I run following pipeline.

node('master') {
    stage ('Run tests')
    dir ('C:/Program Files (x86)/Jenkins/ProjectDirectory') {
        try {
            bat '''mvn -version'''
        }
        catch (Exception ex) { currentBuild.result = 'UNSTABLE' }
        finally {
            stage ('Publish report')
            step([$class: 'AllureReportPublisher', includeProperties: false, jdk: 'jdk-1.8', results: [[path: '/target/surefire-reports']]])
        }
    }
}

Outputs:

C:\Program Files (x86)\Jenkins\ProjectDirectory>mvn -version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: C:\3rd_party\apache-maven-3.6.3\bin\..
Java version: 1.8.0_191, vendor: Oracle Corporation, runtime: C:\Program Files (x86)\Java\jre1.8.0_191
Default locale: en_US, platform encoding: Cp1252
OS name: "windows server 2016", version: "10.0", arch: "x86", family: "windows"

If I run tests in the Jenkins pipeline, I get following error.

[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.942 s
[INFO] Finished at: 2020-02-07T14:51:07Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:testCompile (default-testCompile) on project restassuredcourse: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I have correct JDK path in Manage Jenkins > Configure System.

If I execute "mvn -version" in Jenkins pipeline. I can see Jenkins machine can access correct path.


问:
Getting PDO exception 42000 on PDO SQL query
This has been bugging me for a fair amount of time now and I can't seem to find were the issue lies. This is the query I'm stuck at:

$stmt2 = $conn->prepare('SELECT a.[zone], b.[source_external_subscriber_id], SUM(b.[source_customer_cost]) AS [total]
    FROM billing_zones a INNER JOIN cdr b
    ON a.[id] = b.[source_customer_billing_zone_id]
    WHERE destination_account_id = :destinationId
    GROUP BY b.[source_external_subscriber_id], a.[zone]');
$stmt2->execute(array('destinationId' => $destinationId));
```

The message I get:

Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[zone], b.[source_external_subscriber_id], SUM(b.[source_customer_cost] AS [tota' at line 1 in /home/integracion.php:14

答:
Squared brackets ([...]) are for Microsoft SQL Server, not for MySQL/MariaDB. You need to use backticks instead

```<code>--       v----v------- check this
SELECT a.`zone` ...
</code>```

Note that you can use double quotes too if you enable SQL_MODE=ANSI_QUOTE. Double quotes are SQL-92 standard and should be compatible with any DBMS

Body:
This has been bugging me for a fair amount of time now and I can't seem to find were the issue lies. This is the query I'm stuck at:

$stmt2 = $conn->prepare('SELECT a.[zone], b.[source_external_subscriber_id], SUM(b.[source_customer_cost]) AS [total]
    FROM billing_zones a INNER JOIN cdr b
    ON a.[id] = b.[source_customer_billing_zone_id]
    WHERE destination_account_id = :destinationId
    GROUP BY b.[source_external_subscriber_id], a.[zone]');
$stmt2->execute(array('destinationId' => $destinationId));

The message I get:

Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '[zone], b.[source_external_subscriber_id], SUM(b.[source_customer_cost] AS [tota' at line 1 in /home/integracion.php:14

Body:
Squared brackets ([...]) are for Microsoft SQL Server, not for MySQL/MariaDB. You need to use backticks instead

--       v----v------- check this
SELECT a.`zone` ...

Note that you can use double quotes too if you enable SQL_MODE=ANSI_QUOTE. Double quotes are SQL-92 standard and should be compatible with any DBMS


问:
Better text in SVG announcements in screen readers (VoiceOver)
I have an SVG figure that represents a name card for a person:

  <svg
    viewBox="0 0 300 100"
    style="border: 1px solid black;"
  >
    <g>
      <text x="5" y="25">Name</text>
      <text x="120" y="25">Joe Smith</text>
    </g>

    <g>
      <text x="5" y="55">Age</text>
      <text x="120" y="55">55</text>
    </g>

    <g>
        <text x="5" y="85">Occupation</text>
        <text x="120" y="85">Astronaut</text>
      </g>
  </svg>
```

VoiceOver reads it like this:

Name, group

Name

End of, name, group

Joe Smith, group

Joe Smith

End of, Joe Smith, group

Age, group

Age

End of, Age, group

55, group

55

End of, 55, group

Occupation, group

Occupation

End of, Occupation, group

Astronaut, group

Astronaut

End of, Astronaut, group

It's very, very verbose. How do I modify this code to make VoiceOver read it like this?

Name

Joe Smith

Age

55

Occupation

Astronaut

I'm looking for a solution using SVG / ARIA. I know I can implement this using HTML and achieve better results in VoiceOver, but this is just a dummy example to illustrate the problem.

答:
You can safely remove the <g> elements as they serve no real purpose for display (they are used for layering in an editor and as a possible point to apply transforms, styling etc.)

After doing that the element will read correctly.

I recommend using SVG OMG to optimise your SVGs, especially if they are large and complex graphics. You may still need to remove some <g> tags, you can safely do this just using a replace function on <g> and </g> (the hacky way!) or better yet use an XML reader / writer and do it properly!

Body:
I have an SVG figure that represents a name card for a person:

  <svg
    viewBox="0 0 300 100"
    style="border: 1px solid black;"
  >
    <g>
      <text x="5" y="25">Name</text>
      <text x="120" y="25">Joe Smith</text>
    </g>

    <g>
      <text x="5" y="55">Age</text>
      <text x="120" y="55">55</text>
    </g>

    <g>
        <text x="5" y="85">Occupation</text>
        <text x="120" y="85">Astronaut</text>
      </g>
  </svg>

VoiceOver reads it like this:

Name, group

Name

End of, name, group

Joe Smith, group

Joe Smith

End of, Joe Smith, group

Age, group

Age

End of, Age, group

55, group

55

End of, 55, group

Occupation, group

Occupation

End of, Occupation, group

Astronaut, group

Astronaut

End of, Astronaut, group

It's very, very verbose. How do I modify this code to make VoiceOver read it like this?

Name

Joe Smith

Age

55

Occupation

Astronaut

I'm looking for a solution using SVG / ARIA. I know I can implement this using HTML and achieve better results in VoiceOver, but this is just a dummy example to illustrate the problem.


问:
Programmatically retrieve Maven Dependencies
Pls are there any Java libraries that can retrieve Maven dependencies from a POM file? Anything that does not require retrieving out put of a mvn command. Thanks</p>

答:
Thanks.

I used the MavenProject library. Pretty straight forward.
I also used MavenXppReader to get the model that I passed to MavenProject(). The rest was a matter of calling the right methods.


问:
Share file via intent android to whatsapp with fingerprint on not work
Hi I'm sharing file using intent.
And work well, share to whatsapp too.

```<code>fun shareFile(fileList: List<File>) {
        activity?.let {
            val target = Intent(Intent.ACTION_SEND_MULTIPLE)
            val uriList = fileList.map { file ->
                FileProvider.getUriForFile(
                        it.baseContext, it.applicationContext?.packageName + ".provider", file)
            }

            target.putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uriList))
            target.type = "application/pdf"
            target.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
            target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

            try {
                startActivity(Intent.createChooser(target, ""))
            } catch (e: ActivityNotFoundException) {
                Crashlytics.logException(e)
            }
        }
    }
</code>```

But the problem if whatsapp with fingerprint on.
Share file not work.

Any suggestion to share on this case?

Thank you

答:
Ah, I found the solution
I should not include this code

```<code>target.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
</code>```

so remove this code, share will work on whatsapp with fingerprint on

Thanks for all the reply

Body:
Hi I'm sharing file using intent.
And work well, share to whatsapp too.

fun shareFile(fileList: List<File>) {
        activity?.let {
            val target = Intent(Intent.ACTION_SEND_MULTIPLE)
            val uriList = fileList.map { file ->
                FileProvider.getUriForFile(
                        it.baseContext, it.applicationContext?.packageName + ".provider", file)
            }

            target.putParcelableArrayListExtra(Intent.EXTRA_STREAM, ArrayList(uriList))
            target.type = "application/pdf"
            target.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
            target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

            try {
                startActivity(Intent.createChooser(target, ""))
            } catch (e: ActivityNotFoundException) {
                Crashlytics.logException(e)
            }
        }
    }

But the problem if whatsapp with fingerprint on.
Share file not work.

Any suggestion to share on this case?

Thank you

Body:
Ah, I found the solution
I should not include this code

target.flags = Intent.FLAG_ACTIVITY_NO_HISTORY

so remove this code, share will work on whatsapp with fingerprint on

Thanks for all the reply


问:
How to change line space with a SpannableString?
For a project, I have to edit text in an EditText with some attributes like bold, italic, size... etc. So, I have made a CustomSpan, which implements StyleSpan, with all the attributes I need. Below my code :

```<code>class CustomSpan(
    val bold: Boolean = false,
    val italic: Boolean = false,
    val size: Int = 14,
    val color: Int = Color.BLACK,
    val letterSpacing: Float = 0f
): StyleSpan(when {
        bold && italic -> Typeface.BOLD_ITALIC
        bold -> Typeface.BOLD
        italic -> Typeface.ITALIC
        else -> Typeface.NORMAL
    }) {

    override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)

        ds.color = color
        ds.textSize = size.toFloat()
        ds.letterSpacing = letterSpacing
    }

    override fun updateMeasureState(paint: TextPaint) {
        super.updateMeasureState(paint)

        paint.color = color
        paint.textSize = size.toFloat()
        paint.letterSpacing = letterSpacing
    }

    fun copy() : CustomSpan = CustomSpan(bold, italic, size, color, font, letterSpacing)

    fun copyWith(bold: Boolean? = null,
                 italic: Boolean? = null,
                 size: Int? = null,
                 color: Int? = null,
                 letterSpacing: Float? = null) : CustomSpan {

        return CustomSpan(
            bold = bold ?: this.bold,
            italic = italic ?: this.italic,
            size = size ?: this.size,
            color = color ?: this.color,
            letterSpacing = letterSpacing ?: this.letterSpacing
        )
    }
}
</code>```

But, I also need to change the line space between lines in my EditText. For that I thought to change bottom or padding, but I don't know how to do that. Have you some ideas ?

Thank you for your help, have a nice day !

答:
Probably you could achieve that via baselineShift, you could try something like this:

```<code>override fun updateDrawState(ds: TextPaint) {
    super.updateDrawState(ds)

    ds.color = color
    ds.textSize = size.toFloat()
    ds.letterSpacing = letterSpacing

    // here you might want to play with a specific value or ds.ascent/ds.descent..
    ds.baselineShift += 12
}
</code>```

Body:
For a project, I have to edit text in an EditText with some attributes like bold, italic, size... etc. So, I have made a CustomSpan, which implements StyleSpan, with all the attributes I need. Below my code :

class CustomSpan(
    val bold: Boolean = false,
    val italic: Boolean = false,
    val size: Int = 14,
    val color: Int = Color.BLACK,
    val letterSpacing: Float = 0f
): StyleSpan(when {
        bold && italic -> Typeface.BOLD_ITALIC
        bold -> Typeface.BOLD
        italic -> Typeface.ITALIC
        else -> Typeface.NORMAL
    }) {

    override fun updateDrawState(ds: TextPaint) {
        super.updateDrawState(ds)

        ds.color = color
        ds.textSize = size.toFloat()
        ds.letterSpacing = letterSpacing
    }

    override fun updateMeasureState(paint: TextPaint) {
        super.updateMeasureState(paint)

        paint.color = color
        paint.textSize = size.toFloat()
        paint.letterSpacing = letterSpacing
    }

    fun copy() : CustomSpan = CustomSpan(bold, italic, size, color, font, letterSpacing)

    fun copyWith(bold: Boolean? = null,
                 italic: Boolean? = null,
                 size: Int? = null,
                 color: Int? = null,
                 letterSpacing: Float? = null) : CustomSpan {

        return CustomSpan(
            bold = bold ?: this.bold,
            italic = italic ?: this.italic,
            size = size ?: this.size,
            color = color ?: this.color,
            letterSpacing = letterSpacing ?: this.letterSpacing
        )
    }
}

But, I also need to change the line space between lines in my EditText. For that I thought to change bottom or padding, but I don't know how to do that. Have you some ideas ?

Thank you for your help, have a nice day !

Body:
Probably you could achieve that via baselineShift, you could try something like this:

override fun updateDrawState(ds: TextPaint) {
    super.updateDrawState(ds)

    ds.color = color
    ds.textSize = size.toFloat()
    ds.letterSpacing = letterSpacing

    // here you might want to play with a specific value or ds.ascent/ds.descent..
    ds.baselineShift += 12
}


问:
Need to show Preview Video Thumbnails while seeking (Like youtube) for iOS
I need to show Video Preview Thumbanils while seeking in AVPlayer.
Just like how youtube shows them. (iOS)
(Also for live streaming) (Solution preferred more for Wowza/Amazon S3)

答:
You can try this Youtube helper instead -
https://github.com/youtube/youtube-ios-player-helper</p>


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

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

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

答:
Why doesn't the following work for you?

const tableBody = document.getElementById("table-body");

const amountOfInputs = 3;

function generateRow() {
  let generatedHtmlBody = "
";
  for (let i = 1; i <= amountOfInputs; i++) {
    generatedHtmlBody += `<td><input id="input-${i}" type="date" /></td>`
  }
  generatedHtmlBody += `<td><input type="submit" value="submit" /></td></tr>`;
  return generatedHtmlBody;
}

function addRow() {
  tableBody.innerHTML += generateRow();
}

addRow();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="addRow()">Add row</button>
<table>
  <thead>
    <tr id="table-header-first-row">
      <th>Table</th>
    </tr>
  </thead>
  <tbody id="table-body">
  </tbody>
</table></code>```

Body:
for this example

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

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

Body:
Why doesn't the following work for you?

const tableBody = document.getElementById("table-body");

const amountOfInputs = 3;

function generateRow() {
  let generatedHtmlBody = "<tr>";
  for (let i = 1; i <= amountOfInputs; i++) {
    generatedHtmlBody += `<td><input id="input-${i}" type="date" /></td>`
  }
  generatedHtmlBody += `<td><input type="submit" value="submit" /></td></tr>`;
  return generatedHtmlBody;
}

function addRow() {
  tableBody.innerHTML += generateRow();
}

addRow();

<button onclick="addRow()">Add row</button>
<table>
  <thead>
    <tr id="table-header-first-row">
      <th>Table</th>
    </tr>
  </thead>
  <tbody id="table-body">
  </tbody>
</table>


问:
phpspreadsheet error : Message: syntax error, unexpected '='
I am getting error is : </p>

```<code>Type: ParseError

Message: syntax error, unexpected '='

Filename: /volume1/web/dbms/dev/akshay/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php

Line Number: 2460

my Code is :

    <?php
    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

    class Mgs_to_dbms extends MY_Controller{
       public function transfer_pe(){
        $spreadsheet = new Spreadsheet();
        }
    }
</code>```

答:
Method #1 Update PHP to v7.1

Method #2 Install a previous version of PhpSpreadsheet

Adjust composer.json

```<code>  "require": {
    "php": ">=7.0",
    "phpoffice/phpspreadsheet": "*"
  }
</code>```

And run

```<code>php composer.phar update phpoffice/phpspreadsheet
</code>```

Body:
I am getting error is :

Type: ParseError

Message: syntax error, unexpected '='

Filename: /volume1/web/dbms/dev/akshay/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Calculation/Calculation.php

Line Number: 2460

my Code is :

    <?php
    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

    class Mgs_to_dbms extends MY_Controller{
       public function transfer_pe(){
        $spreadsheet = new Spreadsheet();
        }
    }

Body:
Method #1 Update PHP to v7.1

Method #2 Install a previous version of PhpSpreadsheet

Adjust composer.json

  "require": {
    "php": ">=7.0",
    "phpoffice/phpspreadsheet": "*"
  }

And run

php composer.phar update phpoffice/phpspreadsheet


问:
Zoom out of website when using RSelenium without changing page size/resolution
I'd like to zoom out of RSelenium remote, but this is surprisingly difficult to find a solution.
I am aware of

How to zoom out page using RSelenium library in R?, but I woud like to not adjust the page size or the resolution---simply zoom out.

I have pondered sending control + substract simultaneously, but this is also not quite working. I have taken a look at How to press two keys simultaneously (i.e., control-s) in a webpage using RSelenium?, which as the OP noted, control + a worked but not control + s, and subsequently control + substract didn't work either.

I also tried the Unicode method specified in How to send simultaneous keys in RSelenium ALT+S to web driver?, which did not work either.

```<code>library(RSelenium)
driver <- rsDriver()
remDr <- driver[["client"]]
remDr$navigate("https://www.google.com/")
webElem <- remDr$findElement("css", "html")
webElem$sendKeysToElement(list(key = "control", "-"))              ## Does not work
webElem$sendKeysToElement(list(key = "control", key = "subtract")) ## Does not work
</code>```

The browser is Chrome.

答:
I don't think the problem is with sending the keys to the browser, since as noted in the linked posts, it is possible to send control + a to the browser window to select elements. It seems rather that the keys are not being recognised as commands to the browser application.

There are other ways round this problem however.

As @Muzzamil suggests, you can get a similar effect with changing the css of the document body using Chrome, though this doesn't work in Firefox.

If you want to natively change the browser zoom in a way that persists throughout the session, I can demonstrate solutions using Firefox and Chrome, since in both cases one can navigate to the html-based options page and interact with it to set the browser zoom level.

Here's how you do it with Firefox:

library(RSelenium)

zoom_firefox <- function(client, percent)
{
  store_page <- client$getCurrentUrl()[[1]]
  client$navigate("about:preferences")
  webElem <- client$findElement("css", "#defaultZoom")
  webElem$clickElement()
  webElem$sendKeysToElement(list(as.character(percent)))
  webElem$sendKeysToElement(list(key = "return"))
  client$navigate(store_page)
}
```

<p>This allows the following:</p>

```driver <- rsDriver(browser = "firefox")
client <- driver$client
client$navigate("https://www.google.com")
client$screenshot(display = TRUE)
```

<p>We can see the default zoom is set (100%):</p>

<p><img src="https://i.stack.imgur.com/CIEA2.png" alt="enter image description here"></p>

<p>Now we zoom out to 50% like this:</p>

<pre class="lang-r prettyprint-override"><code>zoom_firefox(client, 50)
client$screenshot(display = TRUE)
</code>```

And zoom back in like this:

zoom_firefox(client, 100)
client$screenshot(display = TRUE)
```

<p><img src="https://i.stack.imgur.com/xysA1.png" alt="enter image description here"></p>

<p>It's harder with Chrome because its options page uses a complex, nested shadow DOM. Since we can't get an xpath or css selectors to navigate a shadow dom, we need to extract the element's webdriver id using javascript and then force this Id onto another web element which we can then control.</p>

```zoom_chrome <- function(client, percent)
{
  store_page <- client$getCurrentUrl()[[1]]
  client$navigate("chrome://settings/")
  webElemId <- client$executeScript(paste0("return document.querySelector",
                                           "(\"body > settings-ui\").",
                                           "shadowRoot.querySelector(\"#main\")",
                                           ".shadowRoot.querySelector",
                                           "(\"settings-basic-page\")",
                                           ".shadowRoot.querySelector",
                                           "(\"#basicPage > ",
                                           "settings-section:nth-child(8)",
                                           "> settings-appearance-page\")",
                                           ".shadowRoot.querySelector",
                                           "(\"#zoomLevel\");"),
                                    args = list("dummy"))
  webElem <- client$findElement("css", "html")
  webElem@.xData$elementId <- as.character(webElemId)
  webElem$clickElement()
  webElem$sendKeysToElement(list("3"))
  zooms <- c(25, 33, 50, 67, 75, 8:11 * 10, 125, 150, 175, 200, 250, 3:5 * 100)
  desired_zoom <- which.min(abs(percent - zooms))
  current_zoom <- which(zooms == 300)
  n_keys <- desired_zoom - current_zoom
  if(n_keys > 0)
    for(i in seq(n_keys))
      webElem$sendKeysToElement(list(key = "down_arrow"))
  if(n_keys < 0)
    for(i in seq(abs(n_keys)))
      webElem$sendKeysToElement(list(key = "up_arrow"))
  webElem$sendKeysToElement(list(as.character(percent)))
  webElem$sendKeysToElement(list(key = "return"))
  client$navigate(store_page)
}
```

<p>But it works in the same way:</p>

```driver <- rsDriver(browser = "chrome", chromever = "80.0.3987.106")
client <- driver$client
client$navigate("https://www.google.com")
client$screenshot(display = TRUE)
zoom_chrome(client, 50)
client$screenshot(display = TRUE)
zoom_chrome(client, 100)
client$screenshot(display = TRUE)
```

Which gives exactly the same results as firefox.

Of course, you could easily write a simple wrapper function that selects which "zoom" function to call based on the current browser.

I have not looked into implementing this in internet explorer or phantomjs since they do not have html-based options pages.

Body:
I'd like to zoom out of RSelenium remote, but this is surprisingly difficult to find a solution.
I am aware of

How to zoom out page using RSelenium library in R?, but I woud like to not adjust the page size or the resolution---simply zoom out.

I have pondered sending control + substract simultaneously, but this is also not quite working. I have taken a look at How to press two keys simultaneously (i.e., control-s) in a webpage using RSelenium?, which as the OP noted, control + a worked but not control + s, and subsequently control + substract didn't work either.

I also tried the Unicode method specified in How to send simultaneous keys in RSelenium ALT+S to web driver?, which did not work either.

library(RSelenium)
driver <- rsDriver()
remDr <- driver[["client"]]
remDr$navigate("https://www.google.com/")
webElem <- remDr$findElement("css", "html")
webElem$sendKeysToElement(list(key = "control", "-"))              ## Does not work
webElem$sendKeysToElement(list(key = "control", key = "subtract")) ## Does not work

The browser is Chrome.

Body:
I don't think the problem is with sending the keys to the browser, since as noted in the linked posts, it is possible to send control + a to the browser window to select elements. It seems rather that the keys are not being recognised as commands to the browser application.

There are other ways round this problem however.

As @Muzzamil suggests, you can get a similar effect with changing the css of the document body using Chrome, though this doesn't work in Firefox.

If you want to natively change the browser zoom in a way that persists throughout the session, I can demonstrate solutions using Firefox and Chrome, since in both cases one can navigate to the html-based options page and interact with it to set the browser zoom level.

Here's how you do it with Firefox:

library(RSelenium)

zoom_firefox <- function(client, percent)
{
  store_page <- client$getCurrentUrl()[[1]]
  client$navigate("about:preferences")
  webElem <- client$findElement("css", "#defaultZoom")
  webElem$clickElement()
  webElem$sendKeysToElement(list(as.character(percent)))
  webElem$sendKeysToElement(list(key = "return"))
  client$navigate(store_page)
}

This allows the following:

driver <- rsDriver(browser = "firefox")
client <- driver$client
client$navigate("https://www.google.com")
client$screenshot(display = TRUE)

We can see the default zoom is set (100%):

Now we zoom out to 50% like this:

zoom_firefox(client, 50)
client$screenshot(display = TRUE)

And zoom back in like this:

zoom_firefox(client, 100)
client$screenshot(display = TRUE)

It's harder with Chrome because its options page uses a complex, nested shadow DOM. Since we can't get an xpath or css selectors to navigate a shadow dom, we need to extract the element's webdriver id using javascript and then force this Id onto another web element which we can then control.

zoom_chrome <- function(client, percent)
{
  store_page <- client$getCurrentUrl()[[1]]
  client$navigate("chrome://settings/")
  webElemId <- client$executeScript(paste0("return document.querySelector",
                                           "(\"body > settings-ui\").",
                                           "shadowRoot.querySelector(\"#main\")",
                                           ".shadowRoot.querySelector",
                                           "(\"settings-basic-page\")",
                                           ".shadowRoot.querySelector",
                                           "(\"#basicPage > ",
                                           "settings-section:nth-child(8)",
                                           "> settings-appearance-page\")",
                                           ".shadowRoot.querySelector",
                                           "(\"#zoomLevel\");"),
                                    args = list("dummy"))
  webElem <- client$findElement("css", "html")
  webElem@.xData$elementId <- as.character(webElemId)
  webElem$clickElement()
  webElem$sendKeysToElement(list("3"))
  zooms <- c(25, 33, 50, 67, 75, 8:11 * 10, 125, 150, 175, 200, 250, 3:5 * 100)
  desired_zoom <- which.min(abs(percent - zooms))
  current_zoom <- which(zooms == 300)
  n_keys <- desired_zoom - current_zoom
  if(n_keys > 0)
    for(i in seq(n_keys))
      webElem$sendKeysToElement(list(key = "down_arrow"))
  if(n_keys < 0)
    for(i in seq(abs(n_keys)))
      webElem$sendKeysToElement(list(key = "up_arrow"))
  webElem$sendKeysToElement(list(as.character(percent)))
  webElem$sendKeysToElement(list(key = "return"))
  client$navigate(store_page)
}

But it works in the same way:

driver <- rsDriver(browser = "chrome", chromever = "80.0.3987.106")
client <- driver$client
client$navigate("https://www.google.com")
client$screenshot(display = TRUE)
zoom_chrome(client, 50)
client$screenshot(display = TRUE)
zoom_chrome(client, 100)
client$screenshot(display = TRUE)

Which gives exactly the same results as firefox.

Of course, you could easily write a simple wrapper function that selects which "zoom" function to call based on the current browser.

I have not looked into implementing this in internet explorer or phantomjs since they do not have html-based options pages.


问:
How to Test Select for Update in MySQL
I am performing SELECT ... FOR UPDATE or row level locking with InnoDB tables.

My intention is to only one request can read the same row. So if two users make request for the same data as the same time. Only one of them get data, who fires the query first.

But How can i test that locking is placed or not. as I am testing it by retrieving the same data at same time and both users getting the data.

Note: My tables are InnoDB, My query executes in transaction, my query as below:

```<code>SELECT * FROM table_name WHERE cond FOR UPDATE;
</code>```

Any other thing I have to check for this to make work?

答:
open 2 mysql client session.

on session 1:

```<code>mysql> start transaction;

mysql> SELECT * FROM table_name WHERE cond FOR UPDATE;

... (result here) ...

1 row in set (0.00 sec)
</code>```

on session 2:

```<code>mysql> start transaction;

mysql> SELECT * FROM table_name WHERE cond FOR UPDATE;

... (no result yet, will wait for the lock to be released) ...
</code>```

back to session 1, to update selected record (and release the lock):

```<code>mysql> UPDATE table_name SET something WHERE cond;

mysql> commit;
</code>```

back to session 2:

1) either showing lock timeout error

```<code>ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
</code>```

2) or showing result

```<code>... (result here) ...

1 row in set (0.00 sec)
</code>```

3) or showing no result (because corresponding record has been modified, so specified condition was not met)

```<code>Empty set (0.00 sec)
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to Test Select for Update in MySQL

Body:
I am performing SELECT ... FOR UPDATE or row level locking with InnoDB tables.

My intention is to only one request can read the same row. So if two users make request for the same data as the same time. Only one of them get data, who fires the query first.

But How can i test that locking is placed or not. as I am testing it by retrieving the same data at same time and both users getting the data.

Note: My tables are InnoDB, My query executes in transaction, my query as below:

SELECT * FROM table_name WHERE cond FOR UPDATE;

Any other thing I have to check for this to make work?

Body:
open 2 mysql client session.

on session 1:

mysql> start transaction;

mysql> SELECT * FROM table_name WHERE cond FOR UPDATE;

... (result here) ...

1 row in set (0.00 sec)

on session 2:

mysql> start transaction;

mysql> SELECT * FROM table_name WHERE cond FOR UPDATE;

... (no result yet, will wait for the lock to be released) ...

back to session 1, to update selected record (and release the lock):

mysql> UPDATE table_name SET something WHERE cond;

mysql> commit;

back to session 2:

1) either showing lock timeout error

ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

2) or showing result

... (result here) ...

1 row in set (0.00 sec)

3) or showing no result (because corresponding record has been modified, so specified condition was not met)

Empty set (0.00 sec)


问:
how to display async function output in angular template
Actually am treying to build an social media app and i want to check if post is already liked or not so that i can disabled button
here what i have done so far:

Post Component

```<code>export class PostsComponent implements OnInit {
  posts;
  socket;
  user;
  constructor(private authService: AuthService, private postService: PostService) {
    this.socket = io('http://localhost:3000')
  }

  fromNowDate(date) {
    return moment(date).fromNow()
  }
  ngOnInit() {
    this.user = this.authService.getUser()
    console.log(this.user)
    this.getAllPost()
    this.socket.on('refreshPage', data => {
      this.getAllPost()
    })
  }

  getAllPost() {
    this.postService.getPosts().subscribe(post => {
      this.posts = post
      console.log(this.posts)

    })
  }

  likePost(post) {
    console.log(post)
    this.postService.likePost(post).subscribe(data => {
      this.socket.emit('refresh', { data: 'refresh the postss' })
      console.log(data)
    })
  }

  isLikedPost(post, userID) {
    post.find(post => {
      console.log(post.userID == userID)
      return post.userID == userID
    })
  }

}
</code>```

and as you can see in Post componenet there is function that is isLikedPost() which takes post and userID as an argument.

so i use this function in my template

```<code><div *ngFor="let post of posts">
    <ul class="collection" style="border: none;">
        <li class="collection-item avatar">
            <img src="https://via.placeholder.com/150" alt="" class="circle">
            <span class="title">{{post.user.username}}</span>
            <p>Username<br>
                {{fromNowDate(post.createdAt)}}
            </p>
            <a href="#!" class="secondary-content"><i class="material-icons">grade</i></a>
        </li>

        <div class="row">
            <div class="col s12 m12">
                <div class="card">
                    <div class="card-image" style="width: 30%; left: 35%;">
                        <img src="https://via.placeholder.com/150" style="padding-top: 20px;">

                    </div>
                    <!-- <span class="card-title">Card Title</span> -->
                    <div class="card-content">
                        <p>{{post.post}}</p>
                    </div>
                    <div class="card-action">
                        <i class="material-icons" style="cursor: pointer;" (click)="likePost(post)">thumb_up </i><span
                            style="position: absolute; margin-left: 5px;">{{post.likes.length}}</span>
                            <p>{{isLikedPost(post.likes, user.user._id)}}</p> //<-- here the function is used
                        <i class="material-icons" style="margin-left: 35px; cursor: pointer;">comment </i><span
                            style="position: absolute; margin-left: 5px;">{{post.comments.length}}</span>

                    </div>
                </div>
            </div>
        </div>

    </ul>
</div>
</code>```

my problem is here is that am didn't getting any output of this function. Help

答:
```<code>  isLikedPost(post :Post[], userID) : boolean{

    return post.some(post => {
      console.log(post.userID == userID)
      return post.userID == userID
    });
  }
</code>```

Body:
Actually am treying to build an social media app and i want to check if post is already liked or not so that i can disabled button
here what i have done so far:

Post Component

export class PostsComponent implements OnInit {
  posts;
  socket;
  user;
  constructor(private authService: AuthService, private postService: PostService) {
    this.socket = io('http://localhost:3000')
  }

  fromNowDate(date) {
    return moment(date).fromNow()
  }
  ngOnInit() {
    this.user = this.authService.getUser()
    console.log(this.user)
    this.getAllPost()
    this.socket.on('refreshPage', data => {
      this.getAllPost()
    })
  }

  getAllPost() {
    this.postService.getPosts().subscribe(post => {
      this.posts = post
      console.log(this.posts)

    })
  }

  likePost(post) {
    console.log(post)
    this.postService.likePost(post).subscribe(data => {
      this.socket.emit('refresh', { data: 'refresh the postss' })
      console.log(data)
    })
  }

  isLikedPost(post, userID) {
    post.find(post => {
      console.log(post.userID == userID)
      return post.userID == userID
    })
  }

}

and as you can see in Post componenet there is function that is isLikedPost() which takes post and userID as an argument.

so i use this function in my template

            {{post.user.username}}

Username

                {{fromNowDate(post.createdAt)}}

            grade

{{post.post}}

                        thumb_up {{post.likes.length}}

{{isLikedPost(post.likes, user.user._id)}}
 //<-- here the function is used
                        comment {{post.comments.length}}

my problem is here is that am didn't getting any output of this function. Help


问:
How do I grab an element with jQuery without a way to reference it via class, ID, etc
I have a table like so:

```<code><table>
<thead>
    <tr>
        <th>Hostname</th>
        <th>Action</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>127.0.0.1</td>
        <td><a name="delete" onclick="remove_host('127.0.0.1')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.2</td>
        <td><a name="delete" onclick="remove_host('127.0.0.2')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.3</td>
        <td><a name="delete" onclick="remove_host('127.0.0.3')">Remove</a></td>
    </tr>
</tbody>
</code>```

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

答:
if using jQuery...</p>

```<code><script type=text/javascript>
$("document").ready( function(){
    $("a[name=delete]").click(function(){
        $(this).hide().after('<img src="loading.png" />');
    });
});
</script>
</code>```

Body:
I have a table like so:

        Hostname
        Action

        127.0.0.1
        Remove

        127.0.0.2
        Remove

        127.0.0.3
        Remove

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

Body:
if using jQuery...

<script type=text/javascript>
$("document").ready( function(){
    $("a[name=delete]").click(function(){
        $(this).hide().after('<img src="loading.png" />');
    });
});
</script>


问:
How do i acces files in Xamarin.Form app?
I am current writing a small tool with Xamarin Form (Android) that takes some file content and displays them in some specific way.
In these files i have some cross-links (e.g. jpeg-images) that should be embedded in the display of the file.

To get the main file i am using "CrossFilePicker.Current.PickFile()".
It returns an "FileData" object, which allready has the main file contents, plus the URI of that file.

If there is a cross-link in that file i can assume that the linked file is in the same folder as the main file.

My idea (taking jpeg as example) to get the base-folder of the file and append the name of the jpeg and then open the image as stream:

```<code>ImagePath = Path.Combine(baseFolder.Trim(), imageFile.Trim());

try
{
    fileStream = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
    fileStream.DisposeWith(Disposables);

    ImageSource = ImageSource.FromStream(() => fileStream);
    ShowImage = true;
}
catch
{
    // Ignore
}
</code>```

Unfortunatelly FileStream failes, and claims it could not find the containing directory.

The path towards to JPG look like this:

```<code>/document/0F1E-120D/TestData/P1060371.jpg
</code>```

The file path i get from the Picker is:

```<code>content://com.android.externalstorage.documents/document/0F1E-120D%3ATestData%2FTestFile.txt
</code>```

Using that a an URI i can extract the local path:

```<code>/document/0F1E-120D:TestData/TestFile.txt
</code>```

When removing the file name i get

```<code>/document/0F1E-120D:TestData
</code>```

Obviously that path is invalid...

Any hint on how i can get a valid path i can feed into the FileStream for reading the file?
Any more hints about that permissions i have to take care? Currently i have set READ_EXTERNAL_STORAGE

答:
If you use NetStandard2.0 you use this code

```<code>System.IO.File.ReadAllBytes(filePath);
</code>```

it also applied to specific platform(e.g: Xamarin.Android, Xamarin.iOS, etc)

Body:
I am current writing a small tool with Xamarin Form (Android) that takes some file content and displays them in some specific way.
In these files i have some cross-links (e.g. jpeg-images) that should be embedded in the display of the file.

To get the main file i am using "CrossFilePicker.Current.PickFile()".
It returns an "FileData" object, which allready has the main file contents, plus the URI of that file.

If there is a cross-link in that file i can assume that the linked file is in the same folder as the main file.

My idea (taking jpeg as example) to get the base-folder of the file and append the name of the jpeg and then open the image as stream:

ImagePath = Path.Combine(baseFolder.Trim(), imageFile.Trim());

try
{
    fileStream = new FileStream(ImagePath, FileMode.Open, FileAccess.Read);
    fileStream.DisposeWith(Disposables);

    ImageSource = ImageSource.FromStream(() => fileStream);
    ShowImage = true;
}
catch
{
    // Ignore
}

Unfortunatelly FileStream failes, and claims it could not find the containing directory.

The path towards to JPG look like this:

/document/0F1E-120D/TestData/P1060371.jpg

The file path i get from the Picker is:

content://com.android.externalstorage.documents/document/0F1E-120D%3ATestData%2FTestFile.txt

Using that a an URI i can extract the local path:

/document/0F1E-120D:TestData/TestFile.txt

When removing the file name i get

/document/0F1E-120D:TestData

Obviously that path is invalid...

Any hint on how i can get a valid path i can feed into the FileStream for reading the file?
Any more hints about that permissions i have to take care? Currently i have set READ_EXTERNAL_STORAGE

Body:
If you use NetStandard2.0 you use this code

System.IO.File.ReadAllBytes(filePath);

it also applied to specific platform(e.g: Xamarin.Android, Xamarin.iOS, etc)


问:
DAO insert behavior doesnt seem normal
I made the DAO to create a sales offer and it is similar to an other DAO where it makes users and that connects and works. But the one below keeps skipping the if statements and I'm not sure why it isn't adding to the data base. I ran the same command in the SQL string in oracle and it worked there.</p>

```<code>public boolean sendOffer(Sales sell) {

    boolean done = false;
    int key =0;
    Connection conn = cu.getConnection();
    try {

        String sql = "INSERT INTO sales (offer_amount, offer_who, car_id) values(?,?,?)";
        String[]keys= {"ID"};
        PreparedStatement ps = conn.prepareStatement(sql,keys);
        ps.setInt(1, sell.getOfferAmount());
        ps.setInt(2, sell.getOwnerID());  //foriegn key
        ps.setInt(3, sell.getCarID()); // forgien key
        int number = ps.executeUpdate();
        ResultSet rs = ps.getGeneratedKeys();
        if(number!=1)
        {
            log.warn("data insert fail");
        }
        else
        {
            log.trace("success");
            done=true;
        }
           if(rs.next()) {
               key=rs.getInt(1);
               sell.setID(key);
               conn.commit();
               }
           else {
               log.warn("data not found");
           }

    }catch(SQLException e)
    {

    }
finally {
    try {
        conn.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
}

    // TODO Auto-generated method stub
    return done;
}'''
</code>```

答:
The main issue is that an exception is happening in your code but the try/catch block is intercepting it and swallowing it silently. While it may be tempting to catch and swallow exceptions, truth is it always causes more problems than it solves and the key concept of handling exceptions is to NOT handle them: just put the throws declaration and let the application crash.

You then have other possible side-issues depending on how the Connection was obtained in the first place, like the fact that you're never closing the PreparedStatement and the ResultSet (if the connection is closed, they are closed as well... but if the connection is returned to a pool then they are never going to be closed).

In general the above code tends to pack too much functionality in a single method and can quickly spiral out of control, so you might want to divide it in smaller chunks with clear individual responsibilities.

All of the above is common to observe wherever Connection and PreparedStatement are used directly, be it for maximum performance reasons or for lack of experience. Typically in web applications using the Spring framework this is solved through the use of a JdbcTemplate but I cannot assume that you are using Spring so I won't show its usage here.

At a minimum, I would modify your code roughly as follows:

```<code>public boolean sendOffer(Sales sell) {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = cu.getConnection();
        ps = prepareInsertOfferStatement(sell, conn);
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        sell.setID(extractKey(rs));
        conn.commit();
        log.trace("success");
        return true;
    }
    catch(Exception ex) {
        log.error(ex);  // this is actually probably bad. Consider putting a throws declaration and get rid of this catch
        return false;
    }
    finally {
        closeQuietly(rs, ps, conn);
    }
}

private void closeQuietly(AutoCloseable... objs) {
    for(AutoCloseable obj : objs) {
        try {
            obj.close();
        } catch (SQLException e) {
            // this is usually mostly safe to ignore. Maybe log a warning somewhere
        }
    }
}

private PreparedStatement prepareInsertOfferStatement(Sales sell, Connection conn) throws SQLException {
    String sql = "INSERT INTO sales (offer_amount, offer_who, car_id) values(?,?,?)";
    String[] keys= {"ID"};
    PreparedStatement ps = conn.prepareStatement(sql,keys);
    ps.setInt(1, sell.getOfferAmount());
    ps.setInt(2, sell.getOwnerID());  //foreign key
    ps.setInt(3, sell.getCarID()); // foreign key
    return ps;
}

private int extractKey(ResultSet rs) throws SQLException {
    if(rs.next()) {
        return rs.getInt(1);
    }
    else {
        throw new Exception("The statement did not return any generated key.");
    }
}
</code>```

As you can see it's not shorter, but responsibilities are clearer and all objects are closed accordingly. Furthermore, it gives you nice reusable primitives to close connections and related objects and to extract the key from other inserts you will want to do. Further abstractions would allow you to obtain more primitives, but I think this is sufficient for you to get the gist of it.

Title: DAO insert behavior doesnt seem normal

Body:
I made the DAO to create a sales offer and it is similar to an other DAO where it makes users and that connects and works. But the one below keeps skipping the if statements and I'm not sure why it isn't adding to the data base. I ran the same command in the SQL string in oracle and it worked there.

public boolean sendOffer(Sales sell) {

    boolean done = false;
    int key =0;
    Connection conn = cu.getConnection();
    try {

        String sql = "INSERT INTO sales (offer_amount, offer_who, car_id) values(?,?,?)";
        String[]keys= {"ID"};
        PreparedStatement ps = conn.prepareStatement(sql,keys);
        ps.setInt(1, sell.getOfferAmount());
        ps.setInt(2, sell.getOwnerID());  //foriegn key
        ps.setInt(3, sell.getCarID()); // forgien key
        int number = ps.executeUpdate();
        ResultSet rs = ps.getGeneratedKeys();
        if(number!=1)
        {
            log.warn("data insert fail");
        }
        else
        {
            log.trace("success");
            done=true;
        }
           if(rs.next()) {
               key=rs.getInt(1);
               sell.setID(key);
               conn.commit();
               }
           else {
               log.warn("data not found");
           }

    }catch(SQLException e)
    {

    }
finally {
    try {
        conn.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
}

    // TODO Auto-generated method stub
    return done;
}'''

Body:
The main issue is that an exception is happening in your code but the try/catch block is intercepting it and swallowing it silently. While it may be tempting to catch and swallow exceptions, truth is it always causes more problems than it solves and the key concept of handling exceptions is to NOT handle them: just put the throws declaration and let the application crash.

You then have other possible side-issues depending on how the Connection was obtained in the first place, like the fact that you're never closing the PreparedStatement and the ResultSet (if the connection is closed, they are closed as well... but if the connection is returned to a pool then they are never going to be closed).

In general the above code tends to pack too much functionality in a single method and can quickly spiral out of control, so you might want to divide it in smaller chunks with clear individual responsibilities.

All of the above is common to observe wherever Connection and PreparedStatement are used directly, be it for maximum performance reasons or for lack of experience. Typically in web applications using the Spring framework this is solved through the use of a JdbcTemplate but I cannot assume that you are using Spring so I won't show its usage here.

At a minimum, I would modify your code roughly as follows:

public boolean sendOffer(Sales sell) {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        conn = cu.getConnection();
        ps = prepareInsertOfferStatement(sell, conn);
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        sell.setID(extractKey(rs));
        conn.commit();
        log.trace("success");
        return true;
    }
    catch(Exception ex) {
        log.error(ex);  // this is actually probably bad. Consider putting a throws declaration and get rid of this catch
        return false;
    }
    finally {
        closeQuietly(rs, ps, conn);
    }
}

private void closeQuietly(AutoCloseable... objs) {
    for(AutoCloseable obj : objs) {
        try {
            obj.close();
        } catch (SQLException e) {
            // this is usually mostly safe to ignore. Maybe log a warning somewhere
        }
    }
}

private PreparedStatement prepareInsertOfferStatement(Sales sell, Connection conn) throws SQLException {
    String sql = "INSERT INTO sales (offer_amount, offer_who, car_id) values(?,?,?)";
    String[] keys= {"ID"};
    PreparedStatement ps = conn.prepareStatement(sql,keys);
    ps.setInt(1, sell.getOfferAmount());
    ps.setInt(2, sell.getOwnerID());  //foreign key
    ps.setInt(3, sell.getCarID()); // foreign key
    return ps;
}

private int extractKey(ResultSet rs) throws SQLException {
    if(rs.next()) {
        return rs.getInt(1);
    }
    else {
        throw new Exception("The statement did not return any generated key.");
    }
}

As you can see it's not shorter, but responsibilities are clearer and all objects are closed accordingly. Furthermore, it gives you nice reusable primitives to close connections and related objects and to extract the key from other inserts you will want to do. Further abstractions would allow you to obtain more primitives, but I think this is sufficient for you to get the gist of it.


问:
Query TFS to show all releases and whether or not it is set for approval. V 2017.3
I need to run a query in sql that will show all the TFS releases from all projects and whether or not it is setup for pre relase approvals.  I see in the defaultcollection db there is the Release.tbl_ReleaseDefinition table, it has a lot of data but not approval info.  I do see the Release.tbl_DefinitionEnvironment and I see ApprovalOptions there, but that seems to be showing the approval info for every release created whereas I am needing info on release definitions only.</p>

答:
Just as Daniel pointed out, we highly not recommend you dig into TFS databased directly.

According to your description, you just need the approval info for all release definitions. Suggest you use Rest API to handle this.

For a single release, you could use below Rest API:

```<code>GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions/{definitionId}?api-version=5.1
</code>```

It will return both  preDeployApprovals and postDeployApprovals, for example:

```<code>"preDeployApprovals": {
        "approvals": [
          {
            "rank": 1,
            "isAutomated": false,
            "isNotificationOn": false,
            "approver": {
              "displayName": "Chuck Reinhart",
              "url": "https://vssps.dev.azure.com/fabrikam/_apis/Identities/aeb95c63-4fac-4948-84ce-711b0a9dda97",
              "_links": {
                "avatar": {
                  "href": "https://dev.azure.com/fabrikam/_apis/GraphProfile/MemberAvatars/aad.YjYxMjE5ZWQtODEwYS03OTU3LWJjYzAtMjQ0YTI5ZDk0ZjFl"
                }
              },
              "id": "aeb95c63-4fac-4948-84ce-711b0a9dda97",
              "uniqueName": "fabfiber@outlook.com",
              "imageUrl": "https://dev.azure.com/fabrikam/_api/_common/identityImage?id=aeb95c63-4fac-4948-84ce-711b0a9dda97",
              "descriptor": "aad.YjYxMjE5ZWQtODEwYS03OTU3LWJjYzAtMjQ0YTI5ZDk0ZjFl"
            },
            "id": 118
          }
        ],
</code>```

More details please take a look at official doc here: Definitions - Get

For multiple release, you should use list: Definitions - List

Hope this helps.

Body:
Just as Daniel pointed out, we highly not recommend you dig into TFS databased directly.

According to your description, you just need the approval info for all release definitions. Suggest you use Rest API to handle this.

For a single release, you could use below Rest API:

GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions/{definitionId}?api-version=5.1

It will return both  preDeployApprovals and postDeployApprovals, for example:

"preDeployApprovals": {
        "approvals": [
          {
            "rank": 1,
            "isAutomated": false,
            "isNotificationOn": false,
            "approver": {
              "displayName": "Chuck Reinhart",
              "url": "https://vssps.dev.azure.com/fabrikam/_apis/Identities/aeb95c63-4fac-4948-84ce-711b0a9dda97",
              "_links": {
                "avatar": {
                  "href": "https://dev.azure.com/fabrikam/_apis/GraphProfile/MemberAvatars/aad.YjYxMjE5ZWQtODEwYS03OTU3LWJjYzAtMjQ0YTI5ZDk0ZjFl"
                }
              },
              "id": "aeb95c63-4fac-4948-84ce-711b0a9dda97",
              "uniqueName": "fabfiber@outlook.com",
              "imageUrl": "https://dev.azure.com/fabrikam/_api/_common/identityImage?id=aeb95c63-4fac-4948-84ce-711b0a9dda97",
              "descriptor": "aad.YjYxMjE5ZWQtODEwYS03OTU3LWJjYzAtMjQ0YTI5ZDk0ZjFl"
            },
            "id": 118
          }
        ],

More details please take a look at official doc here: Definitions - Get

For multiple release, you should use list: Definitions - List

Hope this helps.


问:
gsutil ServiceException: 401 Anonymous caller does not have storage.objects.list access to bucket even though I'm loggedin in gcloud
I am trying to create an internal app to upload files to google cloud. I don't want each individual user or this app to log in so I'm using a service account. I login into the service account and everything is ok, but when I try to upload it gives me this error:
ServiceException: 401 Anonymous caller does not have storage.objects.list access to bucket

As you can see I am logged in with a service account and my account and(neither service or personal) works

答: I had the same issue, tried to do gsutil config then it recommended me gcloud auth login which opened google in the browser. After i logged in, i could download with gsutil cp -r gs://my_bucket/Directory local_save_path the entire bucket and save it locally.


答:
try this</p>

```<code>windows = df.groupby("Time")["A"].rolling(60)
df[out] = windows.apply(lambda x: np.polyfit(range(60), x, 1)[0], raw=True).values
</code>```

Title: Pandas - Rolling slope calculation

Body:
How to calculate slope of each columns' rolling(window=60) value, stepped by 5?

I'd like to calculate every 5 minutes' value, and I don't need every record's results.

Here's sample dataframe and results:

df
Time                A    ...      N
2016-01-01 00:00  1.2    ...    4.2
2016-01-01 00:01  1.2    ...    4.0
2016-01-01 00:02  1.2    ...    4.5
2016-01-01 00:03  1.5    ...    4.2
2016-01-01 00:04  1.1    ...    4.6
2016-01-01 00:05  1.6    ...    4.1
2016-01-01 00:06  1.7    ...    4.3
2016-01-01 00:07  1.8    ...    4.5
2016-01-01 00:08  1.1    ...    4.1
2016-01-01 00:09  1.5    ...    4.1
2016-01-01 00:10  1.6    ...    4.1
....

result
Time                A    ...      N
2016-01-01 00:04  xxx    ...    xxx
2016-01-01 00:09  xxx    ...    xxx
2016-01-01 00:14  xxx    ...    xxx
...

Can df.rolling function be applied to this problem?

It's fine if NaN is in the window, meaning subset could be less than 60.

Body:
try this

windows = df.groupby("Time")["A"].rolling(60)
df[out] = windows.apply(lambda x: np.polyfit(range(60), x, 1)[0], raw=True).values


问:
SSRS report subscriptions cannot be created
I am not able to create subscriptions for SSRS reports as it gives the following error:

Subscriptions cannot be created because the credentials used to run
  the report are not stored, or if a linked report, the link is no
  longer valid.

My set up is as following:

ServerA - Database Server

ServerB - Report Server

MachineC - Internet explorer to view the reports

So I am viewing reports on Machine C, IE, and ServerB connects to ServerA for Datasource.

答:
The problem sounds like the report expects the user to provide credentials when it is viewed. When you create a subscription, it does not have the credentials to execute the report.

Go to the report, click the properties tab, then choose Data Sources in the left pane.

Are you using a shared data source? Is it using Windows integrated security? If so, can you change it to use a service account made just to run these reports? You may need to view these properties by viewing the data source itself.

If it is a custom data source is the option "Credentials supplied by the user running the report" selected? If so, can you change it to "Credentials stored securely in the report server"?

Either way, if you want to set up a subscription, I have made it work by providing credentials in the data source rather than have the user input them.

If you are worried about security, I would suggest managing that on the report level rather than the data source level.


问:
Emoticon cause html text elements to not be vertically aligned
I have an .jspx file with html

```<code><label for="foo">Country:</label>
<div id="foo"><c:out value="FooBar-islands"/></div> <br/>
</code>```

The result of the above code is perfectly vertically aligned. Two columns with texts.

When I add an emoticon like below, they are not aligned anymore.

```<code><label for="foo">Country:</label>
<div id="foo"><c:out value=""/></div> <br/>
</code>```

If I add an emoticon in the label as well:

```<code><label for="foo">Country:</label>
<div id="foo"><c:out value=""/></div> <br/>
</code>```

Then they are aligned again.

I want to make a minimal encroachment on the code of this page. It feels like when adding the emoticon the encoding changes and that messes with the text baseline.

Can I fix this cleverly without changing the structure with label/div? (I've been looking for invisible/unobtrusive emoticons to add to the label but havn't found any)

答:
I tried wrapping the row in a div with:

```<code>.centeredRow {
    display: flex;
    flex-direction:row;
    align-items: center;
}
</code>```

Bigger incision than I would want, but the alignment is quite a bit better.

It is also not perfectly aligned. It is one pixel of, the text without emoticon encoding is one pixel higher. I assume this is still due to encoding text baseline shenanigans.

I invite better answers.

Body:
I have an .jspx file with html

Country:

<c:out value="FooBar-islands"/>

The result of the above code is perfectly vertically aligned. Two columns with texts.

When I add an emoticon like below, they are not aligned anymore.

Country:

<c:out value=""/>

If I add an emoticon in the label as well:

Country:

<c:out value=""/>

Then they are aligned again.

I want to make a minimal encroachment on the code of this page. It feels like when adding the emoticon the encoding changes and that messes with the text baseline.

Can I fix this cleverly without changing the structure with label/div? (I've been looking for invisible/unobtrusive emoticons to add to the label but havn't found any)

Body:
I tried wrapping the row in a div with:

.centeredRow {
    display: flex;
    flex-direction:row;
    align-items: center;
}

Bigger incision than I would want, but the alignment is quite a bit better.

It is also not perfectly aligned. It is one pixel of, the text without emoticon encoding is one pixel higher. I assume this is still due to encoding text baseline shenanigans.

I invite better answers.


问:
Export two different list into one string
I have two different lists I want to export in single CSV file in ASP.NET

```<code>string listToString1= string.Join(",", list1.ToArray());
string listToString2= string.Join(",", list2.ToArray());
string finalstring = "Collection ID" + listToString1+ "," + "Collection Title" + listToString2;

return File(new System.Text.UTF8Encoding().GetBytes(finalstring), "text/csv", "abcd.csv");
</code>```

Here i am getting output like:

Collection ID , id1,id2,id3

Collection Title, Title1,Title2,Title3

But I want output to be like :

Collection Id, Collection Title id1          , Title1 id2          ,
  Title2 id3          , Title3

Here collection ids are in same column and collection titles are in same column

答:
What you need is a Zip method:

```<code>List<string> list1 = new List<string>() { "Collection ID", "id1", "id2" , "id3" };
List<string> list2 = new List<string>() { "Collection Title", "Title1", "Title2", "Title3" };
var result = string.Join(" ",list1.Zip(list2, (f,l) => f + "," + l));
</code>```

You need to make sure that you've added the System.Linq to your using directive though

Body:
I have two different lists I want to export in single CSV file in ASP.NET

string listToString1= string.Join(",", list1.ToArray());
string listToString2= string.Join(",", list2.ToArray());
string finalstring = "Collection ID" + listToString1+ "," + "Collection Title" + listToString2;

return File(new System.Text.UTF8Encoding().GetBytes(finalstring), "text/csv", "abcd.csv");

Here i am getting output like:

Collection ID , id1,id2,id3

Collection Title, Title1,Title2,Title3

But I want output to be like :

Collection Id, Collection Title id1          , Title1 id2          ,
  Title2 id3          , Title3

Here collection ids are in same column and collection titles are in same column

Body:
What you need is a Zip method:

List<string> list1 = new List<string>() { "Collection ID", "id1", "id2" , "id3" };
List<string> list2 = new List<string>() { "Collection Title", "Title1", "Title2", "Title3" };
var result = string.Join(" ",list1.Zip(list2, (f,l) => f + "," + l));

You need to make sure that you've added the System.Linq to your using directive though


问:
How to implement a navigation controller within a child fragment?
I have a navigation controller fragment defined inside my activity_main that has a match height and width of parent. So when I navigate between fragments, it replaces the entire screen. Now say I navigate to a fragment that loads up a material card. I want that material card to have its own navigation controller that takes up the height and width of the material card. So when I use its navigation controller, it will only replace fragments within the material card view and not change the parent's view.

Is there a way to have two navigation host fragments? So I can define one inside activity_main and then another one that I can define inside the child fragment.

activity_main:

```<code><androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@id/barrier"
            app:navGraph="@navigation/base_nav_graph" />

</code>```

childfragment:

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_layout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="600dp"
    android:layout_height="match_parent"
    android:layout_gravity="end"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintEnd_toEndOf="parent">

    <fragment
        android:id="@+id/nav_child_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:navGraph="@navigation/child_nav_graph" />
</code>```

答:
See advanced sample
https://github.com/android/architecture-components-samples/tree/master/NavigationAdvancedSample

There used multiple navigation controllers for BottomNavigationView items

Body:
I have a navigation controller fragment defined inside my activity_main that has a match height and width of parent. So when I navigate between fragments, it replaces the entire screen. Now say I navigate to a fragment that loads up a material card. I want that material card to have its own navigation controller that takes up the height and width of the material card. So when I use its navigation controller, it will only replace fragments within the material card view and not change the parent's view.

Is there a way to have two navigation host fragments? So I can define one inside activity_main and then another one that I can define inside the child fragment.

activity_main:

<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@id/barrier"
            app:navGraph="@navigation/base_nav_graph" />

childfragment:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_layout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="600dp"
    android:layout_height="match_parent"
    android:layout_gravity="end"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintEnd_toEndOf="parent">

    <fragment
        android:id="@+id/nav_child_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:navGraph="@navigation/child_nav_graph" />


问:
How to use sys.argv?
Hello I am trying to write a function which will take different argument and
would be used in another function in another script. My idea is to be able to precise a parameter directly from the terminal and the script will somewhat go the function with the precise parameter and Apply the correct line.

So I run my script like this and put f which is my parameter but I do not have any answer , below the full script.

```<code>C:\Users\Etu\ocuments>python test2.py f
</code>```

first script

```<code>
import sys

first_arg = sys.argv[1]

texte = "je MaNgE"

def get_command(texte, first_arg):
    if first_arg =="f":
        texte = texte.lower()
        return texte
    elif first_arg=="t":
        return texte.split()
    elif first_arg =="r":

    return texte

    else:
        raise Exception("Wrongfile feature type entered. Possible values: 't','f', 'r")

</code>```

second script

```<code>from test import *

texte = "je MaNgE"

def choose (texte):
    texte=get_command(texte, first_arg)

    print(texte)

</code>```

The idea is to modify directly the parameter from the shell without going Inside the script all the time.

答:
What you need here is called COMMAND LINE ARGUMENTS.

here's a way to implement it.

```<code>import sys
first_arg = sys.argv[1]
second_arg = sys.argv[2]
</code>```

the first_args will hold whatever the first parameter is passed to the script and so on.

sys.argv is a list of parameters provided to the python interpreter. sys.argv[0] will always be the file name.

Title: How to use sys.argv?

Body:
Hello I am trying to write a function which will take different argument and
would be used in another function in another script. My idea is to be able to precise a parameter directly from the terminal and the script will somewhat go the function with the precise parameter and Apply the correct line.

So I run my script like this and put f which is my parameter but I do not have any answer , below the full script.

C:\Users\Etu\ocuments>python test2.py f

first script

import sys

first_arg = sys.argv[1]

texte = "je MaNgE"

def get_command(texte, first_arg):
    if first_arg =="f":
        texte = texte.lower()
        return texte
    elif first_arg=="t":
        return texte.split()
    elif first_arg =="r":

    return texte

    else:
        raise Exception("Wrongfile feature type entered. Possible values: 't','f', 'r")

second script

from test import *

texte = "je MaNgE"

def choose (texte):
    texte=get_command(texte, first_arg)

    print(texte)

The idea is to modify directly the parameter from the shell without going Inside the script all the time.

Body:
What you need here is called COMMAND LINE ARGUMENTS.

here's a way to implement it.

import sys
first_arg = sys.argv[1]
second_arg = sys.argv[2]

the first_args will hold whatever the first parameter is passed to the script and so on.

sys.argv is a list of parameters provided to the python interpreter. sys.argv[0] will always be the file name.


问:
How can I search through a single sharepoint List in a site collection using Search Scope?
I have added a Web Address rule to a Search Scope and set the Folder url to the following for searching through a single list in site collection :-

http://svrmosstest3/sites/asmtportal/Lists/SearchList

And added this scope to the search dropdown, this search is working fine and will return results from that list only, but it returns one extra item which is an entry for the list itself which is :-

http://svrmosstest3/sites/asmtportal/Lists/SearchList/AllItems.aspx

because this will always fall under the Rule URL.

Is there any other method to create a search scope that will search only through the items of a Single Sharepoint List in a site collection ??

Please tell me ,.. if there are any sharepoint experts ??

答: You will most likely need to add a crawl rule to exclude that one page from being added to the index (which will then prevent it from being included in your search scope).</p>


问:
How to find pair of numbers in a list which makes a sum as given number
A few days back I encountered a problem which says that there is a list of numbers and a value called total. Now we need to write a program that gives a list of tuples (only 2 elements in the tuple) and sum of each tuple should be equal to the value of total. Example: Following is the input:

```<code>input = [1,2,3,4,6,7,8,9]
total = 10
</code>```

Following is the output:

```<code>output = [(1,9), (2,8), (3,7), (4,6)]
</code>```

答:
Using a list-comprehension with itertools.combinations:

```<code>>>> import itertools
>>> inpt = [1,2,3,4,6,7,8,9]
>>> total = 10
>>> [p for p in itertools.combinations(inpt, 2) if sum(p) == total]
[(1, 9), (2, 8), (3, 7), (4, 6)]
</code>```

Note you should not use input as a variable name as it shadows the builtin input() function.

To do this without itertools, we can use the following list-comprehension:

```<code>>>> [(inpt[i],inpt[j]) for i in range(len(inpt)) for j in range(i+1, len(inpt)) if sum((inpt[i],inpt[j])) == total]
>>> [(1, 9), (2, 8), (3, 7), (4, 6)]
</code>```

Body:
A few days back I encountered a problem which says that there is a list of numbers and a value called total. Now we need to write a program that gives a list of tuples (only 2 elements in the tuple) and sum of each tuple should be equal to the value of total. Example: Following is the input:

input = [1,2,3,4,6,7,8,9]
total = 10

Following is the output:

output = [(1,9), (2,8), (3,7), (4,6)]

Body:
Using a list-comprehension with itertools.combinations:

>>> import itertools
>>> inpt = [1,2,3,4,6,7,8,9]
>>> total = 10
>>> [p for p in itertools.combinations(inpt, 2) if sum(p) == total]
[(1, 9), (2, 8), (3, 7), (4, 6)]

Note you should not use input as a variable name as it shadows the builtin input() function.

To do this without itertools, we can use the following list-comprehension:

>>> [(inpt[i],inpt[j]) for i in range(len(inpt)) for j in range(i+1, len(inpt)) if sum((inpt[i],inpt[j])) == total]
>>> [(1, 9), (2, 8), (3, 7), (4, 6)]


问:
Is there a way to use a Javascript package in R?
I am trying to call a Javascript file in R. Inside the Java script file has a require function that calls a a Javascript package. When I try to run this in R, I am getting a ReferenceError. I am not so familiar with frontend, but I want to use Javascript to do something for me.

rFile.R

```<code>extendShinyjs(script = 'file/jsFile.js')
</code>```

jsFile.js

```<code>var = require('some-module')
</code>```

Error in R:

```<code>Error in : shinyjs: Error parsing the JavaScript file: ReferenceError: require is not defined.
</code>```

Do you know how I can make this work?

答:
This R Package helped me to convert the npm package to "browserify" it. Thanks for all your help.

https://cran.r-project.org/web/packages/V8/vignettes/npm.html#what_is_v8_(not)

If you will be encountering errors like:

```<code>ReferenceError: window is not defined
</code>```

You need to remove all the lines in bundle.js that uses window. Though I am still not sure of the implications of doing so. I am still working on how to call functions.

Body:
I am trying to call a Javascript file in R. Inside the Java script file has a require function that calls a a Javascript package. When I try to run this in R, I am getting a ReferenceError. I am not so familiar with frontend, but I want to use Javascript to do something for me.

rFile.R

extendShinyjs(script = 'file/jsFile.js')

jsFile.js

var = require('some-module')

Error in R:

Error in : shinyjs: Error parsing the JavaScript file: ReferenceError: require is not defined.

Do you know how I can make this work?

Body:
This R Package helped me to convert the npm package to "browserify" it. Thanks for all your help.

https://cran.r-project.org/web/packages/V8/vignettes/npm.html#what_is_v8_(not)

If you will be encountering errors like:

ReferenceError: window is not defined

You need to remove all the lines in bundle.js that uses window. Though I am still not sure of the implications of doing so. I am still working on how to call functions.