问:
SPARQL Geospatial Queries (MarkLogic)
Carrying on from a previous question here. Where it was noted that avoiding fn:doc() should be avoided in SPARQL queries. However, for geospatial queries aside from the code shown below I am unable to find an alternative solution. I have also used this query and it's runtime is really slow. For bigger set of data it will hit the 1 hour timeout.

Hence, I would like to ask if there is a better way in implementing Geospatial queries for SPARQL? Is it possible to use GEOSPARQL with PREFIX spatial:<http://jena.apache.org/spatial#>?

```<code>xquery version "1.0-ml";
import module namespace sem = "http://marklogic.com/semantics" at "/MarkLogic/semantics.xqy";
import module namespace thsr="http://marklogic.com/xdmp/thesaurus"
                             at "/MarkLogic/thesaurus.xqy";

let $query := sem:sparql(
'
PREFIX xs: <http://www.w3.org/2001/XMLSchema#>
PREFIX cts: <http://marklogic.com/cts#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema/>
PREFIX fn: <http://www.w3.org/2005/xpath-functions#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX db: <http://dbpedia.org/resource/>
PREFIX onto: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns>
PREFIX xdmp: <http://marklogic.com/xdmp#>

SELECT *
WHERE{
?people </posted> ?question .
FILTER (cts:contains(fn:doc(?people),
cts:path-geospatial-query("/people_data/location",  cts:circle(10, cts:point(59,28)))
)) .
}',
(),
(),
()
)

return (xdmp:elapsed-time())
</code>```

=======Update========

Question brought over to thread

答:
I see two options here:

either you use the geospatial function that are built into MarkLogic to find geospatial overlap directly from inside SPARQL, preferably comparing an RDF property, rather than a value from a path index (still sub-optimal)

better: pre-fetch a list of documents matching your geospatial constraint, and feed that as constraint into your SPARQL (this should be highly performant)

Something along the lines of:

```<code>let $uris := cts:uris((), (), cts:path-geospatial-query("/people_data/location",  cts:circle(10, cts:point(59,28))))
return sem:sparql('
  SELECT *
  WHERE{
    ?person </posted> ?question .
    FILTER (?person = ?people) .
  }
', map:entry("people", $uris))
</code>```

A slightly more convenient, and better optimized of above example would be to rewrite it using Optic API. It is designed specifically for providing a highly performant way of bridging the gap between the various data models.

Extrapolating on the above code, I think it would read something like this in optic code:

```<code>import module namespace op="http://marklogic.com/optic" at "/MarkLogic/optic.xqy";

let $people := op:from-lexicons(
  map:entry("people", cts:uri-reference()),
  "lexicon"
)
  => op:where(
    cts:path-geospatial-query("/people_data/location", cts:circle(10, cts:point(59,28)))
  )

let $questions := op:from-sparql('SELECT * WHERE { ?person </posted> ?question. }', "sparql")

return $people
  => op:join-inner(
    $questions,
    op:on(
      op:view-col("lexicon", "people"),
      op:view-col("sparql", "person")
    )
  )
  =>op:result()
</code>```

It is a bit hard to test it without proper data and indexes, but I hope it is enough to get you started.

You can find introductory documentation on it here:

```<code>https://docs.marklogic.com/guide/app-dev/OpticAPI
</code>```

And the API reference can be found here:

```<code>https://docs.marklogic.com/op
</code>```

HTH!

Title: SPARQL Geospatial Queries (MarkLogic)

Body:
Carrying on from a previous question here. Where it was noted that avoiding fn:doc() should be avoided in SPARQL queries. However, for geospatial queries aside from the code shown below I am unable to find an alternative solution. I have also used this query and it's runtime is really slow. For bigger set of data it will hit the 1 hour timeout.

Hence, I would like to ask if there is a better way in implementing Geospatial queries for SPARQL? Is it possible to use GEOSPARQL with PREFIX spatial:<http://jena.apache.org/spatial#>?

xquery version "1.0-ml";
import module namespace sem = "http://marklogic.com/semantics" at "/MarkLogic/semantics.xqy";
import module namespace thsr="http://marklogic.com/xdmp/thesaurus"
                             at "/MarkLogic/thesaurus.xqy";

let $query := sem:sparql(
'
PREFIX xs: <http://www.w3.org/2001/XMLSchema#>
PREFIX cts: <http://marklogic.com/cts#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema/>
PREFIX fn: <http://www.w3.org/2005/xpath-functions#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX db: <http://dbpedia.org/resource/>
PREFIX onto: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns>
PREFIX xdmp: <http://marklogic.com/xdmp#>

SELECT *
WHERE{
?people </posted> ?question .
FILTER (cts:contains(fn:doc(?people),
cts:path-geospatial-query("/people_data/location",  cts:circle(10, cts:point(59,28)))
)) .
}',
(),
(),
()
)

return (xdmp:elapsed-time())

=======Update========

Question brought over to thread

Body:
I see two options here:

either you use the geospatial function that are built into MarkLogic to find geospatial overlap directly from inside SPARQL, preferably comparing an RDF property, rather than a value from a path index (still sub-optimal)

better: pre-fetch a list of documents matching your geospatial constraint, and feed that as constraint into your SPARQL (this should be highly performant)

Something along the lines of:

let $uris := cts:uris((), (), cts:path-geospatial-query("/people_data/location",  cts:circle(10, cts:point(59,28))))
return sem:sparql('
  SELECT *
  WHERE{
    ?person </posted> ?question .
    FILTER (?person = ?people) .
  }
', map:entry("people", $uris))

A slightly more convenient, and better optimized of above example would be to rewrite it using Optic API. It is designed specifically for providing a highly performant way of bridging the gap between the various data models.

Extrapolating on the above code, I think it would read something like this in optic code:

import module namespace op="http://marklogic.com/optic" at "/MarkLogic/optic.xqy";

let $people := op:from-lexicons(
  map:entry("people", cts:uri-reference()),
  "lexicon"
)
  => op:where(
    cts:path-geospatial-query("/people_data/location", cts:circle(10, cts:point(59,28)))
  )

let $questions := op:from-sparql('SELECT * WHERE { ?person </posted> ?question. }', "sparql")

return $people
  => op:join-inner(
    $questions,
    op:on(
      op:view-col("lexicon", "people"),
      op:view-col("sparql", "person")
    )
  )
  =>op:result()

It is a bit hard to test it without proper data and indexes, but I hope it is enough to get you started.

You can find introductory documentation on it here:

https://docs.marklogic.com/guide/app-dev/OpticAPI

And the API reference can be found here:

https://docs.marklogic.com/op

HTH!


来源: stackexchange

问:
Git - How to handle changes in locally renamed files when pulling from a parent repo

Question

I'm having issues pulling a parent repository into a fork and properly resolving conflicts.
It appears that if a file is renamed in the fork and is modified by both the parent and the fork, git only treats it as being deleted by us.

This happens when I use git pull /path/to/parent master and git merge upstream/master (with upstream configured).

How can I use git such that I am prompted to resolve the conflict on the renamed file instead of having git assume the file was deleted by us?

Setup

Here is a setup to demonstrate the issue I'm having. This can be done locally or in an online managed system (I'm experiencing this in Azure DevOps / VSTS).

I've duplicated most of the steps below in GitHub with these two repos:

parent - https://github.com/Daniel-Khodabakhsh/TestForkPull

fork - https://github.com/Daniel-H-K/TestForkPull

You can clone the fork and do a git pull https://github.com/Daniel-Khodabakhsh/TestForkPull.git master to see the issue.

Manual steps:

Create a small project with files with arbitrary text named A.txt, B.txt, and C.txt in a repo path /path/to/parent.

Create a fork of this repo by copying it to /path/to/fork and switch to this path.

In this new fork repo, rename the files in the following way and commit. I did it with the OS instead of using git mv but this shouldn't matter because of how git works.

```<code>A.txt → X.txt
B.txt → Y.txt
C.txt → Z.txt
</code>```

Verify git recognises the rename by running git diff --name-status HEAD~1 and noticing the 'R' indicating a detected rename.

```<code>$ git diff --name-status HEAD~1
R100    A.txt   X.txt
R100    B.txt   Y.txt
R100    C.txt   Z.txt
</code>```

In the parent repo, make modifications to the contents of files A.txt and B.txt.

In the fork repo, make modifications to the contents of files Y.txt and Z.txt.

Up to here, you'd have the following files in both repos:

```<code>A.txt → X.txt - Modified in parent
B.txt → Y.txt - Modified in both
C.txt → Z.txt - Modified in fork
</code>```

"pull" the parent repo into the fork by running git pull /path/to/parent master from the fork path. You will get the following output:

```<code>$ git pull /path/to/parent/ master
remote: Enumerating objects: 7, done.
remote: Counting objects: 100% (7/7), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
From D:/path/to/parent
 * branch            master     -> FETCH_HEAD
CONFLICT (modify/delete): B.txt deleted in HEAD and modified in ba146eba53bd7d51c9977238d9d62b56f7a984f7. Version ba146eba53bd7d51c9977238d9d62b56f7a984f7 of B.txt left in tree.
Automatic merge failed; fix conflicts and then commit the result.
</code>```

```<code>$ git status
On branch master
You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

Changes to be committed:

        modified:   X.txt

Unmerged paths:
  (use "git add/rm <file>..." as appropriate to mark resolution)

        deleted by us:   B.txt
</code>```

Here X.txt correctly only shows the modification from the parent repo, Z.txt is correctly untouched with changes from the fork repo, but Y.txt (B.txt) is not properly shown as in conflict, but rather, shown as only being deleted by us.

答: note : github shows some extra chars (a crlfmaybe ?) at the end of B.txt, which disappear both in "modified B.txt" and "renamed Y.txt". This may add to the confusion in detecting renames for git.

ContentLicense: CC BY-SA 4.0

Body:
Question

I'm having issues pulling a parent repository into a fork and properly resolving conflicts.
It appears that if a file is renamed in the fork and is modified by both the parent and the fork, git only treats it as being deleted by us.

This happens when I use git pull /path/to/parent master and git merge upstream/master (with upstream configured).

How can I use git such that I am prompted to resolve the conflict on the renamed file instead of having git assume the file was deleted by us?

Setup

Here is a setup to demonstrate the issue I'm having. This can be done locally or in an online managed system (I'm experiencing this in Azure DevOps / VSTS).

I've duplicated most of the steps below in GitHub with these two repos:

parent - https://github.com/Daniel-Khodabakhsh/TestForkPull

fork - https://github.com/Daniel-H-K/TestForkPull

You can clone the fork and do a git pull https://github.com/Daniel-Khodabakhsh/TestForkPull.git master to see the issue.

Manual steps:

Create a small project with files with arbitrary text named A.txt, B.txt, and C.txt in a repo path /path/to/parent.

Create a fork of this repo by copying it to /path/to/fork and switch to this path.

In this new fork repo, rename the files in the following way and commit. I did it with the OS instead of using git mv but this shouldn't matter because of how git works.

A.txt → X.txt
B.txt → Y.txt
C.txt → Z.txt

Verify git recognises the rename by running git diff --name-status HEAD~1 and noticing the 'R' indicating a detected rename.

