问:
Return an array after loop async
I know that the solution to my problem is the promises but I can't understand at all how to apply it to what I want to do ... Can you help me without referring me to the courses on promises in javascript?

thx you

function getPosition (workers) {
    let counter = 0
    let allResult = []
    _.forEach(workers, (n) => {
        let firstname = n.firstname
        let lastname = n.lastname
        let streetname = n.address.streetname
        let city = n.address.city
        let country = n.address.country
        axios.get('https://api-adresse.data.gouv.fr/search/?q=' + streetname + ' ' + city)
            .then(response => {
                let lon = response.data.features[0].geometry.coordinates[0]
                let lat = response.data.features[0].geometry.coordinates[1]
                let finalResult = {
                    firstname: firstname,
                    lastname: lastname,
                    address: {streetname: streetname, country: country, city: city, lon: lon, lat: lat}
                }
                logger.info('Longitude and latitude was found for ' + firstname + ' ' + lastname)
                counter++
                allResult.push(finalResult)
                if (counter === workers.length) {
                    return(allResult)
                }
            })
            .catch(error => {
                logger.error(error)
            })
    })
}```

I just want to return 'allresult' ...
thanks for your help

答:
You can't really return a promise, you can resolve it instead like so:

```<code>function getPosition(workers) {
    return Promise.all(workers.map(worker => {
        const {firstname, lastname, address: {streetname, city, country}} = worker;
        return axios.get(`https://api-adresse.data.gouv.fr/search/?q=${streetname} ${city}`)
            .then(response => {
                const [lon, lat] = response.data.features[0].geometry.coordinates;
                return {
                    firstname: firstname,
                    lastname: lastname,
                    address: {streetname, country, city, lon, lat}
                };
            })
            .catch(logger.error)
    })).then(results => results.filter(Boolean));
}
</code>```

And access the results in a form of

```<code>getPosition(workers)
    .then(allResults => {
        // do what you need with the results
    })
</code>```

Or alternatively with async/await syntax

```<code>(async ()=>{
    const allResults = await getPosition(workers)
    // do what you need with the results
})()
</code>```

Title: Return an array after loop async

Body:
I know that the solution to my problem is the promises but I can't understand at all how to apply it to what I want to do ... Can you help me without referring me to the courses on promises in javascript?

thx you

function getPosition (workers) {
    let counter = 0
    let allResult = []
    _.forEach(workers, (n) => {
        let firstname = n.firstname
        let lastname = n.lastname
        let streetname = n.address.streetname
        let city = n.address.city
        let country = n.address.country
        axios.get('https://api-adresse.data.gouv.fr/search/?q=' + streetname + ' ' + city)
            .then(response => {
                let lon = response.data.features[0].geometry.coordinates[0]
                let lat = response.data.features[0].geometry.coordinates[1]
                let finalResult = {
                    firstname: firstname,
                    lastname: lastname,
                    address: {streetname: streetname, country: country, city: city, lon: lon, lat: lat}
                }
                logger.info('Longitude and latitude was found for ' + firstname + ' ' + lastname)
                counter++
                allResult.push(finalResult)
                if (counter === workers.length) {
                    return(allResult)
                }
            })
            .catch(error => {
                logger.error(error)
            })
    })
}

I just want to return 'allresult' ...
thanks for your help

Body:
You can't really return a promise, you can resolve it instead like so:

function getPosition(workers) {
    return Promise.all(workers.map(worker => {
        const {firstname, lastname, address: {streetname, city, country}} = worker;
        return axios.get(`https://api-adresse.data.gouv.fr/search/?q=${streetname} ${city}`)
            .then(response => {
                const [lon, lat] = response.data.features[0].geometry.coordinates;
                return {
                    firstname: firstname,
                    lastname: lastname,
                    address: {streetname, country, city, lon, lat}
                };
            })
            .catch(logger.error)
    })).then(results => results.filter(Boolean));
}

And access the results in a form of

getPosition(workers)
    .then(allResults => {
        // do what you need with the results
    })

Or alternatively with async/await syntax

(async ()=>{
    const allResults = await getPosition(workers)
    // do what you need with the results
})()


来源: stackexchange

问:
Syncing localStorage
I'm looking for a solution that allows a browser's localStorage to be less local, so that people can access their data on multiple devices. The traditional way is to run a database on a server and have people log in; but I'm trying to avoid doing that. I'd like the server side to be lightweight - perhaps even completely static if possible - and to not have the job of safely storing passwords, worrying about data protection etc.

Many browsers have a login of some sort -- Google Account, Firefox Account etc -- that ties a user's browsers together. So the ideal solution would be to store data in localStorage, but use that account to sync across devices. There are interfaces such as chrome.storage that seem to be available to packaged apps, but not to ordinary web pages.

Is something like this possible with present technologies?

答:
AFAIK there are no good ways to do what you'd like to do. There are some hacks but they each have their own shortcomings.

If you really don't care about security here (which I'll assume is the case since you don't want a server): you could use the URL itself as your localStorage. That is to say, you could for example base64encode(JSON.stringify(yourLocalStorageData)) and tack that onto a URL: example.com/#eyJmb28iOiAiYmFyIn0=\n. When the browser opens your URL, it could start by looking for the above and perform the opposite procedure: localStorage = JSON.parse(base64decode(URL_DATA)).

From there you could make it the users problem of "syncing" the page by allowing them to share the URL using whatever method they choose.

Downside is of course keeping things in sync. User has 2 browsers. User shares the original link between browser A and browser B. User continues to work on browser B. User now opens browser A: it will not reflect the changes made in browser B unless if the URL was shared again, in the other direction.

I've seen a few examples of this technique already where the user would "download the application state" as text (again, base64 encoded) and would upload that text when coming back. It was worded as "take a backup" and "restore a backup" which is maybe more user friendly.

ContentLicense: CC BY-SA 3.0

Title: Syncing localStorage

ContentLicense: CC BY-SA 4.0


问:
Connect to a Database in Flask, Which Approach is better?
Method One: Using special g object from http://flask.pocoo.org/docs/tutorial/dbcon/ and http://flask.pocoo.org/docs/patterns/sqlite3/

```<code>import sqlite3
from flask import g

DATABASE = '/path/to/database.db'

def connect_db():
    return sqlite3.connect(DATABASE)

@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()
</code>```

Method Two: Using Mysterious _app_ctx_stack from https://github.com/mitsuhiko/flask/blob/master/examples/flaskr/flaskr.py

```<code>from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash, _app_ctx_stack
def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    top = _app_ctx_stack.top
    if not hasattr(top, 'sqlite_db'):
        top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
    return top.sqlite_db

@app.teardown_appcontext
def close_db_connection(exception):
    """Closes the database again at the end of the request."""
    top = _app_ctx_stack.top
    if hasattr(top, 'sqlite_db'):
        top.sqlite_db.close()
</code>```

Which method is better? What is the difference?

答:
To preserve the database connection within the same flask session you may use the application context and assign database connection.
If the connection breaks,the context will try to establish the connection back as it polls the connection object continuously.</p>

```<code>from flask import Flask
application = Flask(__name__)

def connect_to_database():
  db_handler = SqliteDBConnect("uid={0};""pwd={1}".format(UID, PWD),
                                table_prefix="{}".format(TBL_PRFX))
  return db_handler

fd = {'_database': None}
def get_db():
  db = fd['_database']
  if not isinstance(db, SqliteDBConnect):
    fd['_database'] = connect_to_database()
    db = fd['_database']
return db

with application.app_context():
  #Get DB connection from application's context
  db = LocalProxy(lambda: get_db())
</code>```

Body:
Method One: Using special g object from http://flask.pocoo.org/docs/tutorial/dbcon/ and http://flask.pocoo.org/docs/patterns/sqlite3/

import sqlite3
from flask import g

DATABASE = '/path/to/database.db'

def connect_db():
    return sqlite3.connect(DATABASE)

@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()

Method Two: Using Mysterious _app_ctx_stack from https://github.com/mitsuhiko/flask/blob/master/examples/flaskr/flaskr.py

from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash, _app_ctx_stack
def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    top = _app_ctx_stack.top
    if not hasattr(top, 'sqlite_db'):
        top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
    return top.sqlite_db

@app.teardown_appcontext
def close_db_connection(exception):
    """Closes the database again at the end of the request."""
    top = _app_ctx_stack.top
    if hasattr(top, 'sqlite_db'):
        top.sqlite_db.close()

Which method is better? What is the difference?

Body:
To preserve the database connection within the same flask session you may use the application context and assign database connection.
If the connection breaks,the context will try to establish the connection back as it polls the connection object continuously.

from flask import Flask
application = Flask(__name__)

def connect_to_database():
  db_handler = SqliteDBConnect("uid={0};""pwd={1}".format(UID, PWD),
                                table_prefix="{}".format(TBL_PRFX))
  return db_handler

fd = {'_database': None}
def get_db():
  db = fd['_database']
  if not isinstance(db, SqliteDBConnect):
    fd['_database'] = connect_to_database()
    db = fd['_database']
return db

with application.app_context():
  #Get DB connection from application's context
  db = LocalProxy(lambda: get_db())


问:
The temporary upload location [/tmp/tomcat.4296537502689403143.5000/work/Tomcat/localhost/ROOT] is not valid
I am using Spring Boot 1.5.13 version.

I got the exception message like below.

```<code>Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [/tmp/tomcat.4296537502689403143.5000/work/Tomcat/localhost/ROOT] is not valid
</code>```

I founded out this issue in Spring Github Issues.
https://github.com/spring-projects/spring-boot/issues/9616

But I still have questions of that.