$ git diff --name-status HEAD~1
R100    A.txt   X.txt
R100    B.txt   Y.txt
R100    C.txt   Z.txt

In the parent repo, make modifications to the contents of files A.txt and B.txt.

In the fork repo, make modifications to the contents of files Y.txt and Z.txt.

Up to here, you'd have the following files in both repos:

A.txt → X.txt - Modified in parent
B.txt → Y.txt - Modified in both
C.txt → Z.txt - Modified in fork

"pull" the parent repo into the fork by running git pull /path/to/parent master from the fork path. You will get the following output:

$ git pull /path/to/parent/ master
remote: Enumerating objects: 7, done.
remote: Counting objects: 100% (7/7), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
From D:/path/to/parent
 * branch            master     -> FETCH_HEAD
CONFLICT (modify/delete): B.txt deleted in HEAD and modified in ba146eba53bd7d51c9977238d9d62b56f7a984f7. Version ba146eba53bd7d51c9977238d9d62b56f7a984f7 of B.txt left in tree.
Automatic merge failed; fix conflicts and then commit the result.

$ git status
On branch master
You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

Changes to be committed:

        modified:   X.txt

Unmerged paths:
  (use "git add/rm <file>..." as appropriate to mark resolution)

        deleted by us:   B.txt

Here X.txt correctly only shows the modification from the parent repo, Z.txt is correctly untouched with changes from the fork repo, but Y.txt (B.txt) is not properly shown as in conflict, but rather, shown as only being deleted by us.


问:
clean "prefixes" in a set of arrays?
I was wondering, I've got a Set of Arrays containing something of my own datatype.
something looking like:

```<code>traces = {[<label1>, <label2>], [<label1>], [<label1>,<label2>,<label3>]}
</code>```

Now, I would like to have a method that cleans all 'prefix'-existing arrays in the Set,
so my new set will be in this example:

```<code>traces = {[<label1>,<label2>,<label3>]}
</code>```

Anybody an idea how to make a clean implementation out of this?
I hope there is a neater solution than stepping through traces and a Set new_traces and comparing every array-item several times.

Note:
I define Array A is a prefix of Array B iff the first items of Array B are actually the Array A

答:
call flatten and then uniq</p>

```<code> class T
  attr_accessor :n
  def initialize(n); @n = n; end
  def eql?(other); n.eql?(other.n); end
  def hash; n.hash; end
end

a = [T.new(1), T.new(2), T.new(3), T.new(4), T.new(2), T.new(1), [T.new(2), T.new(2)], [T.new(4)]]

a.flatten.uniq.map(&:n) # => [1, 2, 3, 4]
</code>```

ContentLicense: CC BY-SA 3.0

Title: clean "prefixes" in a set of arrays?

Body:
I was wondering, I've got a Set of Arrays containing something of my own datatype.
something looking like:

traces = {[<label1>, <label2>], [<label1>], [<label1>,<label2>,<label3>]}

Now, I would like to have a method that cleans all 'prefix'-existing arrays in the Set,
so my new set will be in this example:

traces = {[<label1>,<label2>,<label3>]}

Anybody an idea how to make a clean implementation out of this?
I hope there is a neater solution than stepping through traces and a Set new_traces and comparing every array-item several times.

Note:
I define Array A is a prefix of Array B iff the first items of Array B are actually the Array A

Body:
call flatten and then uniq

 class T
  attr_accessor :n
  def initialize(n); @n = n; end
  def eql?(other); n.eql?(other.n); end
  def hash; n.hash; end
end

a = [T.new(1), T.new(2), T.new(3), T.new(4), T.new(2), T.new(1), [T.new(2), T.new(2)], [T.new(4)]]

a.flatten.uniq.map(&:n) # => [1, 2, 3, 4]


问:
SIM800 HTTPS 606 Error
I have been using SSL to connect a SIMCOM SIM800 GSM Module to a Microsoft Azure function endpoint.  This has been working for months and has now stopped working and reports a 606 error code which indicates an "SSL alert message with a level of fatal result and the immediate termination of the connection" according to  SIM800 Series_SSL_Application Note_V1.02

I tried HTTPS connections to various other sites using the SIM800 e.g. google and httpbin and got mixed results: I could connect to some e.g. google but not others e.g. httpbin.  See here for a similar result.

Does anyone know if sites have recently changed SSL cipher or protocol requirements? The SIM800 module (only) supports  SSL2.0, SSL3.0 and TLS1.0.

答:
I'm using a SIM808 (V2 / R14.18) to make some GET requests to HTTPS endpoints such a https://www.google.com and a personal Azure website.
I get successful answers from google but from Azure, even if change the "Minimum TLS version" I'm always having a 606 answer.

So, I'm not sure if my SIM808 does really support TLS1.0. Maybe your SIM800 does (documentation is quite confusing).

Title: SIM800 HTTPS 606 Error


问:
What is the difference between TF 2.0 Alpha and TF nightly preview?
Is there any difference between them, in terms of stability, which one is more recent etc.
Additionally, what should I expect in the coming months, a beta version? and then final release?</p>

答:
Tensorflow 2.0 alpha is the Tensorflow 2.0 alpha version released on the Tensorflow dev summit 2019 day. Its API is "stable" (that means, it doesn't change every day), although it is explicitly an alpha version, hence something can't work as you expect.

The nightly builds, instead, are builds created daily with the changes occurring on the master branch of the Tensorflow repo. The API changes often (e.g. 2 days ago the symbol tf.mod was a thing, now it is present only in tf.math.mod) and is more "unstable" then the alpha itself.

In the coming months... who knows. The first release candidate was planned for "spring" 2019 - but spring is a flexible concept (quote from Martin Wicke - "Spring is a sort of flexible concept").


问:
Json doesn't appear
I trying to catch value from json.I haven't arrays(name). So I need directly able to data. I get a warning about "getJSONObject(0)" It's said "String.valueOf()" So I applied to this.

My JSON
link available here

```<code>{
  "-LZEGO2dtHMm7zNP05Jd" : {
    "NewZaman" : "20.02.2019 / 22:45",
    "Oynayanlar" : "Derby - Millwall",
    "Tahmin" : "UNDER 2.5",
    "Tahmin2" : "ALT 1.5",
    "id" : "85",
    "mackelesonucu" : 44,
    "sonuckelesen" : "Win",
    "sonuckelestr" : "Kazandı",
    "sortingId" : -85
  },
  "-LZEJ_ohgg3eLr1Jdv38" : {
    "NewZaman" : "20.02.2019 / 13:15",
    "Oynayanlar" : "Dunav Ruse - FC Vereya",
    "Tahmin" : "1",
    "Tahmin2" : "1",
    "id" : "86",
    "mackelesonucu" : 44,
    "sonuckelesen" : "Win",
    "sonuckelestr" : "Kazandı",
    "sortingId" : -86
   }
}
</code>```

CODE

Code for parse

```<code>    private void parseJSON() {
        String url ="http://xjamal.epizy.com/tahminall-dene.json";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            //JSONArray jsonArray = response.getJSONArray("hits");
                            JSONObject jsonArray = response.getJSONObject(String.valueOf(0));

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(String.valueOf(i));

                                String creatorName = hit.getString("sonuckelesen");
                                String likeCount = hit.getString("mackelesonucu");

                                mExampleList.add(new arsivlist(creatorName, likeCount));
                            }

                            mExampleAdapter = new ArsivAdapter(Arsivgoster.this, mExampleList);
                            mRecyclerView.setAdapter(mExampleAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQueue.add(request);
    }
}
</code>```

Now json doesn't appear. The page shows empty.

UPDATE for Kulan's aswer.It doesn't work.

```<code>    private void parseJSON() {
        String url ="http://xjamal.epizy.com/tahminall-dene.json";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Iterator<String> keys = response.keys();

                            while(keys.hasNext()) {
                                String key = keys.next();
                                if (response.get(key) instanceof JSONObject) {
                                    JSONObject innerObject = response.getJSONObject(key);
                                    String creatorName = innerObject.getString("sonuckelesen");
                                    String likeCount = innerObject.getString("mackelesonucu");

                                    mExampleList.add(new arsivlist(creatorName, likeCount));

                                }
                            }
                            mExampleAdapter = new ArsivAdapter(Arsivgoster.this, mExampleList);
                            mRecyclerView.setAdapter(mExampleAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQueue.add(request);
    }
}
</code>```

答:
try parsing your response json object like this

```<code>Iterator<String> keys = response.keys();

        while(keys.hasNext()) {
            String key = keys.next();
            if (response.get(key) instanceof JSONObject) {
                JSONObject innerObject = response.getJSONObject(key);
                String creatorName = innerObject.getString("sonuckelesen");
                String likeCount = innerObject.getString("mackelesonucu");

                mExampleList.add(new arsivlist(creatorName, likeCount));

            }
        }
        mExampleAdapter = new ArsivAdapter(Arsivgoster.this, mExampleList);
        mRecyclerView.setAdapter(mExampleAdapter);
</code>```

replace this code with your code in try block

Title: Json doesn't appear

Body:
I trying to catch value from json.I haven't arrays(name). So I need directly able to data. I get a warning about "getJSONObject(0)" It's said "String.valueOf()" So I applied to this.

My JSON
link available here

{
  "-LZEGO2dtHMm7zNP05Jd" : {
    "NewZaman" : "20.02.2019 / 22:45",
    "Oynayanlar" : "Derby - Millwall",
    "Tahmin" : "UNDER 2.5",
    "Tahmin2" : "ALT 1.5",
    "id" : "85",
    "mackelesonucu" : 44,
    "sonuckelesen" : "Win",
    "sonuckelestr" : "Kazandı",
    "sortingId" : -85
  },
  "-LZEJ_ohgg3eLr1Jdv38" : {
    "NewZaman" : "20.02.2019 / 13:15",
    "Oynayanlar" : "Dunav Ruse - FC Vereya",
    "Tahmin" : "1",
    "Tahmin2" : "1",
    "id" : "86",
    "mackelesonucu" : 44,
    "sonuckelesen" : "Win",
    "sonuckelestr" : "Kazandı",
    "sortingId" : -86
   }
}

CODE

Code for parse

    private void parseJSON() {
        String url ="http://xjamal.epizy.com/tahminall-dene.json";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            //JSONArray jsonArray = response.getJSONArray("hits");
                            JSONObject jsonArray = response.getJSONObject(String.valueOf(0));

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject hit = jsonArray.getJSONObject(String.valueOf(i));

                                String creatorName = hit.getString("sonuckelesen");
                                String likeCount = hit.getString("mackelesonucu");

                                mExampleList.add(new arsivlist(creatorName, likeCount));
                            }

                            mExampleAdapter = new ArsivAdapter(Arsivgoster.this, mExampleList);
                            mRecyclerView.setAdapter(mExampleAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQueue.add(request);
    }
}

Now json doesn't appear. The page shows empty.

UPDATE for Kulan's aswer.It doesn't work.

    private void parseJSON() {
        String url ="http://xjamal.epizy.com/tahminall-dene.json";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Iterator<String> keys = response.keys();

                            while(keys.hasNext()) {
                                String key = keys.next();
                                if (response.get(key) instanceof JSONObject) {
                                    JSONObject innerObject = response.getJSONObject(key);
                                    String creatorName = innerObject.getString("sonuckelesen");
                                    String likeCount = innerObject.getString("mackelesonucu");

                                    mExampleList.add(new arsivlist(creatorName, likeCount));

                                }
                            }
                            mExampleAdapter = new ArsivAdapter(Arsivgoster.this, mExampleList);
                            mRecyclerView.setAdapter(mExampleAdapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQueue.add(request);
    }
}

Body:
try parsing your response json object like this

Iterator<String> keys = response.keys();

        while(keys.hasNext()) {
            String key = keys.next();
            if (response.get(key) instanceof JSONObject) {
                JSONObject innerObject = response.getJSONObject(key);
                String creatorName = innerObject.getString("sonuckelesen");
                String likeCount = innerObject.getString("mackelesonucu");

                mExampleList.add(new arsivlist(creatorName, likeCount));

            }
        }
        mExampleAdapter = new ArsivAdapter(Arsivgoster.this, mExampleList);
        mRecyclerView.setAdapter(mExampleAdapter);

replace this code with your code in try block


问:
XPATH: Check if a xml node contains specific characters or strings
Imagine this XML file (sorry for sick example!!)

```<code><DOC>
<Test>
    <Name>1 vs 100 Pre pre History</Name>
    <Type>Dinasors</Type>
</Test>

<Test>
    <Name> 1 vs 100 Post moderns</Name>
    <Type>Aliens</Type>
</Test>
</Doc>
</code>```

The idea is returning the Type value, By checking if Name node contains a specific character or string. For example I want a XPath Query like:

```<code>/Doc//Test[contains "Pre" and "History" and 1]/Type
</code>```

That is check if Test contains "Pre" and "History" and number 1, What will be the xpath query? Alo I like this query to not be CASE SENSITIVE.

Thanks.

答:
I think this should work (haven't tested it):

```<code>/Doc//Test[contains(Name,'Pre') and contains(Name,'History') and contains(Name,1)]/Type
</code>```

However that is case sensitive. If you want it case insensitive, then you may want to have a look at this question or this question: you must use translate to convert your Name to lower-case (or upper-case) and then match.

Body:
Imagine this XML file (sorry for sick example!!)

<DOC>
<Test>
    <Name>1 vs 100 Pre pre History</Name>
    <Type>Dinasors</Type>
</Test>

<Test>
    <Name> 1 vs 100 Post moderns</Name>
    <Type>Aliens</Type>
</Test>
</Doc>

The idea is returning the Type value, By checking if Name node contains a specific character or string. For example I want a XPath Query like:

/Doc//Test[contains "Pre" and "History" and 1]/Type

That is check if Test contains "Pre" and "History" and number 1, What will be the xpath query? Alo I like this query to not be CASE SENSITIVE.

Thanks.

Body:
I think this should work (haven't tested it):

/Doc//Test[contains(Name,'Pre') and contains(Name,'History') and contains(Name,1)]/Type

However that is case sensitive. If you want it case insensitive, then you may want to have a look at this question or this question: you must use translate to convert your Name to lower-case (or upper-case) and then match.


问:
Blazor 0.6.0 "wipes" Flurl-compatibility?
After updating Blazor from 0.5.1 (with working Flurl) to 0.6.0, calls via flurl throw an exception:

```<code>WASM: [Flurl.Http.FlurlHttpException] Call failed. Cannot invoke method
because it was wiped. See stack trace for details.
</code>```

The project creates a HttpClientFactory which gets Blazor's HttpClient for being used by Flurl:

Create FlurlClient with Blazor's HttpClient (http) using HttpClientFactoryForBlazor:

```<code>IFlurlClient c = new FlurlClient() { Settings = new Flurl.Http.Configuration.ClientFlurlHttpSettings { HttpClientFactory = new HttpClientFactoryForBlazor(http) }};
</code>```

Use the FlurlClient (c) for example by via Flurl's extensionmethod "IFlurlRequest.WithClient(c);"

```<code>private class HttpClientFactoryForBlazor : Flurl.Http.Configuration.IHttpClientFactory
{
    private readonly HttpClient httpClient;

    public HttpClientFactoryForBlazor(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

    public virtual HttpClient CreateHttpClient(HttpMessageHandler handler)
    {
        return this.httpClient;
    }
}
</code>```

So, it seems like this approach does no longer work.

Does anybody know how to make Flurl with Blazor 0.6.0 work?

Call-Stack is:

```<code>WASM: [Flurl.Http.FlurlHttpException] Call failed. Cannot invoke method because it was wiped. See stack trace for details. GET http://srv01.servicegrid.eu:4455/API/Status?forceLoadDbs=False blazor.webassembly.js:1:32098
WASM:   at Flurl.Http.FlurlRequest.HandleExceptionAsync (Flurl.Http.HttpCall call, System.Exception ex, System.Threading.CancellationToken token) <0x26945b8 + 0x001c2> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM:   at Flurl.Http.FlurlRequest.SendAsync (System.Net.Http.HttpMethod verb, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken, System.Net.Http.HttpCompletionOption completionOption) <0x2665d30 + 0x005e6> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM:   at Flurl.Http.FlurlRequest.SendAsync (System.Net.Http.HttpMethod verb, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken, System.Net.Http.HttpCompletionOption completionOption) <0x2665d30 + 0x0079a> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM:   at Flurl.Http.HttpResponseMessageExtensions.ReceiveJson[T] (System.Threading.Tasks.Task`1[TResult] response) <0x26a2180 + 0x000d6> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM:   at DotNetFabrik.FlurlExtensions.FlurlRequestExtensions.HandleWebApiExceptions[T] (System.Threading.Tasks.Task`1[TResult] task) <0x26a43f8 + 0x000e2> in <8c1e6df9d3f545cd831ff49915df2d85>:0 blazor.webassembly.js:1:32098
WASM:   at DotNetFabrik.FlurlExtensions.FlurlRequestExtensions.HandleWebApiExceptions[T] (System.Threading.Tasks.Task`1[TResult] task) <0x26a43f8 + 0x00264> in <8c1e6df9d3f545cd831ff49915df2d85>:0 blazor.webassembly.js:1:32098
WASM:   at BlazorCoreDMSTools.CommunicationService.CommunicationService.SetTokenAsync (System.String token, System.String database, System.String serverUri) <0x260dc60 + 0x00d9e> in <cb925648b50340888772566fbaeac465>:0
</code>```

答:
Currently in my 3.0 preview 5, BrowserHttpMessageHandler is not there anymore. Here is my current fix by simply not using any HttpMessageHandler. As far as I am aware, no problem happens to me yet, but I am not sure in all use cases:

```<code>class BlazorHttpClientFactory : DefaultHttpClientFactory
{

    public override HttpClient CreateHttpClient(HttpMessageHandler handler)
    {
        return new HttpClient();
    }

    public override HttpMessageHandler CreateMessageHandler()
    {
        return null;
    }

}
</code>```

Body:
After updating Blazor from 0.5.1 (with working Flurl) to 0.6.0, calls via flurl throw an exception:

WASM: [Flurl.Http.FlurlHttpException] Call failed. Cannot invoke method
because it was wiped. See stack trace for details.

The project creates a HttpClientFactory which gets Blazor's HttpClient for being used by Flurl:

Create FlurlClient with Blazor's HttpClient (http) using HttpClientFactoryForBlazor:

IFlurlClient c = new FlurlClient() { Settings = new Flurl.Http.Configuration.ClientFlurlHttpSettings { HttpClientFactory = new HttpClientFactoryForBlazor(http) }};

Use the FlurlClient (c) for example by via Flurl's extensionmethod "IFlurlRequest.WithClient(c);"

private class HttpClientFactoryForBlazor : Flurl.Http.Configuration.IHttpClientFactory
{
    private readonly HttpClient httpClient;

    public HttpClientFactoryForBlazor(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

    public virtual HttpClient CreateHttpClient(HttpMessageHandler handler)
    {
        return this.httpClient;
    }
}

So, it seems like this approach does no longer work.

Does anybody know how to make Flurl with Blazor 0.6.0 work?

Call-Stack is:

WASM: [Flurl.Http.FlurlHttpException] Call failed. Cannot invoke method because it was wiped. See stack trace for details. GET http://srv01.servicegrid.eu:4455/API/Status?forceLoadDbs=False blazor.webassembly.js:1:32098
WASM:   at Flurl.Http.FlurlRequest.HandleExceptionAsync (Flurl.Http.HttpCall call, System.Exception ex, System.Threading.CancellationToken token) <0x26945b8 + 0x001c2> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM:   at Flurl.Http.FlurlRequest.SendAsync (System.Net.Http.HttpMethod verb, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken, System.Net.Http.HttpCompletionOption completionOption) <0x2665d30 + 0x005e6> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM:   at Flurl.Http.FlurlRequest.SendAsync (System.Net.Http.HttpMethod verb, System.Net.Http.HttpContent content, System.Threading.CancellationToken cancellationToken, System.Net.Http.HttpCompletionOption completionOption) <0x2665d30 + 0x0079a> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM:   at Flurl.Http.HttpResponseMessageExtensions.ReceiveJson[T] (System.Threading.Tasks.Task`1[TResult] response) <0x26a2180 + 0x000d6> in <c38761af4558433f81b1691eb86a1548>:0 blazor.webassembly.js:1:32098
WASM:   at DotNetFabrik.FlurlExtensions.FlurlRequestExtensions.HandleWebApiExceptions[T] (System.Threading.Tasks.Task`1[TResult] task) <0x26a43f8 + 0x000e2> in <8c1e6df9d3f545cd831ff49915df2d85>:0 blazor.webassembly.js:1:32098
WASM:   at DotNetFabrik.FlurlExtensions.FlurlRequestExtensions.HandleWebApiExceptions[T] (System.Threading.Tasks.Task`1[TResult] task) <0x26a43f8 + 0x00264> in <8c1e6df9d3f545cd831ff49915df2d85>:0 blazor.webassembly.js:1:32098
WASM:   at BlazorCoreDMSTools.CommunicationService.CommunicationService.SetTokenAsync (System.String token, System.String database, System.String serverUri) <0x260dc60 + 0x00d9e> in <cb925648b50340888772566fbaeac465>:0

Body:
Currently in my 3.0 preview 5, BrowserHttpMessageHandler is not there anymore. Here is my current fix by simply not using any HttpMessageHandler. As far as I am aware, no problem happens to me yet, but I am not sure in all use cases:

class BlazorHttpClientFactory : DefaultHttpClientFactory
{

    public override HttpClient CreateHttpClient(HttpMessageHandler handler)
    {
        return new HttpClient();
    }

    public override HttpMessageHandler CreateMessageHandler()
    {
        return null;
    }

}


问:
android how to draw a circle on google map
I am using the new API(Google Map API V2) for my android application, i have done creating the map and adding markers to it, now my task is to manually create a circle around any of the marker and also i want to provide a functionality to the user that he can increase the radius of that circle accordingly, for this i have given a bar, when user increases that bar the radius of circle will increase and vice versa.

If anybody knows how to do this using Google Map API V2 then please help,

答:
Google Maps can use semi-transparent color for the circle.</p>