I am not using File Upload things in my app. But the log says that "Could not parse multipart servlet request" why is that? (I got the exception when my app uses RestTemplate (Post method)

To solve the exception, I rebooted my app but It did not work right away. Although i rebooted my app, it had referenced the tomcat directory which was not exist. After a day after rebooting, it worked. I guess the directory was cached in somewhere in Spring or else..?

Please Help me out!

答:
For me it was using the correct dependency (if using java/maven) </p>

```<code>       <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
</code>```

Body:
I am using Spring Boot 1.5.13 version.

I got the exception message like below.

Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [/tmp/tomcat.4296537502689403143.5000/work/Tomcat/localhost/ROOT] is not valid

I founded out this issue in Spring Github Issues.
https://github.com/spring-projects/spring-boot/issues/9616

But I still have questions of that.

I am not using File Upload things in my app. But the log says that "Could not parse multipart servlet request" why is that? (I got the exception when my app uses RestTemplate (Post method)

To solve the exception, I rebooted my app but It did not work right away. Although i rebooted my app, it had referenced the tomcat directory which was not exist. After a day after rebooting, it worked. I guess the directory was cached in somewhere in Spring or else..?

Please Help me out!

Body:
For me it was using the correct dependency (if using java/maven)

       <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>


问:
excel, check if string contains a character a-z or A-Z
I have a column with unstructured data. I need to detect if the string has an alphabetical character meaning a-z or A-Z. I am not sure how to do this in excel with a formula or other. I am thinking this could be a long countif and sumproduct. Or maybe regex in excel. I will post an attempt try once I try this out more. But I am looking for some advice. While searching online, I could not find a formula to do this. Thanks for your help. Please see below screenshot for sample data.

答:
This is not case sensitive so it will return Yes for a|A

```<code>=IF(SUMPRODUCT(--ISNUMBER(SEARCH(MID(A1,ROW(INDIRECT("A$1:A"&LEN(A1))),1),"abcdefghijklmnopqrstuvwxyz"))),"Yes","No")
</code>```

Body:
This is not case sensitive so it will return Yes for a|A

=IF(SUMPRODUCT(--ISNUMBER(SEARCH(MID(A1,ROW(INDIRECT("A$1:A"&LEN(A1))),1),"abcdefghijklmnopqrstuvwxyz"))),"Yes","No")


问:
How to test if an object is a Proxy?
I would like to test if a JavaScript object is a Proxy. The trivial approach

```<code>if (obj instanceof Proxy) ...
</code>```

doesn't work here, nor does traversing the prototype chain for Proxy.prototype, since all relevant operations are effectively backed by the underlying target.

Is it possible to test if an arbitrary object is a Proxy?

答:
Use window.postMessage() with try-catch to get a hint

postMessage cannot serialize objects which incompatible with structured clone algorithm, like Proxy.

```<code>function shouldBeCloneable(o) {
    const type = typeof o;
    return (
        o?.constructor === ({}).constructor ||
        type === "undefined" ||
        o === null ||
        type === "boolean" ||
        type === "number" ||
        type === "string" ||
        o instanceof Date ||
        o instanceof RegExp ||
        o instanceof Blob ||
        o instanceof File ||
        o instanceof FileList ||
        o instanceof ArrayBuffer ||
        o instanceof ImageData ||
        o instanceof ImageBitmap ||
        o instanceof Array ||
        o instanceof Map ||
        o instanceof Set
    );
}

function isCloneable(obj) {
    try {
        postMessage(obj, "*");
    } catch (error) {
        if (error?.code === 25) return false; // DATA_CLONE_ERR
    }

    return true;
}

function isProxy(obj){
    const _shouldBeCloneable = shouldBeCloneable(obj);
    const _isCloneable = isCloneable(obj);

    if(_isCloneable) return false;
    if(!_shouldBeCloneable) return "maybe";

    return _shouldBeCloneable && !_isCloneable;
}

console.log("proxied {}", isProxy(new Proxy({},{})));
console.log("{}", isProxy({}));

console.log("proxied []", isProxy(new Proxy([],{})));
console.log("[]", isProxy([]));

console.log("proxied function", isProxy(new Proxy(()=>{},{})));
console.log("function", isProxy(()=>{}));

console.log("proxied Map", isProxy(new Proxy(new Map(),{})));
console.log("new Map()", isProxy(new Map()));

class A{};
console.log("proxied class", isProxy(new Proxy(A,{})));
console.log("class", isProxy(A));

console.log("proxied class instance", isProxy(new Proxy(new A(),{})));
console.log("class instance", isProxy(new A()));
</code>```

Title: How to test if an object is a Proxy?

Body:
I would like to test if a JavaScript object is a Proxy. The trivial approach

if (obj instanceof Proxy) ...

doesn't work here, nor does traversing the prototype chain for Proxy.prototype, since all relevant operations are effectively backed by the underlying target.

Is it possible to test if an arbitrary object is a Proxy?

Body:
Use window.postMessage() with try-catch to get a hint

postMessage cannot serialize objects which incompatible with structured clone algorithm, like Proxy.

function shouldBeCloneable(o) {
    const type = typeof o;
    return (
        o?.constructor === ({}).constructor ||
        type === "undefined" ||
        o === null ||
        type === "boolean" ||
        type === "number" ||
        type === "string" ||
        o instanceof Date ||
        o instanceof RegExp ||
        o instanceof Blob ||
        o instanceof File ||
        o instanceof FileList ||
        o instanceof ArrayBuffer ||
        o instanceof ImageData ||
        o instanceof ImageBitmap ||
        o instanceof Array ||
        o instanceof Map ||
        o instanceof Set
    );
}

function isCloneable(obj) {
    try {
        postMessage(obj, "*");
    } catch (error) {
        if (error?.code === 25) return false; // DATA_CLONE_ERR
    }

    return true;
}

function isProxy(obj){
    const _shouldBeCloneable = shouldBeCloneable(obj);
    const _isCloneable = isCloneable(obj);

    if(_isCloneable) return false;
    if(!_shouldBeCloneable) return "maybe";

    return _shouldBeCloneable && !_isCloneable;
}

console.log("proxied {}", isProxy(new Proxy({},{})));
console.log("{}", isProxy({}));

console.log("proxied []", isProxy(new Proxy([],{})));
console.log("[]", isProxy([]));

console.log("proxied function", isProxy(new Proxy(()=>{},{})));
console.log("function", isProxy(()=>{}));

console.log("proxied Map", isProxy(new Proxy(new Map(),{})));
console.log("new Map()", isProxy(new Map()));

class A{};
console.log("proxied class", isProxy(new Proxy(A,{})));
console.log("class", isProxy(A));

console.log("proxied class instance", isProxy(new Proxy(new A(),{})));
console.log("class instance", isProxy(new A()));


问:
Disable option that block repetitive alert in FireFox
I´m developing for web and my application use some alerts to show error messages but in firefox 4 if I show the alert more than one time, the option for blocking repetitive alert dialogs will appear, but if I check the option, I can not continue to do the next action.

Can you tell me how to hide the option in alert ? Is there any possibility  with javascript?

答:
No, that's the user's option not yours.

Edit: You can show error messages in a unique way using JQuery UI's dialog widget. This is not a standard popup box and is a nice way to display the error.

Another alternative is to have a div that you display errors in and show/hide it. This is less distracting since it shows all the errors at once.


问:
go get results in 'terminal prompts disabled' error for github private repo
I created the private repo examplesite/myprivaterepo using the Github UI from my browser.

Then I went to my go directory (on the desktop) and cloned it:

```<code>$ cd $GOPATH
$ go get github.com/examplesite/myprivaterepo
</code>```

So far so good. Created the file scheduler.go, added to repo, and pushed.

```<code>$ vim scheduler.go
$ git add scheduler.go
$ git commit
$ git push
</code>```

Everythng's OK. But when I went to a clean laptop  and tried to clone the repo, I got an error:

```<code># Now on laptop, which doesn't yet know about the repo
$ cd $GOPATH
$ go get github.com/examplesite/myprivaterepo
# At this point it should ask for my user ID and password ,right? But it doesn't.
# Instead, this error occurs:
cd .; git clone https://github.com/examplesite/myprivaterepo /Users/tom/go/src/github.com/examplesite/myprivaterepo
Cloning into '/Users/tom/go/src/github.com/examplesite/myprivaterepo'...
fatal: could not read Username for 'https://github.com': terminal prompts disabled
package github.com/examplesite/myprivaterepo: exit status 128
</code>```

Why is my laptop hating on my own repo and how can I get it to accept its fate? Thanks.

答:
It complains because it needs to use ssh instead of https but your git is still configured with https. so basically as others mentioned previously you need to either enable prompts or to configure git to use ssh instead of https. a simple way to do this by running the following:

```<code>git config --global --add url."git@github.com:".insteadOf "https://github.com/"
</code>```

or if you already use ssh with git in your machine, you can safely edit ~/.gitconfig and add the following line at the very bottom

Note: This covers all SVC, source version control, that depends on what you exactly use, github, gitlab, bitbucket)

```<code># Enforce SSH
[url "ssh://git@github.com/"]
  insteadOf = https://github.com/
[url "ssh://git@gitlab.com/"]
        insteadOf = https://gitlab.com/
[url "ssh://git@bitbucket.org/"]
  insteadOf = https://bitbucket.org/
</code>```

If you want to keep password pompts disabled, you need to cache password. For more information on how to cache your github password on mac, windows or linux, please visit this page.

For more information on how to add ssh to your github account, please visit this page.

Also, more importantly, if this is a private repository for a company or for your self, you may need to skip using proxy or checksum database for such repos to avoid exposing them publicly.

To do this, you need to set GOPRIVATE environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database.

The variable is a comma-separated list of patterns (same syntax of Go's path.Match) of module path prefixes. For example,

```<code>export GOPRIVATE=*.corp.example.com,github.com/mycompany/*
</code>```

Or

```<code>go env -w GOPRIVATE=github.com/mycompany/*
</code>```

For more information on how to solve private packages/modules checksum validation issues, please read this article.

For more information about go 13 modules and new enhancements, please check out Go 1.13 Modules Release notes.

One last thing not to forget to mention, you can still configure go get to authenticate and fetch over https, all you need to do is to add the following line to $HOME/.netrc

```<code>machine github.com login USERNAME password APIKEY
</code>```

For GitHub accounts, the password can be a personal access tokens.

For more information on how to do this, please check Go FAQ page.

Please feel free to leave a comment in case you want more support or help.

Body:
I created the private repo examplesite/myprivaterepo using the Github UI from my browser.

Then I went to my go directory (on the desktop) and cloned it:

$ cd $GOPATH
$ go get github.com/examplesite/myprivaterepo

So far so good. Created the file scheduler.go, added to repo, and pushed.

$ vim scheduler.go
$ git add scheduler.go
$ git commit
$ git push

Everythng's OK. But when I went to a clean laptop  and tried to clone the repo, I got an error:

# Now on laptop, which doesn't yet know about the repo
$ cd $GOPATH
$ go get github.com/examplesite/myprivaterepo
# At this point it should ask for my user ID and password ,right? But it doesn't.
# Instead, this error occurs:
cd .; git clone https://github.com/examplesite/myprivaterepo /Users/tom/go/src/github.com/examplesite/myprivaterepo
Cloning into '/Users/tom/go/src/github.com/examplesite/myprivaterepo'...
fatal: could not read Username for 'https://github.com': terminal prompts disabled
package github.com/examplesite/myprivaterepo: exit status 128

Why is my laptop hating on my own repo and how can I get it to accept its fate? Thanks.

Body:
It complains because it needs to use ssh instead of https but your git is still configured with https. so basically as others mentioned previously you need to either enable prompts or to configure git to use ssh instead of https. a simple way to do this by running the following:

git config --global --add url."git@github.com:".insteadOf "https://github.com/"

or if you already use ssh with git in your machine, you can safely edit ~/.gitconfig and add the following line at the very bottom

Note: This covers all SVC, source version control, that depends on what you exactly use, github, gitlab, bitbucket)

# Enforce SSH
[url "ssh://git@github.com/"]
  insteadOf = https://github.com/
[url "ssh://git@gitlab.com/"]
        insteadOf = https://gitlab.com/
[url "ssh://git@bitbucket.org/"]
  insteadOf = https://bitbucket.org/

If you want to keep password pompts disabled, you need to cache password. For more information on how to cache your github password on mac, windows or linux, please visit this page.

For more information on how to add ssh to your github account, please visit this page.

Also, more importantly, if this is a private repository for a company or for your self, you may need to skip using proxy or checksum database for such repos to avoid exposing them publicly.

To do this, you need to set GOPRIVATE environment variable that controls which modules the go command considers to be private (not available publicly) and should therefore NOT use the proxy or checksum database.

The variable is a comma-separated list of patterns (same syntax of Go's path.Match) of module path prefixes. For example,

export GOPRIVATE=*.corp.example.com,github.com/mycompany/*

Or

go env -w GOPRIVATE=github.com/mycompany/*

For more information on how to solve private packages/modules checksum validation issues, please read this article.

For more information about go 13 modules and new enhancements, please check out Go 1.13 Modules Release notes.

One last thing not to forget to mention, you can still configure go get to authenticate and fetch over https, all you need to do is to add the following line to $HOME/.netrc

machine github.com login USERNAME password APIKEY

For GitHub accounts, the password can be a personal access tokens.

For more information on how to do this, please check Go FAQ page.

Please feel free to leave a comment in case you want more support or help.


问:
Reading a text file and sorting by extension using python
I would like to read a text file using python. If a line with .cpp found, process it first and then if a line with .java extension found, process it second.

Test.py is my sample code, using a for loop, it will read Test.txt and then it will process COMPILE_JAVA() method first and then it will execute COMPILE_CPP() method.

Test.txt

```<code>/home/jenkins/workspace/a/Hello.java
/home/jenkins/workspace/b/Hello.cpp
/home/jenkins/workspace/b/Hello1.cpp
</code>```

Test.py

```<code>for f in files:
    ACTION1 = False
    ACTION2 = False
    with open(f, 'r') as file:
        for line in (file):
            if ACTION1 is False and ('.cpp' in line ):
                COMPILE_CPP()
                ACTION1 = True
            elif ACTION2 is False and '.java' in line:
                COMPILE_JAVA()
                ACTION2 = True
                break
</code>```

答:
IIUC you can sort the list you read from test.txt by extension using os.path.splitext:

```<code>import os

with open(f, 'r') as file:
    sorted_files = sorted(file, key=lambda x: os.path.splitext(x)[1])
    for line in sorted_files:
        # rest of the code
</code>```

Given

```<code>l = ['/home/jenkins/workspace/a/Hello.java',
     '/home/jenkins/workspace/b/Hello.cpp',
     '/home/jenkins/workspace/b/Hello1.cpp']
</code>```

Then running sorted(l, key=lambda x: os.path.splitext(x)[1]) returns:

```<code>['/home/jenkins/workspace/b/Hello.cpp',
 '/home/jenkins/workspace/b/Hello1.cpp',
 '/home/jenkins/workspace/a/Hello.java']
</code>```

Explanation:

os.path.splitext returns a tuple (root, ext), e.g. os.path.splitext("dir/myfile.txt") returns ("dir/myfile", ".txt"), so lambda x: os.path.splitext(x)[1] returns the second part (.txt).

This is then passed as an argument to the sorted function, so the list gets sorted alphabetically by extension.

Body:
I would like to read a text file using python. If a line with .cpp found, process it first and then if a line with .java extension found, process it second.

Test.py is my sample code, using a for loop, it will read Test.txt and then it will process COMPILE_JAVA() method first and then it will execute COMPILE_CPP() method.

Test.txt

/home/jenkins/workspace/a/Hello.java
/home/jenkins/workspace/b/Hello.cpp
/home/jenkins/workspace/b/Hello1.cpp

Test.py

for f in files:
    ACTION1 = False
    ACTION2 = False
    with open(f, 'r') as file:
        for line in (file):
            if ACTION1 is False and ('.cpp' in line ):
                COMPILE_CPP()
                ACTION1 = True
            elif ACTION2 is False and '.java' in line:
                COMPILE_JAVA()
                ACTION2 = True
                break

Body:
IIUC you can sort the list you read from test.txt by extension using os.path.splitext:

import os

with open(f, 'r') as file:
    sorted_files = sorted(file, key=lambda x: os.path.splitext(x)[1])
    for line in sorted_files:
        # rest of the code

Given

l = ['/home/jenkins/workspace/a/Hello.java',
     '/home/jenkins/workspace/b/Hello.cpp',
     '/home/jenkins/workspace/b/Hello1.cpp']

Then running sorted(l, key=lambda x: os.path.splitext(x)[1]) returns:

['/home/jenkins/workspace/b/Hello.cpp',
 '/home/jenkins/workspace/b/Hello1.cpp',
 '/home/jenkins/workspace/a/Hello.java']

Explanation:

os.path.splitext returns a tuple (root, ext), e.g. os.path.splitext("dir/myfile.txt") returns ("dir/myfile", ".txt"), so lambda x: os.path.splitext(x)[1] returns the second part (.txt).

This is then passed as an argument to the sorted function, so the list gets sorted alphabetically by extension.


问:
Seaborn histogram/displot subplots
I have a dataframe, df, which has different rates for multiple 'N' currencies over a time period.

```<code>date         pair       rate
2019-05-01   AUD/USD   -0.004
2019-05-01   GBP/USD    0.05
2019-05-01   USD/NOK    0.0002
...
2020-01-01   AUD/USD   -0.025
2020-01-01   GBP/USD    0.021315
2020-01-01   USD/NOK    0.0045
</code>```

I would like to do a loop to plot N histograms (one per pair) using Seaborn sns; adding a title name that states the pair name on each plot.

I 'can achieve the plots using a simple groupby:

```<code>df.groupby('pair').hist(bins=20, normed=True)
plt.show()
</code>```

However, this doesn't give me the individual titles and I would like to add more features to the plot.

答:
Iterate on your df selecting the slices for each unique value, make a distplot for each slice.</p>

```<code>for pair in df.pair.unique():
    sns.distplot(df.loc[df.pair == pair,'rate'])
    plt.title(pair)

</code>```

Title: Seaborn histogram/displot subplots

Body:
I have a dataframe, df, which has different rates for multiple 'N' currencies over a time period.

date         pair       rate
2019-05-01   AUD/USD   -0.004
2019-05-01   GBP/USD    0.05
2019-05-01   USD/NOK    0.0002
...
2020-01-01   AUD/USD   -0.025
2020-01-01   GBP/USD    0.021315
2020-01-01   USD/NOK    0.0045

I would like to do a loop to plot N histograms (one per pair) using Seaborn sns; adding a title name that states the pair name on each plot.

I 'can achieve the plots using a simple groupby:

df.groupby('pair').hist(bins=20, normed=True)
plt.show()

However, this doesn't give me the individual titles and I would like to add more features to the plot.

Body:
Iterate on your df selecting the slices for each unique value, make a distplot for each slice.

for pair in df.pair.unique():
    sns.distplot(df.loc[df.pair == pair,'rate'])
    plt.title(pair)


问:
Executing F# scripts
I'm trying to practice my F# by writing small console scripts in F# in place of my usual method of writing shell scripts/batch files. I currently run them using "fsi script.fsx [args]". Is there a way I can associate these fsx files with fsi so that I can run them directly like "script.fsx [args]"?</p>

答:
Searching for "executing F# scripts on ubuntu" makes you land here.

To execute .fsx scripts with Mac/Linux, write fsharpi yourScript.fsx, for windows users write: fsi yourScript.fsx

ContentLicense: CC BY-SA 2.5

Title: Executing F# scripts


问:
Change color of a background on click to a multiple choice of color us with jquery
I am trying to add multiple color choices? How can I do it with HTML and CSS?
i dont know how to correctly add multiple color choice
here are my codes

$(document).ready(function() {
      $('#btn').click(function() {
        $('body').css('background', '#ff0000', '#80ff33');
      });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: ;
  background: #D8D8D8;
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

#btn {
  margin-left: 550px;
  width: 200px;
  height: 100px;
  font-size: 2em;
  border-radius: 10px;
  background: #ffffff;
}

#btn:hover {
  background: #ff0000;
  background: #80ff33;
  color: #ffffff;
}</code>```

  CLICK THE BUTTON TO
 CHANGE THE BACKGROUND!

<button id="btn">CLICK ME!</button>```

答:
$(document).ready(function() {
      $('#btn').click(function() {
        $('body').css('background', '#ff0000', '#80ff33');
      });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  height: ;
  background: #D8D8D8;
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

#btn {
  margin-left: 550px;
  width: 200px;
  height: 100px;
  font-size: 2em;
  border-radius: 10px;
  background: #ffffff;
}

#btn:hover {
  background: #ff0000;
  background: #80ff33;
  color: #ffffff;
}</code>```

  CLICK THE BUTTON TO
 CHANGE THE BACKGROUND!

<button id="btn">CLICK ME!</button>```

Body:
I am trying to add multiple color choices? How can I do it with HTML and CSS?
i dont know how to correctly add multiple color choice
here are my codes

$(document).ready(function() {
      $('#btn').click(function() {
        $('body').css('background', '#ff0000', '#80ff33');
      });

body {
  height: ;
  background: #D8D8D8;
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

#btn {
  margin-left: 550px;
  width: 200px;
  height: 100px;
  font-size: 2em;
  border-radius: 10px;
  background: #ffffff;
}

#btn:hover {
  background: #ff0000;
  background: #80ff33;
  color: #ffffff;
}

  CLICK THE BUTTON TO
 CHANGE THE BACKGROUND!

<button id="btn">CLICK ME!</button>

Body:
$(document).ready(function() {
      $('#btn').click(function() {
        $('body').css('background', '#ff0000', '#80ff33');
      });
});

body {
  height: ;
  background: #D8D8D8;
}

.text {
  color: #686868;
  font-family: arial;
  font-size: 2em;
  text-align: center;
  margin-top: 50px;
  margin-bottom: 20px;
}

#btn {
  margin-left: 550px;
  width: 200px;
  height: 100px;
  font-size: 2em;
  border-radius: 10px;
  background: #ffffff;
}

#btn:hover {
  background: #ff0000;
  background: #80ff33;
  color: #ffffff;
}

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section class="text">
  CLICK THE BUTTON TO<br> CHANGE THE BACKGROUND!
</section>
<button id="btn">CLICK ME!</button>


问:
Using React components inside KnockoutJS
We have a big web application mostly built using KnockoutJS. I'm looking at if there is a possibility to migrate to React, but in a way that require rewriting the entire application. My idea was to use a bottom-up approach: start by replacing the basic building blocks one by one.

I was inspired by some prior work to call ReactDOM.render inside a KnockoutJS binding handler:

```<code>ko.bindingHandlers.react = {
    init() {
        return {controlsDescendantBindings: true};
    },
    update(element, valueAccessor) {
        const {component, props} = valueAccessor();
        ReactDOM.render(React.createElement(component, props), element);
    }
};
</code>```

Knockout has its own dependency tracking system, so it will call the update method whenever some data changes.

It works perfectly, and the component is re-rendered to reflect any changes to data. However, it breaks down when data is updated inside a React event handler. E.g., this component does not work as expected:

```<code>const Input = function ({value}) {
    return <input type="text"
                  value={value()}
                  onChange={e => value(e.target.value)}/>;
}
</code>```

Note: value in this case is a ko.observable, and calling it like in the event handler will cause the bindingHandler's update method to be called, which in turn calls ReactDOM.render. However, this render only works once, after that the component stops updating.

The issue is demonstrated in this CodePen. Click the box and try to type something. One update goes through, after than, the component's function stops being called.

Edit: I believe the issue is that the second call to ReactDOM.render (when the value is updated by the user in the onChange handler) is not synchronous. This means that Knockout's dependency detection cannot work and any subsequent calls no longer call the update method of the binding handler.

Can this be circumvented somehow?

答:
For me worked:

```<code> update(element, valueAccessor) {
    const {component, props} = valueAccessor();
    props.value(props.value());
    ReactDOM.render(React.createElement(component, props), element);
}
</code>```

if you refresh your observable it will work but unfortunetaly i don't know how.

Body:
We have a big web application mostly built using KnockoutJS. I'm looking at if there is a possibility to migrate to React, but in a way that require rewriting the entire application. My idea was to use a bottom-up approach: start by replacing the basic building blocks one by one.

I was inspired by some prior work to call ReactDOM.render inside a KnockoutJS binding handler:

ko.bindingHandlers.react = {
    init() {
        return {controlsDescendantBindings: true};
    },
    update(element, valueAccessor) {
        const {component, props} = valueAccessor();
        ReactDOM.render(React.createElement(component, props), element);
    }
};

Knockout has its own dependency tracking system, so it will call the update method whenever some data changes.

It works perfectly, and the component is re-rendered to reflect any changes to data. However, it breaks down when data is updated inside a React event handler. E.g., this component does not work as expected:

const Input = function ({value}) {
    return <input type="text"
                  value={value()}
                  onChange={e => value(e.target.value)}/>;
}

Note: value in this case is a ko.observable, and calling it like in the event handler will cause the bindingHandler's update method to be called, which in turn calls ReactDOM.render. However, this render only works once, after that the component stops updating.

The issue is demonstrated in this CodePen. Click the box and try to type something. One update goes through, after than, the component's function stops being called.

Edit: I believe the issue is that the second call to ReactDOM.render (when the value is updated by the user in the onChange handler) is not synchronous. This means that Knockout's dependency detection cannot work and any subsequent calls no longer call the update method of the binding handler.

Can this be circumvented somehow?

Body:
For me worked:

 update(element, valueAccessor) {
    const {component, props} = valueAccessor();
    props.value(props.value());
    ReactDOM.render(React.createElement(component, props), element);
}

if you refresh your observable it will work but unfortunetaly i don't know how.


问:
Unlock account present in genesis.json for sending ether
I want to sent ether from first account to another.
For this i need to unlock the account.
For unlocking the account i need password, which i don't know.

https://github.com/Capgemini-AIE/ethereum-docker/tree/master/files
http://www.herongyang.com/Ethereum/Transfer-Fund-Send-Ether-from-One-Account-to-Another.html

答:
You can recover a wallet by providing:

The private key

The mnementics

If you don't have access to these informations then you can't do your operation


问:
How can I run a PowerShell script with white spaces in the path from the command line?
So I've tried a bunch of different ways to run a PowerShell script from the command line and every single one returns an error.

Here is this path:

C:\Users\test\Documents\test\line space\PS Script\test.ps1
```
<p>I've tried these:</p>
<pre class="lang-none prettyprint-override"><code>powershell -File '"C:\Users\test\Documents\test\line space\PS Script\test.ps1"'

powershell "& ""C:\Users\test\Documents\test\line space\PS Script\test.ps1"""

Powershell "& 'C:\Users\test\Documents\test\line space\PS Script\test.ps1'"

Powershell -File 'C:\Users\test\Documents\test\line space\PS Script\test.ps1'"
</code>```

I get all these errors:

& : The term 'C:\Users\test\Documents\test\line space\PS Script' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Processing -File ''C:\Users\test\Documents\test\line space\PS Script'' failed: The given path's format is not support ed. Specify a valid path for the -File parameter.

How can I fix this?

答:
In case you use parameters you can do as follows.

```<code>powershell.exe -command "& {&'C:\A B C\foo.ps1' param1 param2}"
</code>```

Thanks at this point to a blog post by Hesham A. Amin :-)

Body:
So I've tried a bunch of different ways to run a PowerShell script from the command line and every single one returns an error.

Here is this path:

C:\Users\test\Documents\test\line space\PS Script\test.ps1

I've tried these:

powershell -File '"C:\Users\test\Documents\test\line space\PS Script\test.ps1"'

powershell "& ""C:\Users\test\Documents\test\line space\PS Script\test.ps1"""

Powershell "& 'C:\Users\test\Documents\test\line space\PS Script\test.ps1'"

Powershell -File 'C:\Users\test\Documents\test\line space\PS Script\test.ps1'"

I get all these errors:

& : The term 'C:\Users\test\Documents\test\line space\PS Script' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Processing -File ''C:\Users\test\Documents\test\line space\PS Script'' failed: The given path's format is not support ed. Specify a valid path for the -File parameter.

How can I fix this?

Body:
In case you use parameters you can do as follows.

powershell.exe -command "& {&'C:\A B C\foo.ps1' param1 param2}"

Thanks at this point to a blog post by Hesham A. Amin :-)


问:
How to set an alarm to be scheduled at an exact time after all the newest restrictions on Android?
Note: I tried various solutions that are written about here on StackOverflow (example here). Please do not close this without checking if your solution from what you've found works using the test I've written below.

Background

There is a requirement on the app, that the user sets a reminder to be scheduled at a specific time, so when the app gets triggered on this time, it does something tiny in the background (just some DB query operation), and shows a simple notification, to tell about the reminder.

In the past, I used a simple code to set something to be scheduled at a relatively specific time:

```<code>            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
            when {
                VERSION.SDK_INT >= VERSION_CODES.KITKAT -> alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
                else -> alarmManager.set(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
            }
</code>```

```<code>class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("AppLog", "AlarmReceiver onReceive")
        //do something in the real app
    }
}
</code>```

Usage:

```<code>            val timeToTrigger = System.currentTimeMillis() + java.util.concurrent.TimeUnit.MINUTES.toMillis(1)
            setAlarm(this, timeToTrigger, 1)
</code>```

The problem

I've now tested this code on emulators on new Android versions and on Pixel 4 with Android 10, and it doesn't seem to trigger, or maybe it triggers after a very long time since what I provide it. I'm well aware of the terrible behavior that some OEMs added to removing apps from the recent tasks, but this one is on both emulators and Pixel 4 device (stock).

I've read on the docs about setting an alarm, that it got restricted for apps so that it won't occur too often, but this doesn't explain how to set an alarm at a specific time, and it doesn't explain how come Google's Clock app succeeds doing it.

Not only that, but according to what I understand, it says the restrictions should be applied especially for low power state of the device, but in my case, I didn't have this state, on both the device and on the emulators. I've set the alarms to be triggered in about a minute from now.

Seeing that many alarm clock apps don't work anymore as they used to, I think there is something that is missing on the docs. Example of such apps is the popular Timely app that was bought by Google but never got new updates to handle the new restrictions, and now users want it back.. However, some popular apps do work fine, such as this one.

What I've tried

To test that indeed the alarm works, I perform these tests when trying to trigger the alarm in a minute from now, after installing the app for the first time, all while the device is connected to the PC (to see the logs) :

Test when the app is in the foreground, visible to the user. - took 1-2 minutes.

Test when the app was sent to the background (using the home button, for example) - took about 1 minute

Test when app's task was removed from the recent tasks. - I waited more than 20 minutes and didn't see the alarm being triggered, writing to logs.

Like #3, but also turn off the screen. It would probably be worse...

I tried to use the next things, all don't work:

alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)

alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

combination of any of the above, with :

if (VERSION.SDK_INT >= VERSION_CODES.KITKAT)
  alarmManager.setWindow(AlarmManager.RTC_WAKEUP, 0, 60 * 1000L, pendingIntent)

Tried to use a service instead of BroadcastReceiver. Also tried on a different process.

Tried making the app be ignored from the battery optimization (didn't help), but since other apps don't need it, I shouldn't use it either.

Tried using this:

```<code>            if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP)
                alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)
            AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
</code>```

Tried having a service that will have a trigger of onTaskRemoved , to re-schedule the alarm there, but this also didn't help (the service worked fine though).

As for Google's Clock app, I didn't see anything special about it except that it shows a notification before being triggered, and I also don't see it in the "not optimized" section of the battery-optimization settings screen.

Seeing that this seems like a bug, I reported about this here, including a sample project and video to show the issue.

I've checked on multiple versions of the emulator, and it seems that this behavior started from API 27 (Android 8.1 - Oreo). Looking at the docs, I don't see AlarmManager being mentioned, but instead, it was written about various background work.

The questions

How do we set something to be triggered at a relatively exact time nowadays?

How come the above solutions don't work anymore? Am I missing anything? Permission? Maybe I'm supposed to use a Worker instead? But then wouldn't it mean that it might not trigger on time at all?

How does Google "Clock" app overcome all of this, and triggers anyway on the exact time, always, even if it was triggered just a minute ago? Is it only because it's a system app? What if it gets installed as a user app, on a device that doesn't have it built-in?

If you say that it's because it's a system app, I've found another app that can trigger an alarm twice in 2 minutes, here, though I think it might use a foreground service sometimes.

EDIT: made a tiny Github repository to try ideas on, here.

EDIT: finally found a sample that is both open-sourced and doesn't have this issue. Sadly it's very complex and I still try to figure out what makes it so different (and what's the minimal code that I should add to my POC) that lets its alarms stay scheduled after removing the app from the recent tasks

答:
Found a weird workaround (sample here) that seems to work for all versions, including even Android R:

Have the permission SAW permission declared in the manifest:

```<code>      <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
</code>```

On Android R you will have to also have it granted. On before, doesn't seem like it's needed to be granted, just declared. Not sure why this changed on R, but I can say that SAW could be required as a possible solution to start things in the background, as written here for Android 10.

EDIT: Here is a guide on how to request it.

Have a service that will detect when the tasks was removed, and when it does, open a fake Activity that all it does is to close itself:

```<code>class OnTaskRemovedDetectorService : Service() {
    override fun onBind(intent: Intent?) = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int) = START_STICKY

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        Log.e("AppLog", "onTaskRemoved")
        applicationContext.startActivity(Intent(this, FakeActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        stopSelf()
    }

}
</code>```

FakeActivity.kt

```<code>class FakeActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("AppLog", "FakeActivity")
        finish()
    }
}
</code>```

You can also make this Activity almost invisible to the user using this theme:

```
<p>Sadly, this is a weird workaround. I hope to find a nicer workaround to this.</p>
<p>The restriction talks about starting Activity, so my current idea is that maybe if I start a foreground service for a split of a second it will also help, and for this I won't even need SAW permission.</p>
<p>EDIT: OK I tried with a foreground service (sample <strong>here</strong>), and it didn't work. No idea why an Activity is working but not a service. I even tried to re-schedule the alarm there and tried to let the service stay for a bit, even after re-schedule. Also tried a normal service but of course it closed right away, as the task was removed, and it didn't work at all (even if I created a thread to run in the background).</p>
<p>Another possible solution that I didn't try is to have a foreground service forever, or at least till the task is removed, but this is a bit weird and I don't see the apps I've mentioned using it.</p>
<p>EDIT: tried to have a foreground service running before removal of the app's task, and for a bit afterwards, and the alarm still worked. Also tried to have this service to be the one in charge of task-removed event, and to close itself right away when it occurs, and it still worked (sample <strong>here</strong>). The advantage of this workaround is that you don't have to have the SAW permission at all. The disadvantage is that you have a service with a notification while the app is already visible to the user. I wonder if it's possible to hide the notification while the app is already in the foreground via the Activity.</p>
<hr />
<p>EDIT: Seems it's a bug on Android Studio (reported here, including videos comparing versions).
When you launch the app from the problematic version I tried, it could cause the alarms to be cleared.</p>
<p>If you launch the app from the launcher, it works fine.</p>
<p>This is the current code to set the alarm:</p>
```        val timeToTrigger = System.currentTimeMillis() + 10 * 1000
        val pendingShowList = PendingIntent.getActivity(this, 1, Intent(this, SomeActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
        val pendingIntent = PendingIntent.getBroadcast(this, 1, Intent(this, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
        manager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingShowList), pendingIntent)
```

I don't even have to use "pendingShowList". Using null is also ok.

Body:
Note: I tried various solutions that are written about here on StackOverflow (example here). Please do not close this without checking if your solution from what you've found works using the test I've written below.

Background

There is a requirement on the app, that the user sets a reminder to be scheduled at a specific time, so when the app gets triggered on this time, it does something tiny in the background (just some DB query operation), and shows a simple notification, to tell about the reminder.

In the past, I used a simple code to set something to be scheduled at a relatively specific time:

            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val pendingIntent = PendingIntent.getBroadcast(context, requestId, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
            when {
                VERSION.SDK_INT >= VERSION_CODES.KITKAT -> alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
                else -> alarmManager.set(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)
            }

class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        Log.d("AppLog", "AlarmReceiver onReceive")
        //do something in the real app
    }
}

Usage:

            val timeToTrigger = System.currentTimeMillis() + java.util.concurrent.TimeUnit.MINUTES.toMillis(1)
            setAlarm(this, timeToTrigger, 1)

The problem

I've now tested this code on emulators on new Android versions and on Pixel 4 with Android 10, and it doesn't seem to trigger, or maybe it triggers after a very long time since what I provide it. I'm well aware of the terrible behavior that some OEMs added to removing apps from the recent tasks, but this one is on both emulators and Pixel 4 device (stock).

I've read on the docs about setting an alarm, that it got restricted for apps so that it won't occur too often, but this doesn't explain how to set an alarm at a specific time, and it doesn't explain how come Google's Clock app succeeds doing it.

Not only that, but according to what I understand, it says the restrictions should be applied especially for low power state of the device, but in my case, I didn't have this state, on both the device and on the emulators. I've set the alarms to be triggered in about a minute from now.

Seeing that many alarm clock apps don't work anymore as they used to, I think there is something that is missing on the docs. Example of such apps is the popular Timely app that was bought by Google but never got new updates to handle the new restrictions, and now users want it back.. However, some popular apps do work fine, such as this one.

What I've tried

To test that indeed the alarm works, I perform these tests when trying to trigger the alarm in a minute from now, after installing the app for the first time, all while the device is connected to the PC (to see the logs) :

Test when the app is in the foreground, visible to the user. - took 1-2 minutes.

Test when the app was sent to the background (using the home button, for example) - took about 1 minute

Test when app's task was removed from the recent tasks. - I waited more than 20 minutes and didn't see the alarm being triggered, writing to logs.

Like #3, but also turn off the screen. It would probably be worse...

I tried to use the next things, all don't work:

alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)

alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

combination of any of the above, with :

if (VERSION.SDK_INT >= VERSION_CODES.KITKAT)
  alarmManager.setWindow(AlarmManager.RTC_WAKEUP, 0, 60 * 1000L, pendingIntent)

Tried to use a service instead of BroadcastReceiver. Also tried on a different process.

Tried making the app be ignored from the battery optimization (didn't help), but since other apps don't need it, I shouldn't use it either.

Tried using this:

            if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP)
                alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingIntent), pendingIntent)
            AlarmManagerCompat.setExactAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, timeToTrigger, pendingIntent)

Tried having a service that will have a trigger of onTaskRemoved , to re-schedule the alarm there, but this also didn't help (the service worked fine though).

As for Google's Clock app, I didn't see anything special about it except that it shows a notification before being triggered, and I also don't see it in the "not optimized" section of the battery-optimization settings screen.

Seeing that this seems like a bug, I reported about this here, including a sample project and video to show the issue.

I've checked on multiple versions of the emulator, and it seems that this behavior started from API 27 (Android 8.1 - Oreo). Looking at the docs, I don't see AlarmManager being mentioned, but instead, it was written about various background work.

The questions

How do we set something to be triggered at a relatively exact time nowadays?

How come the above solutions don't work anymore? Am I missing anything? Permission? Maybe I'm supposed to use a Worker instead? But then wouldn't it mean that it might not trigger on time at all?

How does Google "Clock" app overcome all of this, and triggers anyway on the exact time, always, even if it was triggered just a minute ago? Is it only because it's a system app? What if it gets installed as a user app, on a device that doesn't have it built-in?

If you say that it's because it's a system app, I've found another app that can trigger an alarm twice in 2 minutes, here, though I think it might use a foreground service sometimes.

EDIT: made a tiny Github repository to try ideas on, here.

EDIT: finally found a sample that is both open-sourced and doesn't have this issue. Sadly it's very complex and I still try to figure out what makes it so different (and what's the minimal code that I should add to my POC) that lets its alarms stay scheduled after removing the app from the recent tasks

Body:
Found a weird workaround (sample here) that seems to work for all versions, including even Android R:

Have the permission SAW permission declared in the manifest:

      <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

On Android R you will have to also have it granted. On before, doesn't seem like it's needed to be granted, just declared. Not sure why this changed on R, but I can say that SAW could be required as a possible solution to start things in the background, as written here for Android 10.

EDIT: Here is a guide on how to request it.

Have a service that will detect when the tasks was removed, and when it does, open a fake Activity that all it does is to close itself:

class OnTaskRemovedDetectorService : Service() {
    override fun onBind(intent: Intent?) = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int) = START_STICKY

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        Log.e("AppLog", "onTaskRemoved")
        applicationContext.startActivity(Intent(this, FakeActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        stopSelf()
    }

}

FakeActivity.kt

class FakeActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("AppLog", "FakeActivity")
        finish()
    }
}

You can also make this Activity almost invisible to the user using this theme:

    <style name="AppTheme.Translucent" parent="@style/Theme.AppCompat.NoActionBar">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:colorBackgroundCacheHint">@null</item>
        <item name="android:windowIsTranslucent">true</item>
    </style>

Sadly, this is a weird workaround. I hope to find a nicer workaround to this.

The restriction talks about starting Activity, so my current idea is that maybe if I start a foreground service for a split of a second it will also help, and for this I won't even need SAW permission.

EDIT: OK I tried with a foreground service (sample here), and it didn't work. No idea why an Activity is working but not a service. I even tried to re-schedule the alarm there and tried to let the service stay for a bit, even after re-schedule. Also tried a normal service but of course it closed right away, as the task was removed, and it didn't work at all (even if I created a thread to run in the background).

Another possible solution that I didn't try is to have a foreground service forever, or at least till the task is removed, but this is a bit weird and I don't see the apps I've mentioned using it.

EDIT: tried to have a foreground service running before removal of the app's task, and for a bit afterwards, and the alarm still worked. Also tried to have this service to be the one in charge of task-removed event, and to close itself right away when it occurs, and it still worked (sample here). The advantage of this workaround is that you don't have to have the SAW permission at all. The disadvantage is that you have a service with a notification while the app is already visible to the user. I wonder if it's possible to hide the notification while the app is already in the foreground via the Activity.

EDIT: Seems it's a bug on Android Studio (reported here, including videos comparing versions).
When you launch the app from the problematic version I tried, it could cause the alarms to be cleared.

If you launch the app from the launcher, it works fine.

This is the current code to set the alarm:

        val timeToTrigger = System.currentTimeMillis() + 10 * 1000
        val pendingShowList = PendingIntent.getActivity(this, 1, Intent(this, SomeActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
        val pendingIntent = PendingIntent.getBroadcast(this, 1, Intent(this, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
        manager.setAlarmClock(AlarmManager.AlarmClockInfo(timeToTrigger, pendingShowList), pendingIntent)

I don't even have to use "pendingShowList". Using null is also ok.


问:
Error while Indtalling EFCodeFirst
I am developing ASP.NET MVC 3 music store site from the tutorial, Page 45.

When I am trying to install the EFCodeFirst I am getting the below error
Please help

答:
Update NuGet

from menu: Tools > Extension Manager

select update section from left menu

Title: Error while Indtalling EFCodeFirst


问:
Keep Business Process Display State as collapsed
I am trying to keep the business process flow display state as collapsed.

I am currently making it collapsed at addOnStageChange

```<code>Xrm.Page.ui.process.setDisplayState('collapsed');
</code>```

It works fine on Stage Change for me. But if I click on the same stage twice which means stage is not changing then the BPF gets expanded. I am assuming if it is the default behavior.

How can I prevent it from expanding permanently?

答:
BPF cannot be collapsed always in classic UI, but possible in UCI like popout behavior or flyout without expanding. It needs some unsupported DOM manipulation in classic UI to nullify the click event of stage chevron or simply user training not to click it at all. Or better create a similar UI using webresource if you want.

It fails the original purpose, and re-purposing the BPF raise these kind of questions. If you have built the necessary business logic already in some other means - then custom UI is better choice rather than bending the BPF.

BPF is for guided process advancement, we can add attributes/entities as steps to move forward and enforce the field value requirements for reaching next level. I know some clients use them as tabs, some use them as just chevron tracker, so they don't want to waste the real estate under the BPF as they don't need any fields under the stages.

Body:
I am trying to keep the business process flow display state as collapsed.

I am currently making it collapsed at addOnStageChange

Xrm.Page.ui.process.setDisplayState('collapsed');

It works fine on Stage Change for me. But if I click on the same stage twice which means stage is not changing then the BPF gets expanded. I am assuming if it is the default behavior.

How can I prevent it from expanding permanently?


问:
show data row in specified number position
I have coding like this, showing data list, I want to show ads at row 3 and 6, please help me to resolve this query.</p>

```<code>for ($i = 0; $i <= count($random_id_ad) - 1; $i++)
   test
   if row(position is 3 and 6)
       ads
   }
}
</code>```

答:
$i represents the current row in your code, so just change the if statement to this

```<code>if($i == 3 || $i == 6) {
    echo 'INSERT ADD CONTENT HERE';
}
</code>```

Loops

Body:
I have coding like this, showing data list, I want to show ads at row 3 and 6, please help me to resolve this query.

for ($i = 0; $i <= count($random_id_ad) - 1; $i++)
   test
   if row(position is 3 and 6)
       ads
   }
}

Body:
$i represents the current row in your code, so just change the if statement to this

if($i == 3 || $i == 6) {
    echo 'INSERT ADD CONTENT HERE';
}

Loops


问:
Is there a way to get the complete console output on xcode through code?
I need to read the entire console output so i'd like to implement a functionality which will send everything that was printed out to my email or something like that.

Is it possible?

I do realize that I could just use a different function for logging print statements etc but i need the outputs from the 3rd party libs as well.

答:
You can write the log to a file and then email it. I put the snippet here. Just one question, why would you want to retrieve the log by mail?

Objective-c

```<code> NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [allPaths objectAtIndex:0];
 NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"logfile.log"];

 freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
</code>```

Swift

```<code>let allPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = allPaths.first!
let pathForLog = documentsDirectory.stringByAppendingString("/logfile.log")

freopen(pathForLog.cStringUsingEncoding(NSASCIIStringEncoding)!, "a+", stderr)
</code>```

Body:
You can write the log to a file and then email it. I put the snippet here. Just one question, why would you want to retrieve the log by mail?

Objective-c

 NSArray *allPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [allPaths objectAtIndex:0];
 NSString *pathForLog = [documentsDirectory stringByAppendingPathComponent:@"logfile.log"];

 freopen([pathForLog cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);

Swift

let allPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = allPaths.first!
let pathForLog = documentsDirectory.stringByAppendingString("/logfile.log")

freopen(pathForLog.cStringUsingEncoding(NSASCIIStringEncoding)!, "a+", stderr)


问:
Concatenate values returned from an array in Swift
I'm training on Swift, doing some exercises with arrays. I would like to pick up randomly 6 letters in an array containing the 26 letters of the alphabet, then concatenate them to generate a string.

I have no problem picking the values, but when it comes to concatenate them, I get error messages.

Here is my code :

```<code>var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

var a = alphabet.randomElement()
var b = alphabet.randomElement()
var c = alphabet.randomElement()
var d = alphabet.randomElement()
var e = alphabet.randomElement()
var f = alphabet.randomElement()

var password = a + b + c + d + e + f

print(password)
</code>```

What am I doing wrong ?

答:
Actually I think the simplest solution is to declare an extension at the top level of your file, allowing you to concatenate Optional Strings coherently:

```<code>func +(lhs:String?, rhs:String?) -> String {
    return (lhs ?? "") + (rhs ?? "")
}
</code>```

Now your original code will compile and run correctly without changes (except that I changed var to let everywhere to eliminate compiler warnings):

```<code>let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

let a = alphabet.randomElement()
let b = alphabet.randomElement()
let c = alphabet.randomElement()
let d = alphabet.randomElement()
let e = alphabet.randomElement()
let f = alphabet.randomElement()

let password = a + b + c + d + e + f

print(password) // cpndmz
</code>```

Body:
I'm training on Swift, doing some exercises with arrays. I would like to pick up randomly 6 letters in an array containing the 26 letters of the alphabet, then concatenate them to generate a string.

I have no problem picking the values, but when it comes to concatenate them, I get error messages.

Here is my code :

var alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

var a = alphabet.randomElement()
var b = alphabet.randomElement()
var c = alphabet.randomElement()
var d = alphabet.randomElement()
var e = alphabet.randomElement()
var f = alphabet.randomElement()

var password = a + b + c + d + e + f

print(password)

What am I doing wrong ?

Body:
Actually I think the simplest solution is to declare an extension at the top level of your file, allowing you to concatenate Optional Strings coherently:

func +(lhs:String?, rhs:String?) -> String {
    return (lhs ?? "") + (rhs ?? "")
}

Now your original code will compile and run correctly without changes (except that I changed var to let everywhere to eliminate compiler warnings):

let alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

let a = alphabet.randomElement()
let b = alphabet.randomElement()
let c = alphabet.randomElement()
let d = alphabet.randomElement()
let e = alphabet.randomElement()
let f = alphabet.randomElement()

let password = a + b + c + d + e + f

print(password) // cpndmz


问:
C# JSON deserialization trying to deserialize into an array of KeyValuePairs when i pass a JSON object to it
I have got an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,Tessa.Extensions.Shared.Acquiring.AcqFieldData]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

when i pass a JSON array string (settings) to the JsonConvert.DeserializeObject<Dictionary<String, AcqFieldData>>(settings)

and the other error:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.KeyValuePair`2[System.String,Tessa.Extensions.Shared.Acquiring.AcqFieldRef][]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

when i pass a JSON object string as an input. Here is my two inputs, array:

```<code>[
  {
    "eca31ead-e905-43af-b92d-d5c01eccb590": {
      "Fields": {
        "EquipmentManufacturerName": {
          "CardID": "3ae9344f-00f7-4760-a790-4b5375807791",
          "Section": "AcqEquipmentManufacturerCards",
          "Field": "Name",
          "Value": "ref"
        },
        "EquipmentManufacturerID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "3ae9344f-00f7-4760-a790-4b5375807791"
        },
        "IsClientEquipment": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "ServiceCatID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "ServiceCatName": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        }
      },
      "ReadonlyControlAliases": null
    }
  },
  {
    "67830499-876a-4e2c-a08d-fd6100349b99": {
      "Fields": {
        "ClassBName": {
          "CardID": "0fb18fa1-8560-4364-9a16-03815f5e9303",
          "Section": "AcqClassBCards",
          "Field": "Name",
          "Value": "ref"
        },
        "ClassBID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "0fb18fa1-8560-4364-9a16-03815f5e9303"
        },
        "TerminalTypeName": {
          "CardID": "7c081fbf-13e6-4949-a634-85d7a99ebe01",
          "Section": "AcqTerminalTypeCards",
          "Field": "Name",
          "Value": "ref"
        },
        "TerminalTypeID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "7c081fbf-13e6-4949-a634-85d7a99ebe01"
        },
        "EquipmentManufacturerName": {
          "CardID": "3ae9344f-00f7-4760-a790-4b5375807791",
          "Section": "AcqEquipmentManufacturerCards",
          "Field": "Name",
          "Value": "ref"
        },
        "EquipmentManufacturerID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "3ae9344f-00f7-4760-a790-4b5375807791"
        },
        "FloorLimitSum": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "FloorLimit": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "CreditVaucherSum": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "CreditVaucher": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "MotoSof": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "Preauthorization": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "IsClientEquipment": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": true
        },
        "ServiceCatID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "ServiceCatName": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        }
      },
      "ReadonlyControlAliases": [
        "ClassB",
        "TerminalType",
        "EquipmentManufacturer",
        "FloorLimitSum",
        "FloorLimit",
        "CreditVaucherSum",
        "CreditVaucher",
        "MotoSof",
        "Preauthorization",
        "IsClientEquipment"
      ]
    }
  },
  {
    "9560cc34-822e-430a-9a42-0eccb6d052f2": {
      "Fields": {
        "EquipmentTemplate": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "GPRS"
        },
        "TerminalTypeName": {
          "CardID": "7c081fbf-13e6-4949-a634-85d7a99ebe01",
          "Section": "AcqTerminalTypeCards",
          "Field": "Name",
          "Value": "ref"
        },
        "TerminalTypeID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "7c081fbf-13e6-4949-a634-85d7a99ebe01"
        },
        "IsClientEquipment": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "ServiceCatID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "ServiceCatName": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        }
      },
      "ReadonlyControlAliases": [
        "EquipmentTemplate",
        "TerminalType",
        "IsClientEquipment"
      ]
    }
  }
]
</code>```

and object:

```<code>{
  "eca31ead-e905-43af-b92d-d5c01eccb590": {
    "Fields": {
      "EquipmentManufacturerName": {
        "CardID": "3ae9344f-00f7-4760-a790-4b5375807791",
        "Section": "AcqEquipmentManufacturerCards",
        "Field": "Name",
        "Value": "ref"
      },
      "EquipmentManufacturerID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "3ae9344f-00f7-4760-a790-4b5375807791"
      },
      "IsClientEquipment": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "ServiceCatID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "ServiceCatName": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      }
    },
    "ReadonlyControlAliases": null
  },
  "67830499-876a-4e2c-a08d-fd6100349b99": {
    "Fields": {
      "ClassBName": {
        "CardID": "0fb18fa1-8560-4364-9a16-03815f5e9303",
        "Section": "AcqClassBCards",
        "Field": "Name",
        "Value": "ref"
      },
      "ClassBID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "0fb18fa1-8560-4364-9a16-03815f5e9303"
      },
      "TerminalTypeName": {
        "CardID": "7c081fbf-13e6-4949-a634-85d7a99ebe01",
        "Section": "AcqTerminalTypeCards",
        "Field": "Name",
        "Value": "ref"
      },
      "TerminalTypeID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "7c081fbf-13e6-4949-a634-85d7a99ebe01"
      },
      "EquipmentManufacturerName": {
        "CardID": "3ae9344f-00f7-4760-a790-4b5375807791",
        "Section": "AcqEquipmentManufacturerCards",
        "Field": "Name",
        "Value": "ref"
      },
      "EquipmentManufacturerID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "3ae9344f-00f7-4760-a790-4b5375807791"
      },
      "FloorLimitSum": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "FloorLimit": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "CreditVaucherSum": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "CreditVaucher": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "MotoSof": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "Preauthorization": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "IsClientEquipment": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": true
      },
      "ServiceCatID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "ServiceCatName": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      }
    },
    "ReadonlyControlAliases": [
      "ClassB",
      "TerminalType",
      "EquipmentManufacturer",
      "FloorLimitSum",
      "FloorLimit",
      "CreditVaucherSum",
      "CreditVaucher",
      "MotoSof",
      "Preauthorization",
      "IsClientEquipment"
    ]
  },
  "9560cc34-822e-430a-9a42-0eccb6d052f2": {
    "Fields": {
      "EquipmentTemplate": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "GPRS"
      },
      "TerminalTypeName": {
        "CardID": "7c081fbf-13e6-4949-a634-85d7a99ebe01",
        "Section": "AcqTerminalTypeCards",
        "Field": "Name",
        "Value": "ref"
      },
      "TerminalTypeID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "7c081fbf-13e6-4949-a634-85d7a99ebe01"
      },
      "IsClientEquipment": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "ServiceCatID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "ServiceCatName": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      }
    },
    "ReadonlyControlAliases": [
      "EquipmentTemplate",
      "TerminalType",
      "IsClientEquipment"
    ]
  }
}
</code>```

Here is my classes. AcqFieldData:

```<code>public class AcqFieldData
    {
        public readonly IDictionary<string, AcqFieldRef> Fields;
        public readonly IEnumerable<string> ReadonlyControlAliases;

        public AcqFieldData(
            IEnumerable<string> readonlyControlAliases,
            params KeyValuePair<string, AcqFieldRef>[] fields)
        {
            this.ReadonlyControlAliases = readonlyControlAliases;

            this.Fields = new Dictionary<string, AcqFieldRef>();

            foreach (var pair in fields)
            {
                if (pair.Key != null)
                    this.Fields.Add(pair);
            }
        }
    }
</code>```

and AcqFieldRef:

```<code>public class AcqFieldRef
    {
        public readonly Guid? CardID;
        public readonly string Section;
        public readonly string Field;
        public readonly Object Value;

        public AcqFieldRef(Guid cardID, string section, string field)
        {
            this.CardID = cardID;
            this.Section = section;
            this.Field = field;
            this.Value = "ref";
        }

        public AcqFieldRef(Object value)
        {
            if (value as String == "ref")
            {
                throw new ArgumentException(
                    "Value \"ref\" is reserved for a link description");
            }

            this.Value = value;
        }

        [UsedImplicitly]
        public AcqFieldRef()
        {

        }
    }
</code>```

答:
First json you have is not a Dictionary<string, object> but a List<Dictionary<string, object>>.

I used dynamic to answer your question since there was no definition of the class, AcqFieldData in your question.

```<code>var value = JsonConvert.DeserializeObject<List<Dictionary<string, dynamic>>>(json);
</code>```

and your Second json is Dictionary<string, object>.

```<code>var value = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);
</code>```

This code works with dynamic object but not AcqFieldData. Your constructors seems to have some issues when trying to create / add objects and inserting them to your Dictionary. When I tested your code, it throws error in foreach (var pair in fields) when fields is null.

I would suggest trying out classes with getter and setter and go from there.

```<code>public class AcqFieldData
{
    public Dictionary<string, AcqFieldRef> Fields { get; set; }
    public List<string> ReadonlyControlAliases { get; set; }
}

public class AcqFieldRef
{
    public Guid? CardID { get; set; }
    public string Section { get; set; }
    public string Field { get; set; }
    public Object Value { get; set; }
}

// Use this in the main for 1st json
var jObject = JsonConvert.DeserializeObject<List<Dictionary<string, AcqFieldData>>>(json);

// Use this in the main for 2nd json
var jObject = JsonConvert.DeserializeObject<Dictionary<string, AcqFieldData>>(json);
</code>```

Body:
I have got an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,Tessa.Extensions.Shared.Acquiring.AcqFieldData]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

when i pass a JSON array string (settings) to the JsonConvert.DeserializeObject<Dictionary<String, AcqFieldData>>(settings)

and the other error:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.KeyValuePair`2[System.String,Tessa.Extensions.Shared.Acquiring.AcqFieldRef][]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

when i pass a JSON object string as an input. Here is my two inputs, array:

[
  {
    "eca31ead-e905-43af-b92d-d5c01eccb590": {
      "Fields": {
        "EquipmentManufacturerName": {
          "CardID": "3ae9344f-00f7-4760-a790-4b5375807791",
          "Section": "AcqEquipmentManufacturerCards",
          "Field": "Name",
          "Value": "ref"
        },
        "EquipmentManufacturerID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "3ae9344f-00f7-4760-a790-4b5375807791"
        },
        "IsClientEquipment": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "ServiceCatID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "ServiceCatName": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        }
      },
      "ReadonlyControlAliases": null
    }
  },
  {
    "67830499-876a-4e2c-a08d-fd6100349b99": {
      "Fields": {
        "ClassBName": {
          "CardID": "0fb18fa1-8560-4364-9a16-03815f5e9303",
          "Section": "AcqClassBCards",
          "Field": "Name",
          "Value": "ref"
        },
        "ClassBID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "0fb18fa1-8560-4364-9a16-03815f5e9303"
        },
        "TerminalTypeName": {
          "CardID": "7c081fbf-13e6-4949-a634-85d7a99ebe01",
          "Section": "AcqTerminalTypeCards",
          "Field": "Name",
          "Value": "ref"
        },
        "TerminalTypeID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "7c081fbf-13e6-4949-a634-85d7a99ebe01"
        },
        "EquipmentManufacturerName": {
          "CardID": "3ae9344f-00f7-4760-a790-4b5375807791",
          "Section": "AcqEquipmentManufacturerCards",
          "Field": "Name",
          "Value": "ref"
        },
        "EquipmentManufacturerID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "3ae9344f-00f7-4760-a790-4b5375807791"
        },
        "FloorLimitSum": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "FloorLimit": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "CreditVaucherSum": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "CreditVaucher": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "MotoSof": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "Preauthorization": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "IsClientEquipment": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": true
        },
        "ServiceCatID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "ServiceCatName": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        }
      },
      "ReadonlyControlAliases": [
        "ClassB",
        "TerminalType",
        "EquipmentManufacturer",
        "FloorLimitSum",
        "FloorLimit",
        "CreditVaucherSum",
        "CreditVaucher",
        "MotoSof",
        "Preauthorization",
        "IsClientEquipment"
      ]
    }
  },
  {
    "9560cc34-822e-430a-9a42-0eccb6d052f2": {
      "Fields": {
        "EquipmentTemplate": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "GPRS"
        },
        "TerminalTypeName": {
          "CardID": "7c081fbf-13e6-4949-a634-85d7a99ebe01",
          "Section": "AcqTerminalTypeCards",
          "Field": "Name",
          "Value": "ref"
        },
        "TerminalTypeID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": "7c081fbf-13e6-4949-a634-85d7a99ebe01"
        },
        "IsClientEquipment": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": false
        },
        "ServiceCatID": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        },
        "ServiceCatName": {
          "CardID": null,
          "Section": null,
          "Field": null,
          "Value": null
        }
      },
      "ReadonlyControlAliases": [
        "EquipmentTemplate",
        "TerminalType",
        "IsClientEquipment"
      ]
    }
  }
]

and object:

{
  "eca31ead-e905-43af-b92d-d5c01eccb590": {
    "Fields": {
      "EquipmentManufacturerName": {
        "CardID": "3ae9344f-00f7-4760-a790-4b5375807791",
        "Section": "AcqEquipmentManufacturerCards",
        "Field": "Name",
        "Value": "ref"
      },
      "EquipmentManufacturerID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "3ae9344f-00f7-4760-a790-4b5375807791"
      },
      "IsClientEquipment": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "ServiceCatID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "ServiceCatName": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      }
    },
    "ReadonlyControlAliases": null
  },
  "67830499-876a-4e2c-a08d-fd6100349b99": {
    "Fields": {
      "ClassBName": {
        "CardID": "0fb18fa1-8560-4364-9a16-03815f5e9303",
        "Section": "AcqClassBCards",
        "Field": "Name",
        "Value": "ref"
      },
      "ClassBID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "0fb18fa1-8560-4364-9a16-03815f5e9303"
      },
      "TerminalTypeName": {
        "CardID": "7c081fbf-13e6-4949-a634-85d7a99ebe01",
        "Section": "AcqTerminalTypeCards",
        "Field": "Name",
        "Value": "ref"
      },
      "TerminalTypeID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "7c081fbf-13e6-4949-a634-85d7a99ebe01"
      },
      "EquipmentManufacturerName": {
        "CardID": "3ae9344f-00f7-4760-a790-4b5375807791",
        "Section": "AcqEquipmentManufacturerCards",
        "Field": "Name",
        "Value": "ref"
      },
      "EquipmentManufacturerID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "3ae9344f-00f7-4760-a790-4b5375807791"
      },
      "FloorLimitSum": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "FloorLimit": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "CreditVaucherSum": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "CreditVaucher": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "MotoSof": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "Preauthorization": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "IsClientEquipment": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": true
      },
      "ServiceCatID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "ServiceCatName": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      }
    },
    "ReadonlyControlAliases": [
      "ClassB",
      "TerminalType",
      "EquipmentManufacturer",
      "FloorLimitSum",
      "FloorLimit",
      "CreditVaucherSum",
      "CreditVaucher",
      "MotoSof",
      "Preauthorization",
      "IsClientEquipment"
    ]
  },
  "9560cc34-822e-430a-9a42-0eccb6d052f2": {
    "Fields": {
      "EquipmentTemplate": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "GPRS"
      },
      "TerminalTypeName": {
        "CardID": "7c081fbf-13e6-4949-a634-85d7a99ebe01",
        "Section": "AcqTerminalTypeCards",
        "Field": "Name",
        "Value": "ref"
      },
      "TerminalTypeID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": "7c081fbf-13e6-4949-a634-85d7a99ebe01"
      },
      "IsClientEquipment": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": false
      },
      "ServiceCatID": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      },
      "ServiceCatName": {
        "CardID": null,
        "Section": null,
        "Field": null,
        "Value": null
      }
    },
    "ReadonlyControlAliases": [
      "EquipmentTemplate",
      "TerminalType",
      "IsClientEquipment"
    ]
  }
}

Here is my classes. AcqFieldData:

public class AcqFieldData
    {
        public readonly IDictionary<string, AcqFieldRef> Fields;
        public readonly IEnumerable<string> ReadonlyControlAliases;

        public AcqFieldData(
            IEnumerable<string> readonlyControlAliases,
            params KeyValuePair<string, AcqFieldRef>[] fields)
        {
            this.ReadonlyControlAliases = readonlyControlAliases;

            this.Fields = new Dictionary<string, AcqFieldRef>();

            foreach (var pair in fields)
            {
                if (pair.Key != null)
                    this.Fields.Add(pair);
            }
        }
    }

and AcqFieldRef:

public class AcqFieldRef
    {
        public readonly Guid? CardID;
        public readonly string Section;
        public readonly string Field;
        public readonly Object Value;

        public AcqFieldRef(Guid cardID, string section, string field)
        {
            this.CardID = cardID;
            this.Section = section;
            this.Field = field;
            this.Value = "ref";
        }

        public AcqFieldRef(Object value)
        {
            if (value as String == "ref")
            {
                throw new ArgumentException(
                    "Value \"ref\" is reserved for a link description");
            }

            this.Value = value;
        }

        [UsedImplicitly]
        public AcqFieldRef()
        {

        }
    }

Body:
First json you have is not a Dictionary<string, object> but a List<Dictionary<string, object>>.

I used dynamic to answer your question since there was no definition of the class, AcqFieldData in your question.

var value = JsonConvert.DeserializeObject<List<Dictionary<string, dynamic>>>(json);

and your Second json is Dictionary<string, object>.

var value = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);

This code works with dynamic object but not AcqFieldData. Your constructors seems to have some issues when trying to create / add objects and inserting them to your Dictionary. When I tested your code, it throws error in foreach (var pair in fields) when fields is null.

I would suggest trying out classes with getter and setter and go from there.

public class AcqFieldData
{
    public Dictionary<string, AcqFieldRef> Fields { get; set; }
    public List<string> ReadonlyControlAliases { get; set; }
}

public class AcqFieldRef
{
    public Guid? CardID { get; set; }
    public string Section { get; set; }
    public string Field { get; set; }
    public Object Value { get; set; }
}

// Use this in the main for 1st json
var jObject = JsonConvert.DeserializeObject<List<Dictionary<string, AcqFieldData>>>(json);

// Use this in the main for 2nd json
var jObject = JsonConvert.DeserializeObject<Dictionary<string, AcqFieldData>>(json);