```<code>private var circle: Circle? = null

private fun drawCircle(latitude: Double, longitude: Double, radius: Double) {
    val circleOptions = CircleOptions()
        .center(LatLng(latitude, longitude))
        .radius(radius)
        .strokeWidth(1.0f)
        .strokeColor(ContextCompat.getColor(context!!, R.color.color1))
        .fillColor(ContextCompat.getColor(context!!, R.color.color2))
    circle?.remove() // Remove old circle.
    circle = googleMap?.addCircle(circleOptions) // Draw new circle.
}
</code>```

Body:
Google Maps can use semi-transparent color for the circle.

private var circle: Circle? = null

private fun drawCircle(latitude: Double, longitude: Double, radius: Double) {
    val circleOptions = CircleOptions()
        .center(LatLng(latitude, longitude))
        .radius(radius)
        .strokeWidth(1.0f)
        .strokeColor(ContextCompat.getColor(context!!, R.color.color1))
        .fillColor(ContextCompat.getColor(context!!, R.color.color2))
    circle?.remove() // Remove old circle.
    circle = googleMap?.addCircle(circleOptions) // Draw new circle.
}


问:
Define values for each namespace
values.yaml

```<code>replicas: {
  test: 1,
  stage: 2,
  prod: 3
}
</code>```

Here I am trying to use Helm templates to define number of replicas per namespace but am unsure of the proper syntax and pattern:

deployment.yaml

```<code>replicas: {{ .Values.replicas.{{ .Release.Namespace }} }}
</code>```

So if this were deployed to --namespace=prod, I would expect the template to return:

```<code># .Values.replicas.prod
replicas: 3
</code>```

答:
All of the template functions provided by the standard Go text/template library are available.  In particular, that includes an index function which can do dynamic lookup in an array or map object.

```<code>replicas: {{ index .Values.replicas .Release.Namespace }}
</code>```

Title: Define values for each namespace

Body:
values.yaml

replicas: {
  test: 1,
  stage: 2,
  prod: 3
}

Here I am trying to use Helm templates to define number of replicas per namespace but am unsure of the proper syntax and pattern:

deployment.yaml

replicas: {{ .Values.replicas.{{ .Release.Namespace }} }}

So if this were deployed to --namespace=prod, I would expect the template to return:

# .Values.replicas.prod
replicas: 3

Body:
All of the template functions provided by the standard Go text/template library are available.  In particular, that includes an index function which can do dynamic lookup in an array or map object.

replicas: {{ index .Values.replicas .Release.Namespace }}


答:
Here is the executed version of your table and query that gives output in the order you needed, on DB-fiddle.
Try this query:

```<code>select * from EntryExitLogs where id in
    (select id from EntryExitLogs where (badge,data_ora)= any
    (select badge,min(data_ora)from EntryExitLogs group by date(data_ora),badge))
    union
    (select * from EntryExitLogs where id in
    (select id from EntryExitLogs where (badge,data_ora)= any
    (select badge,max(data_ora)from EntryExitLogs group by date(data_ora),badge)))
    order by id;
</code>```

I think its better to make use of the ID column for selecting the rows, because the timestamp column contains duplicates.

Title: Select Max and Min datetime for distinct user

Body:
I have a record as below

ID(int)      DATA_ORA(timestamp)     BADGE  LETTORE
   1         2017-04-01 09:30:00       1       1
   2         2017-04-01 12:30:00       1       2
   3         2017-04-01 13:30:00       1       1
   4         2017-04-01 18:30:00       1       2
   5         2017-04-01 09:30:00       2       1
   6         2017-04-01 18:30:00       2       2
   7         2017-04-02 09:30:00       1       1
   8         2017-04-02 18:30:00       1       2
   9         2017-04-03 09:30:00       3       1
   10        2017-04-03 12:30:00       3       2
   11        2017-04-03 13:30:00       3       1
   12        2017-04-03 18:30:00       3       2

I want to get the first access time and the last daily logout time (for each day) for each individual user (badge).

How I can do this?

The record I wish to as below

ID(int)      DATA_ORA(timestamp)     BADGE  LETTORE
   1         2017-04-01 09:30:00       1       1
   4         2017-04-01 18:30:00       1       2
   5         2017-04-01 09:30:00       2       1
   6         2017-04-01 18:30:00       2       2
   7         2017-04-02 09:30:00       1       1
   8         2017-04-02 18:30:00       1       2
   9         2017-04-03 09:30:00       3       1
   12        2017-04-03 18:30:00       3       2

Is it possible to do that? Thanks.

NOTE: ID are auto-incremented and LETTORE 1 is entry and LETTORE 2 is exit.

Body:
Here is the executed version of your table and query that gives output in the order you needed, on DB-fiddle.
Try this query:

select * from EntryExitLogs where id in
    (select id from EntryExitLogs where (badge,data_ora)= any
    (select badge,min(data_ora)from EntryExitLogs group by date(data_ora),badge))
    union
    (select * from EntryExitLogs where id in
    (select id from EntryExitLogs where (badge,data_ora)= any
    (select badge,max(data_ora)from EntryExitLogs group by date(data_ora),badge)))
    order by id;

I think its better to make use of the ID column for selecting the rows, because the timestamp column contains duplicates.


问:
Clarity required in creating LUIS and KB and linking them
I created 10KB for my 10 different process. Lets say, each KB has QNA pertaining to each processes. Now i need to create a LUIS which would identify the right intent of user and fetch an answer from right KB. Can you please clarify how this works from an architecture perspective and please help me with the steps as well.</p>

答:
There is a guide and sample project available here.

Basically you create a LUIS app and then you use the Dispatch tool to create a local file which scans all of your knowledge bases and extracts your questions to use as something that LUIS calls utterances, these utterances are then used to determine the user's LUIS intent in your case which knowledge base to use. Basically the dispatch app in LUIS acts as a router. One you have created the dispatch file locally then you need to push it up to your LUIS app (dispatch create command).

I would recommend downloading the sample app and running through the whole process to get a basic understanding of how everything fits together. Once you have published your LUIS app you will be able to test it within the LUIS portal by inputting example utterances and inspecting the reply to see the intent that was selected. The documentation for the Dispatch tool is available here, please note that when you update your knowledge bases (by adding new entries or alternative phrasing) after publishing your dispatch app initially you will have to refresh your dispatch model for these new questions/alternative phrase to have an utterance added in LUIS to that map to the correct LUIS intent - otherwise they will return the None intent.

NB. you could hack around the need to update the dispatcher by handling the case when you get a the "None" intent back and iterating through all of your knowledge bases to request an answer for the user's query and just return the answer with the higher score (have a collection that keeps the answer from each knowledge base) but I wouldn't recommend it as you miss out on the benefits of Active learning for LUIS and QnA Maker.


问:
drag ImageView inside a WebView
:)
I'm adding an ImageView inside a WebView like this :

```<code>    void addImv(int in)
{
     imageView.setId(imageID);
     webComp.addView(imageView);

     Bitmap bitmap;
     File sd = Environment.getExternalStorageDirectory();
     if(sd.canRead()){
         bitmap = BitmapFactory.decodeFile(sd.getAbsolutePath() + "/FMS/1/file"+in+".jpg");
         imageView.setImageBitmap(bitmap);
         imageView.setAdjustViewBounds(true);
         imageView.setMaxHeight(150);
         imageView.setAlpha(150);

         imageView.bringToFront();
     }
}
</code>```

The photo is shown in the left top of the screen correctly.
Now I have this listener for touches on the imageView

```<code>    OnTouchListener listenTouch = new OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        return true;
    }
</code>```

};

which works too. How can i set the position of the imageView? I've tried using imageView.setPadding and imageView.imageView.setLayoutParams but clearly I'm doing something really wrong as it force-closes. The imageView isn't defined in xml layout file. Thank you!

答:
This worked:

```<code> OnTouchListener listenTouch = new OnTouchListener()
</code>```

{

```<code>public boolean onTouch(View v, MotionEvent event)
{
    imageView.offsetLeftAndRight((int)event.getX()-imageView.getWidth());
    imageView.offsetTopAndBottom((int)event.getY()-imageView.getHeight());
    webComp.invalidate();
    return true;
}
</code>```

};

Title: drag ImageView inside a WebView

Body:
:)
I'm adding an ImageView inside a WebView like this :

    void addImv(int in)
{
     imageView.setId(imageID);
     webComp.addView(imageView);

     Bitmap bitmap;
     File sd = Environment.getExternalStorageDirectory();
     if(sd.canRead()){
         bitmap = BitmapFactory.decodeFile(sd.getAbsolutePath() + "/FMS/1/file"+in+".jpg");
         imageView.setImageBitmap(bitmap);
         imageView.setAdjustViewBounds(true);
         imageView.setMaxHeight(150);
         imageView.setAlpha(150);

         imageView.bringToFront();
     }
}

The photo is shown in the left top of the screen correctly.
Now I have this listener for touches on the imageView

    OnTouchListener listenTouch = new OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        return true;
    }

};

which works too. How can i set the position of the imageView? I've tried using imageView.setPadding and imageView.imageView.setLayoutParams but clearly I'm doing something really wrong as it force-closes. The imageView isn't defined in xml layout file. Thank you!

Body:
This worked:

 OnTouchListener listenTouch = new OnTouchListener()

{

public boolean onTouch(View v, MotionEvent event)
{
    imageView.offsetLeftAndRight((int)event.getX()-imageView.getWidth());
    imageView.offsetTopAndBottom((int)event.getY()-imageView.getHeight());
    webComp.invalidate();
    return true;
}

};


问:
How to fix number of females employees in a shift
I am adding a custom rule for Employee shift where i have 4 types of shifts and in one type of shift the number of female employees have to be fix

i have tried adding a field in shift class namely requiredFemalesEmployees which is set to 1
   //hard constraint
   rule "OneFemaleInShiftA"

```<code>when
$gender:Employee(gender=="F")
 $rfe:Shift(requiredFemalesEmployees==1)
 accumulate(
$a:ShiftAssignment(employee==$gender,$shift:shift.requiredFemalesEmployees),
 $total :count($a)
)

then
 if($total.intValue()!=1){
 scoreHolder.addHardConstraintMatch(kcontext, - 1);
 }
</code>```

end

any suggestions will be a great help.

答:
First, you created a variable named $rfe, but is unused, and in this line:
$a:ShiftAssignment(employee==$gender,$shift:shift.requiredFemalesEmployees), what'r you assigning to $shift ?

This is my example:

```<code>rule "oneFemaleInShift"
    when
        $gender:Employee(gender=="F")
        $rfe:Shift(requiredFemalesEmployees==1)
        Number(intValue!=1) from accumulate(
            $a:ShiftAssignment(employee==$gender, ¿¿$shift:shift.requiredFemalesEmployees??),
            count($a)
        )

    then
        scoreHolder.addHardConstraintMatch(kcontext, - 1);

</code>```

We need the domain model or the source of java POJOs to know the relations between them.

I think this will help you:

```<code>rule "oneFemaleInShift"
    when
        $femaleEmployee:Employee(gender=="F") //GET FEMALE POJOS
        $rfe:Shift(requiredFemalesEmployees==1) // GET SHIFT WHERE FEMALE IS REQUIRED
        Number(intValue > 0) from accumulate( //COUNT NUMBER OF FEMALE EMPLOYEES IN THAT SHIFT, PENALIZE SOLUTION WHERE THERE ARE LESS THAN 1
            $a:ShiftAssignment(employee==$femaleEmployee, shift==$rfe),
            count($a)
        )
    then
        scoreHolder.addHardConstraintMatch(kcontext, - 1); // LOOK AT THE VALUE OF HARD SCORE, PROPORTION WITH OTHER HARD CONSTRAINT
</code>```

Body:
I am adding a custom rule for Employee shift where i have 4 types of shifts and in one type of shift the number of female employees have to be fix

i have tried adding a field in shift class namely requiredFemalesEmployees which is set to 1
   //hard constraint
   rule "OneFemaleInShiftA"

when
$gender:Employee(gender=="F")
 $rfe:Shift(requiredFemalesEmployees==1)
 accumulate(
$a:ShiftAssignment(employee==$gender,$shift:shift.requiredFemalesEmployees),
 $total :count($a)
)

then
 if($total.intValue()!=1){
 scoreHolder.addHardConstraintMatch(kcontext, - 1);
 }

end

any suggestions will be a great help.

Body:
First, you created a variable named $rfe, but is unused, and in this line:
$a:ShiftAssignment(employee==$gender,$shift:shift.requiredFemalesEmployees), what'r you assigning to $shift ?

This is my example:

rule "oneFemaleInShift"
    when
        $gender:Employee(gender=="F")
        $rfe:Shift(requiredFemalesEmployees==1)
        Number(intValue!=1) from accumulate(
            $a:ShiftAssignment(employee==$gender, ¿¿$shift:shift.requiredFemalesEmployees??),
            count($a)
        )

    then
        scoreHolder.addHardConstraintMatch(kcontext, - 1);

We need the domain model or the source of java POJOs to know the relations between them.

I think this will help you:

rule "oneFemaleInShift"
    when
        $femaleEmployee:Employee(gender=="F") //GET FEMALE POJOS
        $rfe:Shift(requiredFemalesEmployees==1) // GET SHIFT WHERE FEMALE IS REQUIRED
        Number(intValue > 0) from accumulate( //COUNT NUMBER OF FEMALE EMPLOYEES IN THAT SHIFT, PENALIZE SOLUTION WHERE THERE ARE LESS THAN 1
            $a:ShiftAssignment(employee==$femaleEmployee, shift==$rfe),
            count($a)
        )
    then
        scoreHolder.addHardConstraintMatch(kcontext, - 1); // LOOK AT THE VALUE OF HARD SCORE, PROPORTION WITH OTHER HARD CONSTRAINT


问:
Trying to install Perl-Mysql DBD, mysql_config can't be found
Here's the output:

```Ian-MacBook-Pro:DBD-mysql-4.011 ianseyer$ sudo Perl Makefile.PL
Can't exec "mysql_config": No such file or directory at Makefile.PL line 76.

Cannot find the file 'mysql_config'! Your execution PATH doesn't seem
not contain the path to mysql_config. Resorting to guessed values!
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located

PLEASE NOTE:

For 'make test' to run properly, you must ensure that the
database user 'root' can connect to your MySQL server
and has the proper privileges that these tests require such
as 'drop table', 'create table', 'drop procedure', 'create procedure'
as well as others.

mysql> grant all privileges on test.* to 'root'@'localhost' identified by 's3kr1t';

You can also optionally set the user to run 'make test' with:

perl Makefile.pl --testuser=username

Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Failed to determine directory of mysql.h. Use

  perl Makefile.PL --cflags=-I

to set this directory. For details see the INSTALL.html file,
section "C Compiler flags" or type

  perl Makefile.PL --help
```

I've researched the issue and tried making a symlink to no avail.

Do I have to compile this myself?

答:
Try yum install mariadb-devel for CentOS 7 and then
run the required Perl module installation such as cpan DBD::mysql

ContentLicense: CC BY-SA 2.5

Body:
Here's the output:

Ian-MacBook-Pro:DBD-mysql-4.011 ianseyer$ sudo Perl Makefile.PL
Can't exec "mysql_config": No such file or directory at Makefile.PL line 76.

Cannot find the file 'mysql_config'! Your execution PATH doesn't seem
not contain the path to mysql_config. Resorting to guessed values!
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located

PLEASE NOTE:

For 'make test' to run properly, you must ensure that the
database user 'root' can connect to your MySQL server
and has the proper privileges that these tests require such
as 'drop table', 'create table', 'drop procedure', 'create procedure'
as well as others.

mysql> grant all privileges on test.* to 'root'@'localhost' identified by 's3kr1t';

You can also optionally set the user to run 'make test' with:

perl Makefile.pl --testuser=username

Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Failed to determine directory of mysql.h. Use

  perl Makefile.PL --cflags=-I

to set this directory. For details see the INSTALL.html file,
section "C Compiler flags" or type

  perl Makefile.PL --help

I've researched the issue and tried making a symlink to no avail.

Do I have to compile this myself?


问:
cannot use buffer (type bytes.Buffer) as type string in argument to db.Query
I have written a SQL query in buffer.WriteString() but not able to use that buffer in db.Query().

```<code>buffer.WriteString(fmt.Sprintf(`SELECT c.id, c.company_name, ss.start_date, ss.shift_length, ss.bill_rate, ss.ot_hrs, ss.dt_hrs, ts.pay_rate, ts.wc_rate, ts.paid, td.wc
        FROM company c
        JOIN users u1 ON c.id = u1.company_id
        JOIN schedule s ON u1.id = s.user_id
        JOIN schedule_shifts ss ON s.id = ss.schedule_id
        JOIN technician_shifts ts ON ss.id = ts.shift_id
        JOIN users u ON u.id = ts.technician_id
        JOIN technician_details td ON td.user_id = u.id
        JOIN master_technicians mt ON mt.id = u.master_technician_id
        WHERE mt.id = %d AND ts.confirmed = 'yes' AND ts.paid = 'yes'`, masterID))

    if e.Type == "today" {
        buffer.WriteString(fmt.Sprintf(`AND ts.paid_on = CURDATE()`))
    } else if e.Type == "weekly" {
        buffer.WriteString(fmt.Sprintf(`AND ts.paid_on > DATE_SUB(NOW(), INTERVAL 1 WEEK)`))
    } else if e.Type == "monthly" {
        buffer.WriteString(fmt.Sprintf(`AND ts.paid_on > DATE_SUB(NOW(), INTERVAL 1 MONTH)`))
    } else {
        if e.StartDate != "" && e.EndDate != "" {
            if e.StartDate == e.EndDate {
                buffer.WriteString(fmt.Sprintf(`AND ts.paid_on = %s`, e.StartDate))
            } else {
                buffer.WriteString(fmt.Sprintf(`AND ts.paid_on >= %s AND ts.paid_on <= %s`, e.StartDate, e.EndDate))
            }
        }
    }

rows, err := db.Query(buffer)
    if err != nil {
        log.Panic(err.Error())
    }
</code>```

It gives me the error that

cannot use buffer (type bytes.Buffer) as type string in argument to
  db.Query

How can i do that?

答:
The direct answer to your question is provided by the docs, and is simply to use the String() method:

```<code>rows, err := db.Query(buffer.String())
</code>```

Having said that, a buffer probably doesn't make sense here. For building strings, the strings.Builder type is more efficient.

But for your particular use case, building SQL queries this way is dangerous and error-prone. Several suggestions:

NEVER, EVER EVER use string concatenation or Sprintf/Fprintf to insert values into SQL queries. You'll open yourself up to SQL injection attacks. Instead, always use parameterized queries.

Large if/else blocks are error-prone and hard to read. Use a proper switch statement instead.

You can use an SQL query builder, but in your case, you have only one optional portion of the query. Just use standard string concatenation for that.

I've rewritten your code considering the above concerns, and now it looks like this:

```<code>var paidCondition string
args := []interface{}{masterID}
switch (
case e.Type == "today":
    paidCondition = `AND ts.paid_on = CURDATE()`
case e.Type == "weekly":
    paidCondition = `AND ts.paid_on > DATE_SUB(NOW(), INTERVAL 1 WEEK)`
case e.Type == "monthly":
    paidCondition = `AND ts.paid_on > DATE_SUB(NOW(), INTERVAL 1 MONTH)`
case e.StartDate != "" && e.EndDate != "" && e.StartDate == e.EndDate:
    paidCondition = `AND ts.paid_on = ?`
    args = append(args, e.StartDate)
case e.StartDate != "" && e.EndDate != "":
    paidCondition = `AND ts.paid_on >= ? AND ts.paid_on <= ?`
    args = append(args, e.StartDate, e.EndDate)
)

query := `SELECT c.id, c.company_name, ss.start_date, ss.shift_length, ss.bill_rate, ss.ot_hrs, ss.dt_hrs, ts.pay_rate, ts.wc_rate, ts.paid, td.wc
    FROM company c
    JOIN users u1 ON c.id = u1.company_id
    JOIN schedule s ON u1.id = s.user_id
    JOIN schedule_shifts ss ON s.id = ss.schedule_id
    JOIN technician_shifts ts ON ss.id = ts.shift_id
    JOIN users u ON u.id = ts.technician_id
    JOIN technician_details td ON td.user_id = u.id
    JOIN master_technicians mt ON mt.id = u.master_technician_id
    WHERE mt.id = ? AND ts.confirmed = 'yes' AND ts.paid = 'yes' ` + paidCondition

rows, err := db.Query(query, args...)
if err != nil {
    log.Panic(err.Error())
}
</code>```

And finally, a couple other improvements, which are not directly related to your question or my suggested code above:

buffer.WriteString(fmt.Sprintf(...)) is overly verbose. The shorter version is: fmt.Fprintf(buffer,...).

You're using fmt.Sprintf() in several places where no formatting is taking place. Just remove this entirely. For example, replace fmt.Sprintf("AND ts.paid_on = CURDATE()") with simply "AND ts.paid_on = CURDATE()".

Body:
I have written a SQL query in buffer.WriteString() but not able to use that buffer in db.Query().

buffer.WriteString(fmt.Sprintf(`SELECT c.id, c.company_name, ss.start_date, ss.shift_length, ss.bill_rate, ss.ot_hrs, ss.dt_hrs, ts.pay_rate, ts.wc_rate, ts.paid, td.wc
        FROM company c
        JOIN users u1 ON c.id = u1.company_id
        JOIN schedule s ON u1.id = s.user_id
        JOIN schedule_shifts ss ON s.id = ss.schedule_id
        JOIN technician_shifts ts ON ss.id = ts.shift_id
        JOIN users u ON u.id = ts.technician_id
        JOIN technician_details td ON td.user_id = u.id
        JOIN master_technicians mt ON mt.id = u.master_technician_id
        WHERE mt.id = %d AND ts.confirmed = 'yes' AND ts.paid = 'yes'`, masterID))

    if e.Type == "today" {
        buffer.WriteString(fmt.Sprintf(`AND ts.paid_on = CURDATE()`))
    } else if e.Type == "weekly" {
        buffer.WriteString(fmt.Sprintf(`AND ts.paid_on > DATE_SUB(NOW(), INTERVAL 1 WEEK)`))
    } else if e.Type == "monthly" {
        buffer.WriteString(fmt.Sprintf(`AND ts.paid_on > DATE_SUB(NOW(), INTERVAL 1 MONTH)`))
    } else {
        if e.StartDate != "" && e.EndDate != "" {
            if e.StartDate == e.EndDate {
                buffer.WriteString(fmt.Sprintf(`AND ts.paid_on = %s`, e.StartDate))
            } else {
                buffer.WriteString(fmt.Sprintf(`AND ts.paid_on >= %s AND ts.paid_on <= %s`, e.StartDate, e.EndDate))
            }
        }
    }

rows, err := db.Query(buffer)
    if err != nil {
        log.Panic(err.Error())
    }

It gives me the error that

cannot use buffer (type bytes.Buffer) as type string in argument to
  db.Query

How can i do that?

Body:
The direct answer to your question is provided by the docs, and is simply to use the String() method:

rows, err := db.Query(buffer.String())

Having said that, a buffer probably doesn't make sense here. For building strings, the strings.Builder type is more efficient.

But for your particular use case, building SQL queries this way is dangerous and error-prone. Several suggestions:

NEVER, EVER EVER use string concatenation or Sprintf/Fprintf to insert values into SQL queries. You'll open yourself up to SQL injection attacks. Instead, always use parameterized queries.

Large if/else blocks are error-prone and hard to read. Use a proper switch statement instead.

You can use an SQL query builder, but in your case, you have only one optional portion of the query. Just use standard string concatenation for that.

I've rewritten your code considering the above concerns, and now it looks like this:

var paidCondition string
args := []interface{}{masterID}
switch (
case e.Type == "today":
    paidCondition = `AND ts.paid_on = CURDATE()`
case e.Type == "weekly":
    paidCondition = `AND ts.paid_on > DATE_SUB(NOW(), INTERVAL 1 WEEK)`
case e.Type == "monthly":
    paidCondition = `AND ts.paid_on > DATE_SUB(NOW(), INTERVAL 1 MONTH)`
case e.StartDate != "" && e.EndDate != "" && e.StartDate == e.EndDate:
    paidCondition = `AND ts.paid_on = ?`
    args = append(args, e.StartDate)
case e.StartDate != "" && e.EndDate != "":
    paidCondition = `AND ts.paid_on >= ? AND ts.paid_on <= ?`
    args = append(args, e.StartDate, e.EndDate)
)

query := `SELECT c.id, c.company_name, ss.start_date, ss.shift_length, ss.bill_rate, ss.ot_hrs, ss.dt_hrs, ts.pay_rate, ts.wc_rate, ts.paid, td.wc
    FROM company c
    JOIN users u1 ON c.id = u1.company_id
    JOIN schedule s ON u1.id = s.user_id
    JOIN schedule_shifts ss ON s.id = ss.schedule_id
    JOIN technician_shifts ts ON ss.id = ts.shift_id
    JOIN users u ON u.id = ts.technician_id
    JOIN technician_details td ON td.user_id = u.id
    JOIN master_technicians mt ON mt.id = u.master_technician_id
    WHERE mt.id = ? AND ts.confirmed = 'yes' AND ts.paid = 'yes' ` + paidCondition

rows, err := db.Query(query, args...)
if err != nil {
    log.Panic(err.Error())
}

And finally, a couple other improvements, which are not directly related to your question or my suggested code above:

buffer.WriteString(fmt.Sprintf(...)) is overly verbose. The shorter version is: fmt.Fprintf(buffer,...).

You're using fmt.Sprintf() in several places where no formatting is taking place. Just remove this entirely. For example, replace fmt.Sprintf("AND ts.paid_on = CURDATE()") with simply "AND ts.paid_on = CURDATE()".


问:
Merging two multidimensional arrays in Javascript by value
I have two arrays:

```<code>var array1 = [['email1', object1],['email2', object2],['email3', object3],['email4',object4]]
var array2 = [['email1',[['a1','b1']]],['email3',[['a3','b3']]], ['email4',[['a4','b4'],['a4a','b4a']]]
</code>```

I need to merge them by email so the resulting array will look like, without duplicate email:

```<code>var mergedarray =
[['email1', object1, [['a1', 'b1']]],['email2', object2],['email3', object3, ['a3', 'b3']],['email4',object4,[['a4','b4'],['a4a','b4a']]]]
</code>```

My brain hurts looking at those multimultidimensions..Any advice?

答:
```<code>   const hash = new Map();

   for(const [email, ...rest] of [...array1, ...array2]) {
     if(hash.has(email)) {
       hash.get(email).push(...rest);
     } else {
        hash.set(email, [email, ...rest]);
    }
  }

  const result = [...hash.values()];
</code>```

Body:
I have two arrays:

var array1 = [['email1', object1],['email2', object2],['email3', object3],['email4',object4]]
var array2 = [['email1',[['a1','b1']]],['email3',[['a3','b3']]], ['email4',[['a4','b4'],['a4a','b4a']]]

I need to merge them by email so the resulting array will look like, without duplicate email:

var mergedarray =
[['email1', object1, [['a1', 'b1']]],['email2', object2],['email3', object3, ['a3', 'b3']],['email4',object4,[['a4','b4'],['a4a','b4a']]]]

My brain hurts looking at those multimultidimensions..Any advice?


问:
Create a CSV file in python
I would like to copy a specific structure of a CSV file and add my own information to it. The file I would like to copy looks like:

```<code>ID      file_name coordinates_X coordinates_Y height width
034033  img/1.jpg 0             0             512    512
021364  img/2.jpg 0             0             512    512
...     ...       ...           ...           ...    ...
</code>```

I would like to create a similar file. The code I have so far:

```<code>dir_ = ... # my path
list_items =  #my list
with open('new.csv', 'w') as csv_file:
lines = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for file in list_items:
    lines.writerow(file+','+ dir_+ file +','+ str(0)+','+ str(0)+','+ str(256)+','+ str(256))
    print (dir_ + file)
</code>```

That approach seems that writes every single character in a different cell. I would like to write in each cell one string instead. How can I do so?

答:
Pass a list to writerow

Ex:

```<code>dir_ = ... # my path
list_items =  #my list
with open('new.csv', 'w') as csv_file:
    lines = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for file in list_items:
        lines.writerow([file, dir_+ file, str(0), str(0), str(256),str(256)])
        print (dir_ + file)
</code>```

Title: Create a CSV file in python

Body:
I would like to copy a specific structure of a CSV file and add my own information to it. The file I would like to copy looks like:

ID      file_name coordinates_X coordinates_Y height width
034033  img/1.jpg 0             0             512    512
021364  img/2.jpg 0             0             512    512
...     ...       ...           ...           ...    ...

I would like to create a similar file. The code I have so far:

dir_ = ... # my path
list_items =  #my list
with open('new.csv', 'w') as csv_file:
lines = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for file in list_items:
    lines.writerow(file+','+ dir_+ file +','+ str(0)+','+ str(0)+','+ str(256)+','+ str(256))
    print (dir_ + file)

That approach seems that writes every single character in a different cell. I would like to write in each cell one string instead. How can I do so?

Body:
Pass a list to writerow

Ex:

dir_ = ... # my path
list_items =  #my list
with open('new.csv', 'w') as csv_file:
    lines = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for file in list_items:
        lines.writerow([file, dir_+ file, str(0), str(0), str(256),str(256)])
        print (dir_ + file)


问:
Passing an object's string value to component using a button Angular
In my html template of my component 'a', I have a button which is used to navigate to an other component :

```<code><button nbButton status="info" class="left" [routerLink]="['/centers', center.id, 'prices']">PRICES</button>
</code>```

So clicking on this button made me move to an other component 'b'.

In the component 'a' I have a private object variable, which contains a string value currenciesAccepted, basically :myObject.currenciesAccepted.

In the component 'b', I need this string value, so I need to pass it when I click on the button, to navigate from the component 'a' to the component 'b'.

答: You can add [queryParams]='{"obj":myObject.currenciesAccepted}' to the button, this will pass the string in query params

Body:
In my html template of my component 'a', I have a button which is used to navigate to an other component :

<button nbButton status="info" class="left" [routerLink]="['/centers', center.id, 'prices']">PRICES</button>

So clicking on this button made me move to an other component 'b'.

In the component 'a' I have a private object variable, which contains a string value currenciesAccepted, basically :myObject.currenciesAccepted.

In the component 'b', I need this string value, so I need to pass it when I click on the button, to navigate from the component 'a' to the component 'b'.


问:
Calling ActionScript from Python. Is that possible?
If swf file is embedded in html it is easy to call ActionScript methods via ExternalInterface using JavaScript.
Now I want to use the swf file outside of a browser and still be able to access its methods, but now I want to use Python to call ActionScript. Is it possible?
There is so little information about it in the Internet.
Probably I can use AMF (pyAmf) for this, can I?

Thanks in advance.

答: Your swf can listen for connections with Socket, acting like a server. ByteArray.readObject can read object in AMF format from message bytes, so you can encode method name and arguments in object.</p>


问:
GitHub social media image is not refreshed on update
I've changed the social media image of my GitHub repository, but when I try to share it in facebook and it displays the old image as I've never updated it in the first place. The image can be updated by going to your repo -> Settings -> Social preview. I dowloaded the template and used it to create an image, but did not remove the red bars on the sides. When I shared it looked like crap, so I removed the red bars and made them white. Now my phone does not want to display the new image when I share it on facebook.

Is this a browser related cache issue or simply the GitHub feature does not work? What am I doing wrong?

答: The problem was solved when I made an URL re-scrape as @04FS suggested. I had to open the facebook page with a regular browser, not the dedicated app, follow the link he provided and paste the URL in there. In the option Time Scraped was set to yesterday at 11:32, which means that FB caches internally the URL result. After hitting the button Scrape Again, the social media picture appeared correctly without the red borders.


问:
How to I adjust the height of a PlotWidget?
I am developing a spectrum analyzer GUI, and I am plotting an FFT using matplotlib.pyplot, and a waterfall display beneath it using PyQtGraph. The waterfall display is created using an ImageItem, which is added to a PlotWidget, which is then added beneath the FFT in a QVBoxLayout. This is the result:

I had to use PyQtGraph for the Waterfall display because MatPlotLib was unable to plot the data quickly enough. Now, I cannot figure out how to adjust the size of the PlotWidget so that the two graphs are approximately the same size. The ImageItem is being generated using

```<code>ImageItem.setImage(dataArray)
</code>```

Suggestions?

答:
you should use scale in first update    </p>

```<code>counter += 1
    if counter == 1:
        ImageItem = pg.ImageItem()
        ImageItem.scale((data_storage.x[-1] - data_storage.x[0]) / len(data_storage.x), 1)
</code>```

Body:
I am developing a spectrum analyzer GUI, and I am plotting an FFT using matplotlib.pyplot, and a waterfall display beneath it using PyQtGraph. The waterfall display is created using an ImageItem, which is added to a PlotWidget, which is then added beneath the FFT in a QVBoxLayout. This is the result:

I had to use PyQtGraph for the Waterfall display because MatPlotLib was unable to plot the data quickly enough. Now, I cannot figure out how to adjust the size of the PlotWidget so that the two graphs are approximately the same size. The ImageItem is being generated using

ImageItem.setImage(dataArray)

Suggestions?

Body:
you should use scale in first update

counter += 1
    if counter == 1:
        ImageItem = pg.ImageItem()
        ImageItem.scale((data_storage.x[-1] - data_storage.x[0]) / len(data_storage.x), 1)


问:
Ruby on Rails [heroku] git push heroku master error
I am trying to upload my web app on heroku, but the following error occurs.

(I'm coding with cloud 9 IDE)

```<code>$ git push heroku master
.....
remote: -----> Installing node-v10.14.1-linux-x64
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        Yarn executable was not detected in the system.
remote:        Download Yarn at https://yarnpkg.com/en/docs/install
remote:        I, [2019-05-22T02:13:47.373334 #1766]  INFO -- : Writing
/tmp/build_fcc84922ee6a02bfc05a163c871d0548/public/assets/noimage-
3aa3997354b4e9c37f379deb61626f55ade493078d1b42dcefe4a3ccbed34106.jpg
remote:        rake aborted!
remote:        ExecJS::RuntimeError: SyntaxError: Unexpected character '`'
remote:        JS_Parse_Error.get ((execjs):3538:621)
remote:        (execjs):4060:48
remote:        (execjs):1:102
.....
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.
</code>```

First of all, It says that "there Yarn executable was not detected in the system", but it is properly downloaded if I check it with yarn -v.

Also, ExecJS :: RuntimeError: SyntaxError: Unexpected character '`' error seems to be that es6 is not recognized, as a solution

config.assets.js_compressor =: uglifier

config.assets.js_compressor = Uglifier.new (harmony: true)

Changed to This seems to be able to read es6. But the above error still persists.

Also, if I run 'rake assets: precompile RAILS_ENV = production' on the console, it runs normally without error.

Thanks.

答:
Try to add this gem in your gem file.

```<code>gem 'therubyracer'
</code>```

Try this link:

Syntax error when deploying Rails app to Heroku: ExecJS::RuntimeError: SyntaxError: Unexpected character

Body:
I am trying to upload my web app on heroku, but the following error occurs.

(I'm coding with cloud 9 IDE)

$ git push heroku master
.....
remote: -----> Installing node-v10.14.1-linux-x64
remote: -----> Detecting rake tasks
remote: -----> Preparing app for Rails asset pipeline
remote:        Running: rake assets:precompile
remote:        Yarn executable was not detected in the system.
remote:        Download Yarn at https://yarnpkg.com/en/docs/install
remote:        I, [2019-05-22T02:13:47.373334 #1766]  INFO -- : Writing
/tmp/build_fcc84922ee6a02bfc05a163c871d0548/public/assets/noimage-
3aa3997354b4e9c37f379deb61626f55ade493078d1b42dcefe4a3ccbed34106.jpg
remote:        rake aborted!
remote:        ExecJS::RuntimeError: SyntaxError: Unexpected character '`'
remote:        JS_Parse_Error.get ((execjs):3538:621)
remote:        (execjs):4060:48
remote:        (execjs):1:102
.....
remote:  !
remote:  !     Precompiling assets failed.
remote:  !
remote:  !     Push rejected, failed to compile Ruby app.

First of all, It says that "there Yarn executable was not detected in the system", but it is properly downloaded if I check it with yarn -v.

Also, ExecJS :: RuntimeError: SyntaxError: Unexpected character '`' error seems to be that es6 is not recognized, as a solution

config.assets.js_compressor =: uglifier

config.assets.js_compressor = Uglifier.new (harmony: true)

Changed to This seems to be able to read es6. But the above error still persists.

Also, if I run 'rake assets: precompile RAILS_ENV = production' on the console, it runs normally without error.

Thanks.

Body:
Try to add this gem in your gem file.

gem 'therubyracer'

Try this link:

Syntax error when deploying Rails app to Heroku: ExecJS::RuntimeError: SyntaxError: Unexpected character


问:
Should ANN results change based on output?
Changing the number of output variables reducing accuracy of the model, although architecture of the NN remains the same (ie same no of input and hidden neurons, same activation func, same data used for learning).

Hi, Ive run a NN with shape (22,20,8) and received an rms value of 5.048 and R2 of 0.925, with one of the output variables predicting to 98% accuracy on new data.
However Ive deceided that i dont need all 8 outputs (only 4 are of interest) so ive run the model again with shape (22,20,4) and received an rms value of 8.20, R2 of 0.62 and accuarcy of a variable at 75%.

If im only changing the output, how does this effect the accuracy of the model ive already created? Im using the same data, so surely the relationship learned from the model will be the same and therefore predictions on the same remaining 4 variables will be the same?
How come changing the output changes the model so much?
Thanks

答:
If I'm only changing the output, how does this effect the accuracy of
  the model I've already created?

As form your question, you must have realized that the model accuracy changes. This behavior is as expected, because you are changing the model.

When you retrain the model with 4 outputs instead of 8 outputs, the relationships learnt are different from the model with 8 outputs.

Changing even small factors like the initial weights and bias, the random states of various initializes and any other tune-able parameters, will for sure result in a change in accuracy.

In you case, a change in the architecture (big change) will and has created a big impact on the results.


问:
How to add spinner/loader in yii2 php
I want to add a spinner/loader in one of my forms. The scenario is simple: When I hit the create button then it will show a spinner/loader. On hitting the create button a call to a web-service is made so the spinner/loader will show from call start to call end.

Below is my controller:

```<code>$m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);
$msn = $m->meter_serial; // current selected meter serial number is saved

$date_time = str_replace(' ', 'T', date('Y-m-d H:i:s')); // current date time

$api_url = 'http://xx.xxx.xxx.xxx:7000/api/meters/GetByMsn/' . $msn . '/' .$date_time; // my base URL

$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization:key'));

$curl_response = curl_exec($curl);
$json = json_decode($curl_response);
$meter_alive = $json->data->Response;
.
.
.
.
// my other code that is saving data
.
.
.
.
return $this->render('create', ['model' => $model,]);
</code>```

The submit button is below:

```<code><div class="form-group">
   <?= Html::submitButton($model->isNewRecord ? 'Verify Communication' : 'Update', ['id'=> 'spin','name'=>'create','class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success']) ?>

</div>
</code>```

As told above when I press the Verify Communication button a call is made to the web-service and during this time I want to show a spinner/loader.

For creating/showing a spinner/loader I have searched many articles.

Show Loading

Kartik Spinner

Submit Spinner

Yii2 Model Loader

Yii2 Jquery Loading

But none of the above articles have mentioned the full implementation details. Although I have tried each and every step mentioned in the articles.

Any help would be highly appreciated.

答:
Instead of on the submit button why not put the loader on each page load. This can be done by making changes in main layout.

```<code><style>
        /*loader css*/

#loader {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 1;
  width: 150px;
  height: 150px;
  margin: -75px 0 0 -75px;
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Add animation to "page content" */
.animate-bottom {
  position: relative;
  -webkit-animation-name: animatebottom;
  -webkit-animation-duration: 1s;
  animation-name: animatebottom;
  animation-duration: 1s
}

@-webkit-keyframes animatebottom {
  from { bottom:-100px; opacity:0 }
  to { bottom:0px; opacity:1 }
}

@keyframes animatebottom {
  from{ bottom:-100px; opacity:0 }
  to{ bottom:0; opacity:1 }
}

</style>
</code>```

Add script for function.

```<code><script>
var myVar;

function myFunction() {
  myVar = setTimeout(showPage, 0000);
}

function showPage() {
  document.getElementById("loader").style.display = "none";
  document.getElementById("container").style.display = "block";
}
</script>
</code>```

Finally, call the function by binding onload function with body.

```<code>    <body onload="myFunction()">
        <div id="loader"></div>
<section id="container" style="display:none;" class="animate-bottom">
</section>
    </body>
</code>```

Title: How to add spinner/loader in yii2 php

Body:
I want to add a spinner/loader in one of my forms. The scenario is simple: When I hit the create button then it will show a spinner/loader. On hitting the create button a call to a web-service is made so the spinner/loader will show from call start to call end.

Below is my controller:

$m = MetersInventoryStore::findOne($_REQUEST['selected_meters']);
$msn = $m->meter_serial; // current selected meter serial number is saved

$date_time = str_replace(' ', 'T', date('Y-m-d H:i:s')); // current date time

$api_url = 'http://xx.xxx.xxx.xxx:7000/api/meters/GetByMsn/' . $msn . '/' .$date_time; // my base URL

$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization:key'));

$curl_response = curl_exec($curl);
$json = json_decode($curl_response);
$meter_alive = $json->data->Response;
.
.
.
.
// my other code that is saving data
.
.
.
.
return $this->render('create', ['model' => $model,]);

The submit button is below:

   <?= Html::submitButton($model->isNewRecord ? 'Verify Communication' : 'Update', ['id'=> 'spin','name'=>'create','class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-success']) ?>

As told above when I press the Verify Communication button a call is made to the web-service and during this time I want to show a spinner/loader.

For creating/showing a spinner/loader I have searched many articles.

Show Loading

Kartik Spinner

Submit Spinner

Yii2 Model Loader

Yii2 Jquery Loading

But none of the above articles have mentioned the full implementation details. Although I have tried each and every step mentioned in the articles.

Any help would be highly appreciated.

Body:
Instead of on the submit button why not put the loader on each page load. This can be done by making changes in main layout.

<style>
        /*loader css*/

#loader {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 1;
  width: 150px;
  height: 150px;
  margin: -75px 0 0 -75px;
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* Add animation to "page content" */
.animate-bottom {
  position: relative;
  -webkit-animation-name: animatebottom;
  -webkit-animation-duration: 1s;
  animation-name: animatebottom;
  animation-duration: 1s
}

@-webkit-keyframes animatebottom {
  from { bottom:-100px; opacity:0 }
  to { bottom:0px; opacity:1 }
}

@keyframes animatebottom {
  from{ bottom:-100px; opacity:0 }
  to{ bottom:0; opacity:1 }
}

</style>

Add script for function.

<script>
var myVar;

function myFunction() {
  myVar = setTimeout(showPage, 0000);
}

function showPage() {
  document.getElementById("loader").style.display = "none";
  document.getElementById("container").style.display = "block";
}
</script>

Finally, call the function by binding onload function with body.

    <body onload="myFunction()">
        <div id="loader"></div>
<section id="container" style="display:none;" class="animate-bottom">
</section>
    </body>


问:
I have downloaded a lambda function from my aws account(deployment package and SAM file) , how do I run this function locally on Intellij Idea?
The lambda function is not functioning as expected and I would like to debug it on IDE , Intellij IDEA . I have the source code , libraries ( as a part of the downloaded deployment package) and template.yaml (SAM file).
I tried to do some research on how to run this function locally , in vain. Any guidance is appreciated.</p>

答:
One of the ways you can test your AWS Lambda code locally,
is by using the ServerlessFramework and the Serverless-Offline plugin

Using Serverless Framework will also help you for creating the Infra you may require for deploying the functions to any of the major Cloud vendors including AWS.

You will need to maintain a serverless.yaml file which gets created for you when you create a serverless framework template.

You can follow these reference links -

 1. https://serverless.com/framework/docs/providers/aws/guide/quick-start/

 2. https://serverless.com/framework/docs/providers/aws/guide/serverless.yml/


问:
How to store ArrayList of Enum in RoomDatabase
my Question is how to store

```<code>List<Enum>
</code>```

in RoomDatabase,
so far I find no answer for that.

答:
Let me show the way of persisting/retrieving it using kotlin.

What restrictions do we have during the operation?

We store enum list as string field in database, so we can't have efficient select or search in database based on it

We have to serialize each enum value to string and deserialize it back

we can't base the behavior on ordinal field to prevent mistakes due to extending the enum in the future, so we need to have a constant field which represents each enum value

we can't base on default toString method of list to string, because it may depend on environment we exactly use

So proper implementation in my opinion will look like:

Create Enumerable interface which all enum classes persisted to db should implement

Each enum class should have creation method with passed serialized parameter to it which restores enum value

Create kotlin extension to serialize/deserialize list of enums

Create type converters for each type of enum

So, the Enumerable interface:

```<code>/** marks the enum with custom int code for each value */
interface Enumerable {
    val code: Int
}
</code>```

enum example:

```<code>enum class PaymentSystemEntity constructor(
    override val code: Int
) : Enumerable {
    VISA(1),
    MASTERCARD(2),
    UNKNOWN(0);

    companion object {
        fun parseFromCode(code: Int): PaymentSystemEntity = values()
            .firstOrNull { it.code == code } ?: UNKNOWN
    }

}
</code>```

serialization extensions:

```<code>fun <T> List<T>.asString(): String where T : Enum<T>, T : Enumerable = this
    .map { it.code }
    .joinToString(separator = ",")

fun <T> String.toEnumList(creator: (code: Int) -> T): List<T> where T : Enum<T>, T : Enumerable = this
    .split(',')
    .map { it.toInt() }
    .map { creator(it) }
</code>```

Sample type converter for enum:

```<code>class PaymentSystemTypeConverter {

    @TypeConverter
    fun paymentSystemsToString(value: List<@JvmSuppressWildcards PaymentSystemEntity>): String =
         value.asString()

    @TypeConverter
    fun stringToPaymentSystems(value: String): List<@JvmSuppressWildcards PaymentSystemEntity> =
        value.toEnumList { PaymentSystemEntity.parseFromCode(it) }

}
</code>```

You may have other types of collections implemented in a same way

Body:
my Question is how to store

List<Enum>

in RoomDatabase,
so far I find no answer for that.

Body:
Let me show the way of persisting/retrieving it using kotlin.

What restrictions do we have during the operation?

We store enum list as string field in database, so we can't have efficient select or search in database based on it

We have to serialize each enum value to string and deserialize it back

we can't base the behavior on ordinal field to prevent mistakes due to extending the enum in the future, so we need to have a constant field which represents each enum value

we can't base on default toString method of list to string, because it may depend on environment we exactly use

So proper implementation in my opinion will look like:

Create Enumerable interface which all enum classes persisted to db should implement

Each enum class should have creation method with passed serialized parameter to it which restores enum value

Create kotlin extension to serialize/deserialize list of enums

Create type converters for each type of enum

So, the Enumerable interface:

/** marks the enum with custom int code for each value */
interface Enumerable {
    val code: Int
}

enum example:

enum class PaymentSystemEntity constructor(
    override val code: Int
) : Enumerable {
    VISA(1),
    MASTERCARD(2),
    UNKNOWN(0);

    companion object {
        fun parseFromCode(code: Int): PaymentSystemEntity = values()
            .firstOrNull { it.code == code } ?: UNKNOWN
    }

}

serialization extensions:

fun <T> List<T>.asString(): String where T : Enum<T>, T : Enumerable = this
    .map { it.code }
    .joinToString(separator = ",")

fun <T> String.toEnumList(creator: (code: Int) -> T): List<T> where T : Enum<T>, T : Enumerable = this
    .split(',')
    .map { it.toInt() }
    .map { creator(it) }

Sample type converter for enum:

class PaymentSystemTypeConverter {

    @TypeConverter
    fun paymentSystemsToString(value: List<@JvmSuppressWildcards PaymentSystemEntity>): String =
         value.asString()

    @TypeConverter
    fun stringToPaymentSystems(value: String): List<@JvmSuppressWildcards PaymentSystemEntity> =
        value.toEnumList { PaymentSystemEntity.parseFromCode(it) }

}

You may have other types of collections implemented in a same way


问:
How to retrieve paginated children in ascending or descending order in Firebase?
Suppose I'm using firebase for a commenting system and I want to retrieve the comments for a given topic, but there are so many comments in one topic that I don't want to retrieve them all at once. I also want the newest comments to be displayed on top.

It seems that the only way to display firebase records in reverse order is to retrieve them all and then iterate over them in reverse.

This could get very unwieldy on large datasets, especially for mobile clients.

Is there any better way? What is the generic and preferred solution to query paginated data from Firebase, in ascending or descending order?

答:
Here is solution from firebase docs:

Query query = cities.orderBy("name", Direction.DESCENDING).limit(3);

https://firebase.google.com/docs/firestore/query-data/order-limit-data


问:
Fetch defined_names from a .xls file
I'm trying to fetch tagged data from a .xls file.

I am able to fetch the tagged data from .xlsx file using Openpyxl, like this: [dn for dn in wb.defined_names.definedName]

But openpyxl does not support .xls format and I need to get the defined_names from .xls file as well.

Is there any library that can read .xls and return the defined_names in the file?

答:
check xlrd package.

Here is the relevant part of the docs - Named references, constants, formulas, and macros

Title: Fetch defined_names from a .xls file


问:
Why does Python return a "TypeError" when passing a column with string data to the lookup() method from the "us" package?
I want to correct respective datatimes to their timezones, using the package "us" to retrieve the timezone and pandas' "tz_covert()" method to apply the correction, but am getting an error "TypeError: expected string or bytes-like object"

I have tried casting the respective column to a type string with df['StateCode'] = df['StateCode'].astype(str)

posting_time = (
    df
    .loc[:, ['shipment_id', 'courier_id', 'posted_at','StateCode']]
    .drop_duplicates(subset=['shipment_id','courier_id'], keep='first')
    .assign(
        posted_at_dt=lambda x: pd.to_datetime(x['posted_at'])\
        .dt.tz_localize(pytz.utc)\
        .dt.tz_convert(us.states.lookup(x['StateCode']).capital_tz)
    )
)
```

<p>My dataframe looks like: </p>

<pre class="lang-py prettyprint-override"><code>shipment_id courier_id  posted_at   StateCode
0   14      228898  2019-02-19 13:18:55 MI
1   91919   196838  2019-01-19 19:29:02 TX
2   92187   196838  2019-01-19 19:29:28 TX
3   92736   196838  2019-01-19 19:29:46 TX
4   92760   196838  2019-01-19 19:29:59 TX
</code>```

I have narrowed the problem down to:

us.states.lookup(x['StateCode']).capital_tz

```

But "x['StateCode']" should be a string type, so I'm not sure why I'm getting "TypeError: expected string or bytes-like object" ?

答:
Use list comprehension or apply function wor working per rows of DataFrame:

```<code>posting_time = (
    df
    .loc[:, ['shipment_id', 'courier_id', 'posted_at','StateCode']]
    .drop_duplicates(subset=['shipment_id','courier_id'], keep='first')
    .assign(
        posted_at_dt=lambda x: pd.to_datetime(x['posted_at'])\
        .dt.tz_localize(pytz.utc)
    )
)

posting_time['posted_at_dt'] = [a.tz_convert(us.states.lookup(b).capital_tz)
                               for a, b in zip(posting_time['posted_at_dt'],
                                               posting_time['StateCode'])]
print (posting_time)
   shipment_id  courier_id            posted_at StateCode  \
0           14      228898  2019-02-19 13:18:55        MI
1        91919      196838  2019-01-19 19:29:02        TX
2        92187      196838  2019-01-19 19:29:28        TX
3        92736      196838  2019-01-19 19:29:46        TX
4        92760      196838  2019-01-19 19:29:59        TX

                posted_at_dt
0  2019-02-19 08:18:55-05:00
1  2019-01-19 13:29:02-06:00
2  2019-01-19 13:29:28-06:00
3  2019-01-19 13:29:46-06:00
4  2019-01-19 13:29:59-06:00
</code>```

Or:

```<code>posting_time['posted_at_dt']  =  posting_time.apply(lambda x: x['posted_at_dt'].tz_convert(us.states.lookup(x['StateCode']).capital_tz), axis=1)
</code>```

Body:
I want to correct respective datatimes to their timezones, using the package "us" to retrieve the timezone and pandas' "tz_covert()" method to apply the correction, but am getting an error "TypeError: expected string or bytes-like object"

I have tried casting the respective column to a type string with df['StateCode'] = df['StateCode'].astype(str)

posting_time = (
    df
    .loc[:, ['shipment_id', 'courier_id', 'posted_at','StateCode']]
    .drop_duplicates(subset=['shipment_id','courier_id'], keep='first')
    .assign(
        posted_at_dt=lambda x: pd.to_datetime(x['posted_at'])\
        .dt.tz_localize(pytz.utc)\
        .dt.tz_convert(us.states.lookup(x['StateCode']).capital_tz)
    )
)

My dataframe looks like:

shipment_id courier_id  posted_at   StateCode
0   14      228898  2019-02-19 13:18:55 MI
1   91919   196838  2019-01-19 19:29:02 TX
2   92187   196838  2019-01-19 19:29:28 TX
3   92736   196838  2019-01-19 19:29:46 TX
4   92760   196838  2019-01-19 19:29:59 TX

I have narrowed the problem down to:

us.states.lookup(x['StateCode']).capital_tz

But "x['StateCode']" should be a string type, so I'm not sure why I'm getting "TypeError: expected string or bytes-like object" ?

Body:
Use list comprehension or apply function wor working per rows of DataFrame:

posting_time = (
    df
    .loc[:, ['shipment_id', 'courier_id', 'posted_at','StateCode']]
    .drop_duplicates(subset=['shipment_id','courier_id'], keep='first')
    .assign(
        posted_at_dt=lambda x: pd.to_datetime(x['posted_at'])\
        .dt.tz_localize(pytz.utc)
    )
)

posting_time['posted_at_dt'] = [a.tz_convert(us.states.lookup(b).capital_tz)
                               for a, b in zip(posting_time['posted_at_dt'],
                                               posting_time['StateCode'])]
print (posting_time)
   shipment_id  courier_id            posted_at StateCode  \
0           14      228898  2019-02-19 13:18:55        MI
1        91919      196838  2019-01-19 19:29:02        TX
2        92187      196838  2019-01-19 19:29:28        TX
3        92736      196838  2019-01-19 19:29:46        TX
4        92760      196838  2019-01-19 19:29:59        TX

                posted_at_dt
0  2019-02-19 08:18:55-05:00
1  2019-01-19 13:29:02-06:00
2  2019-01-19 13:29:28-06:00
3  2019-01-19 13:29:46-06:00
4  2019-01-19 13:29:59-06:00

Or:

posting_time['posted_at_dt']  =  posting_time.apply(lambda x: x['posted_at_dt'].tz_convert(us.states.lookup(x['StateCode']).capital_tz), axis=1)