问:
can i Highlight specific days - like all mondays tuesdays etc in datepicker js
I am trying to highlight days in datepicker. I am using the folowwing code to highlight them.BUt this highlights all the days of the datepicker.</p>

```<code>  dates.data = ['0','1','2'] // days of week
 beforeShowDay: function (date) {
     if($.inArray(date.getDay(), dates.data)) {
          // if it is return the following.
              return [true, 'ui-state-error', 'tooltip text'];
              } else {
                             // default
               return [true, '', ''];
              }
}
</code>```

答:
you can use bdeforeShowDay function with highlighter css.

var highlightDays = ["2020-2-21","2020-2-23","2020-2-11","2020-3-21",];
var date = new Date();
jQuery(document).ready(function() {
    $( "#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        beforeShowDay: function(date) {
            var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
            for (i = 0; i < highlightDays.length; i++) {
                if($.inArray(y + '-' + (m+1) + '-' + d,highlightDays) != -1) {
                    return [true, 'highlight', ''];
                }
            }
            return [true];
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight{
       background-color: red;
   }</code>```

    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

Date: <input type="text" id="datepicker" />

```

Body:
I am trying to highlight days in datepicker. I am using the folowwing code to highlight them.BUt this highlights all the days of the datepicker.

  dates.data = ['0','1','2'] // days of week
 beforeShowDay: function (date) {
     if($.inArray(date.getDay(), dates.data)) {
          // if it is return the following.
              return [true, 'ui-state-error', 'tooltip text'];
              } else {
                             // default
               return [true, '', ''];
              }
}

Body:
you can use bdeforeShowDay function with highlighter css.

var highlightDays = ["2020-2-21","2020-2-23","2020-2-11","2020-3-21",];
var date = new Date();
jQuery(document).ready(function() {
    $( "#datepicker").datepicker({
        dateFormat: 'yy-mm-dd',
        beforeShowDay: function(date) {
            var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
            for (i = 0; i < highlightDays.length; i++) {
                if($.inArray(y + '-' + (m+1) + '-' + d,highlightDays) != -1) {
                    return [true, 'highlight', ''];
                }
            }
            return [true];
        }
    });
});

.highlight{
       background-color: red;
   }

<html lang="en">
  <head>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
  </head>
  <body>
    <p>Date: <input type="text" id="datepicker" /></p>
  </body>
</html>


来源: stackexchange

问:
JavaScript Redirect not working with ?fbclid=
the community!
I'm going through some issues. the redirection feature doesn't work well when I try to post the link on the Facebook platform. in general, the redirection only works outside facebook community. when I click on the shared link on Facebook automatically set this parameter at the end of URL ?fbclid=

example : https://myblog.blogspot.com/go/fb?fbclid=

but when I put the link directly on the browser works properly

here is my code

```<code> <script language='javascript'>

    //<![CDATA[
    var key = window.location.href.split("go/")[1].replace("/","")
    var urls={
     'fb':'https://www.facebook.com',
    }
    if(key){
     if(urls[key]){
     window.location.href=urls[key]
     }else{
     document.write("'"+key+"' not found ");
     }
    }
    //]]>
    </script>
</code>```

答:
Use window.location.pathname instead of window.location.href.

```

ContentLicense: CC BY-SA 4.0

Body:
Use window.location.pathname instead of window.location.href.

<script>
//<![CDATA[
  var key = window.location.pathname.split("go/")[1].replace("/","")
  var urls={
    'fb':'https://www.facebook.com',
  }
  if(key){
    if(urls[key]){
      window.location.href=urls[key]
    } else {
      document.write("'"+key+"' not found ");
    }
  }
//]]>
</script>


问:
R Repeat Rows Data Table
```<code>library(data.table)
dataHAVE=data.frame("student"=c(1,2,3),
                    "score" = c(10,11,12),
                "count"=c(4,1,2))

dataWANT=data.frame("student"=c(1,1,1,1,2,3,3),
                    "score"=c(10,10,10,10,11,12,12),
                    "count"=c(4,4,4,4,1,2,2))

setDT(dataHAVE)dataHAVE[rep(1:.N,count)][,Indx:=1:.N,by=student]
</code>```

I have data 'dataHAVE' and seek to produce 'dataWANT' that basically copies each 'student' 'count' number of times as shown in 'dataWANT'. I try doing this as shown above in data.table as this is the solution I seek but get error

Error: unexpected symbol in "setDT(dat)dat"

and I cannot resolve thank you so much.

答:
Here is a base R solution

```<code>dataWANT<-do.call(rbind,
                  c(with(dataHAVE,rep(split(dataHAVE,student),count)),
                    make.row.names = FALSE))
</code>```

such that

```<code>> dataWANT
  student score count
1       1    10     4
2       1    10     4
3       1    10     4
4       1    10     4
5       2    11     1
6       3    12     2
7       3    12     2
</code>```

Title: R Repeat Rows Data Table

Body:
library(data.table)
dataHAVE=data.frame("student"=c(1,2,3),
                    "score" = c(10,11,12),
                "count"=c(4,1,2))

dataWANT=data.frame("student"=c(1,1,1,1,2,3,3),
                    "score"=c(10,10,10,10,11,12,12),
                    "count"=c(4,4,4,4,1,2,2))

setDT(dataHAVE)dataHAVE[rep(1:.N,count)][,Indx:=1:.N,by=student]

I have data 'dataHAVE' and seek to produce 'dataWANT' that basically copies each 'student' 'count' number of times as shown in 'dataWANT'. I try doing this as shown above in data.table as this is the solution I seek but get error

Error: unexpected symbol in "setDT(dat)dat"

and I cannot resolve thank you so much.

Body:
Here is a base R solution

dataWANT<-do.call(rbind,
                  c(with(dataHAVE,rep(split(dataHAVE,student),count)),
                    make.row.names = FALSE))

such that

> dataWANT
  student score count
1       1    10     4
2       1    10     4
3       1    10     4
4       1    10     4
5       2    11     1
6       3    12     2
7       3    12     2


问:
Popper.js not getting installed
I recently created an angular project and am trying to install popper.js but not getting installed.

```<code>ng new <<project>>
cd <<project>>
npm install popper --save
</code>```

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0

(node_modules\rijs.resdir\node_modules\chokidar\node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for

fsevents@1.2.11: wanted {"os":"darwin","arch":"any"} (current:

{"os":"win32","arch":"x64"}) npm ERR! code ENOENT npm ERR! syscall

spawn git npm ERR! path git npm ERR! errno ENOENT npm ERR! enoent

Error while executing: npm ERR! enoent undefined ls-remote -h -t

ssh://git@github.com/pemrouz/buble.git npm ERR! enoent npm ERR! enoent

npm ERR! enoent spawn git ENOENT npm ERR! enoent This is related to

npm not being able to find a file. npm ERR! enoent npm ERR! A complete

log of this run can be found in: npm ERR! C:\Users\Mukesh

Lekhrajani\AppData\Roaming\npm-cache_logs\2020-02-19T10_09_53_537Z-debug.log

How can I install popperjs / popper.js using npm?

答:
As per their docs, popperjs should be installed using:

```<code>npm i @popperjs/core
</code>```

or it you can use their CDN for runtime downloading by placing the script call in the ... tag of your index.html:

```<code><script src="https://unpkg.com/@popperjs/core@2"></script>
</code>```

https://github.com/popperjs/popper-core

Title: Popper.js not getting installed

Body:
I recently created an angular project and am trying to install popper.js but not getting installed.

ng new <<project>>
cd <<project>>
npm install popper --save

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0

(node_modules\rijs.resdir\node_modules\chokidar\node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for

fsevents@1.2.11: wanted {"os":"darwin","arch":"any"} (current:

{"os":"win32","arch":"x64"}) npm ERR! code ENOENT npm ERR! syscall

spawn git npm ERR! path git npm ERR! errno ENOENT npm ERR! enoent

Error while executing: npm ERR! enoent undefined ls-remote -h -t

ssh://git@github.com/pemrouz/buble.git npm ERR! enoent npm ERR! enoent

npm ERR! enoent spawn git ENOENT npm ERR! enoent This is related to

npm not being able to find a file. npm ERR! enoent npm ERR! A complete

log of this run can be found in: npm ERR! C:\Users\Mukesh

Lekhrajani\AppData\Roaming\npm-cache_logs\2020-02-19T10_09_53_537Z-debug.log

How can I install popperjs / popper.js using npm?

Body:
As per their docs, popperjs should be installed using:

npm i @popperjs/core

or it you can use their CDN for runtime downloading by placing the script call in the <HEAD>...</HEAD> tag of your index.html:

<script src="https://unpkg.com/@popperjs/core@2"></script>

https://github.com/popperjs/popper-core


问:
How to save command line file as .txt file every time. In CMD need to display the speedtest output save the those command line as .txt file
This is the program as given below

import os
import time

index=0

file=open("out_{index}.txt", 'a')

while True:

ps=os.system(f"speedtest.exe")

file.append(ps)

index+=1

time.sleep(4)

答:
I believe it is file.write() and not file.append().

I think you want to write to a new file every time.

I  would do this.

```<code>import time
import os
index = 0
while True:
    ps = os.system("speedtest.exe")
    with open(f"out_{index}.txt", 'w+') as f:
        f.write(ps)
    index += 1
time.sleep(4)
</code>```

However, if you want to write in the same file.

I  would do this.

```<code>import time
import os
with open("out_file.txt", 'a+') as f:
index = 0
    while True:
        ps = os.system("speedtest.exe")
        f.write(ps)
        index += 1
time.sleep(4)
</code>```

Body:
I believe it is file.write() and not file.append().

I think you want to write to a new file every time.

I  would do this.

import time
import os
index = 0
while True:
    ps = os.system("speedtest.exe")
    with open(f"out_{index}.txt", 'w+') as f:
        f.write(ps)
    index += 1
time.sleep(4)

However, if you want to write in the same file.

I  would do this.

import time
import os
with open("out_file.txt", 'a+') as f:
index = 0
    while True:
        ps = os.system("speedtest.exe")
        f.write(ps)
        index += 1
time.sleep(4)


问:
CORS error working only for one controller
I am working on a dotnet core web api.

My API is hosted on localhost:44366
and My client side application is hosted at http://127.0.0.1:5501/ (using vs code live server)

I am making two POST request using a submit button
Previously I faced the following issue when I was making one POST request:

```<code>Access to XMLHttpRequest at 'https://localhost:44366/api/surveycreatoroptions' from origin
'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.
</code>```

I have tried the [EnableCors("AllowMyOrigin")] method on both the controllers.

It works the for the first request but not for the second request (giving the same error)

This is what I have used for Enabling CORS

```<code> services.AddCors(options =>
            {
            options.AddPolicy("AllowMyOrigin",
             builder => builder.WithOrigins("http://127.0.0.1:5501").AllowAnyMethod().AllowAnyHeader())
             ;
            });

        }
</code>```

How can I make it work for both the requests.

答:
You can use below code in ConfigureServices method

```<code>services.AddCors(options =>
{
            options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
                                .AllowAnyMethod()
                                .AllowAnyHeader()
                                .AllowCredentials());
});
</code>```

and in Configure method use

```<code>app.UseCors("CorsPolicy");
</code>```

Body:
I am working on a dotnet core web api.

My API is hosted on localhost:44366
and My client side application is hosted at http://127.0.0.1:5501/ (using vs code live server)

I am making two POST request using a submit button
Previously I faced the following issue when I was making one POST request:

Access to XMLHttpRequest at 'https://localhost:44366/api/surveycreatoroptions' from origin
'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.

I have tried the [EnableCors("AllowMyOrigin")] method on both the controllers.

It works the for the first request but not for the second request (giving the same error)

This is what I have used for Enabling CORS

 services.AddCors(options =>
            {
            options.AddPolicy("AllowMyOrigin",
             builder => builder.WithOrigins("http://127.0.0.1:5501").AllowAnyMethod().AllowAnyHeader())
             ;
            });

        }

How can I make it work for both the requests.

Body:
You can use below code in ConfigureServices method

services.AddCors(options =>
{
            options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
                                .AllowAnyMethod()
                                .AllowAnyHeader()
                                .AllowCredentials());
});

and in Configure method use

app.UseCors("CorsPolicy");


问:
Passing a variable into a class to determine which method to use
im not sure what im missing but it says that my class variable (var1) is not defined

```<code>Class Example(var1):
   if var1 ==1:
      def func1(var2)
         x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
         Return x
   else pass:

Example(1).func1("example")
</code>```

could be because im tired and its simple but im also kinda new to this. Any help would be great and thank you

答:
Here is the modular way of achieving the result,</p>

```<code>class Example():
    def __init__(self, var):
        self.var = var

    def func(self):
        if self.var == 1:
            return cursor.execute("SELECT * FROM examples WHERE Name = 'var1' ")
        elif self.var == 2:
            return cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
        else:
            pass

ex = Example(1)
# call func which automatically executes query based on value of var
ex.func()
</code>```

Body:
im not sure what im missing but it says that my class variable (var1) is not defined

Class Example(var1):
   if var1 ==1:
      def func1(var2)
         x = cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
         Return x
   else pass:

Example(1).func1("example")

could be because im tired and its simple but im also kinda new to this. Any help would be great and thank you

Body:
Here is the modular way of achieving the result,

class Example():
    def __init__(self, var):
        self.var = var

    def func(self):
        if self.var == 1:
            return cursor.execute("SELECT * FROM examples WHERE Name = 'var1' ")
        elif self.var == 2:
            return cursor.execute("SELECT * FROM examples WHERE Name = 'var2' ")
        else:
            pass

ex = Example(1)
# call func which automatically executes query based on value of var
ex.func()


问:
One code to support multiple version of Odata service
Sorry for 2nd question on the same topic . I try to frame the question in better way.

our multi tenant SCP based solution supports both on premise (number of versions) and cloud version of S4HANA  as we have mix of customers from both the worlds.   We have a scenario where new fields are added in the odata service  in latest S4HANA version which are required to be used to develop a new application feature based on this field which will be consumed only by customers who are on the latest version of S4HANA.
But we also need to support customers which are not on latest S4HANA version (on premise)

My understanding on how possibly we can handle this -
1. Generate VDM on the latest odata version (with maximum fields)
2. Check if value in VDM field exists then only use it . This should help to avoid any unexpected runtime error

Can you please let me know if this is correct understanding or we should follow any different approach

Regards,
Apoorv

答:
I think the answer to how to approach this problem requires first and foremost a good understanding of all the API versions that you want to support.

Ideally, and this I think would be the metaphorical grand prize, is if the oldest version offers everything you need and every newer version of the same API has only compatible (i.e. non-breaking) changes compared to that older version. In this case it should suffice if you make sure that your client code is based on this API and you're good to go.

If this is not the case, it comes down to what the differences are. If there are radically different ways to use the (semantically) same API in e.g. SAP S/4HANA OnPremise 1809 vs SAP S/4HANA Cloud 2002, I'd try to reflect this fact in my system. Now there are probably again different ways to approach this. For example, you could think about representing this via different destinations. So you'd need to check which destinations are present in the subscriber's subaccount and then use them accordingly. Alternatively (and I'm not sure whether this is possible), you might be able to somehow determine the target system's version and edition via some API call. This would probably also give an angle with which to approach this problem.

As is probably evident from my answer, I'm not aware of any catch-all elegant solution to this problem. Maybe there are other people who've dealt with this before.


问:
Elasticsearch query to search from different fields non-strictly
I'm relatively new with elasticsearch and have been working with elasticsearch in python. What I had was people's data in csv format which I had converted to json and had added to elasticsearch index.
The fields are the following:

```<code>'Last Name (Legal Name)',
'First Name',
'Middle Name',
'Other Last Name',
'Business Mailing Address City Name',
'Business Mailing Address State Name',
'Business Practice Location Address City Name',
'Business Practice Location Address State Name',
'Authorized Official Last Name',
'Authorized Official First Name',
'Authorized Official Middle Name',
'Authorized Official Title or Position'
</code>```

What I want to put in the query is something like "Name City". For Example, "Clinton Adams Hamilton" where Clinton Adams is the name and Hamilton is the city. In most of the cases I won't be sure which is the first name or which is the last, so I will need to match from all the fields.

What I've used till now is something like this:

```<code>"query":{
                "query_string":{
                    "fields": ['Last Name (Legal Name)', 'First Name', 'Middle Name',
                             'Other Last Name', 'Business Mailing Address City Name',
                             'Business Mailing Address State Name',
                             'Business Practice Location Address City Name', 'Business Practice
                              Location Address State Name',
                             'Authorized Official Last Name', 'Authorized Official First Name',
                             'Authorized Official Middle Name',
                             'Authorized Official Title or Position'],
                    "query": "(Clinton) AND (Adams) AND (Hamilton)",
                    }
                }

</code>```

The following query works fine if I search the exact name and City from the database but if I have a spelling mistake in the name or if in some name the first name is abbreviated, it doesn't give the expected results. For example if the query is something like "Clinton A Hamilton", it wouldn't match with any documents. I can't use the ORoperator as there are multiple people with similar names, so all of the parts of the query - first name/last name and city are important. I would want the query to fetch the most relevant record from the index.

I tried my best to explain the situation. In any case, feel free to ask if anything isn't really clear. Appreciate your suggestions. Thanks.

答:
The first thing I would do is to refine your document mapping. In particular, I would think about whether it makes sense to keep so many different name-related fields (e.g., first name, last name, middle name, official authorized ...), or if it would make sense to filter some and merge something else. For example, would this document mapping make sense for you?

```<code>{
  'name',
  'business_mailing': {
    'city',
    'state'
  },
  'business_practice_location': {
    'city',
    'state'
  }
}
</code>```

Point is, you should optimise your data based on the queries you'd like to run against it.

With the mapping above, then you could run a boolean query (a must) that contains two match queries, possibly with the fuzzyness option configured so as to account for typos. E.g.,

```<code>{
  'query': {
    'bool': {
      'must': [{
        'match': {
          'name': { 'query': 'Clinton Adams', 'fuzzyness': 'AUTO'
        }
      },{
        'match': {
          'business_mailing': { 'query': 'Hamilton', 'fuzzyness': 'AUTO'
        }
      }]
    }
  }
}
</code>```

Another solution could be to use the copy_to mapping option and define a new queryable field that includes the values of the name fields and city fields. Here is the link to the documentation https://www.elastic.co/guide/en/elasticsearch/reference/7.5/copy-to.html

Body:
I'm relatively new with elasticsearch and have been working with elasticsearch in python. What I had was people's data in csv format which I had converted to json and had added to elasticsearch index.
The fields are the following:

'Last Name (Legal Name)',
'First Name',
'Middle Name',
'Other Last Name',
'Business Mailing Address City Name',
'Business Mailing Address State Name',
'Business Practice Location Address City Name',
'Business Practice Location Address State Name',
'Authorized Official Last Name',
'Authorized Official First Name',
'Authorized Official Middle Name',
'Authorized Official Title or Position'

What I want to put in the query is something like "Name City". For Example, "Clinton Adams Hamilton" where Clinton Adams is the name and Hamilton is the city. In most of the cases I won't be sure which is the first name or which is the last, so I will need to match from all the fields.

What I've used till now is something like this:

"query":{
                "query_string":{
                    "fields": ['Last Name (Legal Name)', 'First Name', 'Middle Name',
                             'Other Last Name', 'Business Mailing Address City Name',
                             'Business Mailing Address State Name',
                             'Business Practice Location Address City Name', 'Business Practice
                              Location Address State Name',
                             'Authorized Official Last Name', 'Authorized Official First Name',
                             'Authorized Official Middle Name',
                             'Authorized Official Title or Position'],
                    "query": "(Clinton) AND (Adams) AND (Hamilton)",
                    }
                }

The following query works fine if I search the exact name and City from the database but if I have a spelling mistake in the name or if in some name the first name is abbreviated, it doesn't give the expected results. For example if the query is something like "Clinton A Hamilton", it wouldn't match with any documents. I can't use the ORoperator as there are multiple people with similar names, so all of the parts of the query - first name/last name and city are important. I would want the query to fetch the most relevant record from the index.

I tried my best to explain the situation. In any case, feel free to ask if anything isn't really clear. Appreciate your suggestions. Thanks.

Body:
The first thing I would do is to refine your document mapping. In particular, I would think about whether it makes sense to keep so many different name-related fields (e.g., first name, last name, middle name, official authorized ...), or if it would make sense to filter some and merge something else. For example, would this document mapping make sense for you?

{
  'name',
  'business_mailing': {
    'city',
    'state'
  },
  'business_practice_location': {
    'city',
    'state'
  }
}

Point is, you should optimise your data based on the queries you'd like to run against it.

With the mapping above, then you could run a boolean query (a must) that contains two match queries, possibly with the fuzzyness option configured so as to account for typos. E.g.,

{
  'query': {
    'bool': {
      'must': [{
        'match': {
          'name': { 'query': 'Clinton Adams', 'fuzzyness': 'AUTO'
        }
      },{
        'match': {
          'business_mailing': { 'query': 'Hamilton', 'fuzzyness': 'AUTO'
        }
      }]
    }
  }
}

Another solution could be to use the copy_to mapping option and define a new queryable field that includes the values of the name fields and city fields. Here is the link to the documentation https://www.elastic.co/guide/en/elasticsearch/reference/7.5/copy-to.html


问:
How to split a dataframe and attach the splitted part in new column?
I want to split a dataframe by changing values in the first column and afterward attach the split part in a new column. An example is given below. However, I end up with a list that I can't process back to a handy dataframe.

the desired output should look like df_goal, which is not yet properly formatted.

```<code>#data

x <-c(1,2,3)
y <-c(20200101,20200101,20200101)
z <-c(4.5,5,7)
x_name <- "ID"
y_name <- "Date"
z_name <- "value"

df <-data.frame(x,y,z)
names(df) <- c(x_name,y_name,z_name)

#processing

df$date <-format(as.Date(as.character(df$date), format="%Y%m%d"))
df01 <- split(df, f = df$ID)

#goal
a <-c(1)
b <-c(20200101)
c <-c(4.5)
d <-c(2)
e <-c(20200101)
f <-c(5)
g <-c(3)
h <-c(20200101)
i <-c(7)

df_goal <- data.frame(a,b,c,d,e,f,g,h,i)
</code>```

Body:
I want to split a dataframe by changing values in the first column and afterward attach the split part in a new column. An example is given below. However, I end up with a list that I can't process back to a handy dataframe.

the desired output should look like df_goal, which is not yet properly formatted.

#data

x <-c(1,2,3)
y <-c(20200101,20200101,20200101)
z <-c(4.5,5,7)
x_name <- "ID"
y_name <- "Date"
z_name <- "value"

df <-data.frame(x,y,z)
names(df) <- c(x_name,y_name,z_name)

#processing

df$date <-format(as.Date(as.character(df$date), format="%Y%m%d"))
df01 <- split(df, f = df$ID)

#goal
a <-c(1)
b <-c(20200101)
c <-c(4.5)
d <-c(2)
e <-c(20200101)
f <-c(5)
g <-c(3)
h <-c(20200101)
i <-c(7)

df_goal <- data.frame(a,b,c,d,e,f,g,h,i)

Body:
One option could be:

setNames(Reduce(c, asplit(df, 1)), letters[1:Reduce(`*`, dim(df))])

     a          b          c          d          e          f          g          h          i
   1.0 20200101.0        4.5        2.0 20200101.0        5.0        3.0 20200101.0        7.0


答:
Use OFFSET:

```<code>select t.*
from t
order by created_date
offset 1 row fetch first 1 row only;
</code>```

Title: Select max TASK_ID and CREATED_DATE - already tried MAX and DISTINCT

Body:
I need to fetch only the second record and ignore the first one.
I have this data:

REFERENCE_NO       TASK_ID        CREATED_DATE
------------------------------------------------------------
244038             83102          2020-01-14 09:23:21:000000
244038             83114          2020-01-14 09:23:21:867000

Expected Output:

REFERENCE_NO       TASK_ID        CREATED_DATE
------------------------------------------------------------
244038             83114          2020-01-14 09:23:21:867000

Body:
Use OFFSET:

select t.*
from t
order by created_date
offset 1 row fetch first 1 row only;


问:
Problem with using dynamic allocation in c++
```<code>#include<iostream>
using namespace std;

int d(int num) {
   int dn = num;
   while (num != 0) {
      dn += num % 10;
      num = num / 10;
   }
   return dn;
}

int main() {
   int* arr = new int[10000];
   for (int i = 0; i < 10000; i++) {
      arr[i] = i + 1;
   }
   for (int i = 0; i < 10000; i++) {
      arr[d(i)] = 0;
   }
   for (int i = 0; i < 10000; i++) {
      if (arr[i] > 0) {
         cout << arr[i]-1<<endl;
      }
   }
   delete[] arr;
   return 0;
}
</code>```

I'm tying to code Self Number of D.R. Kaprekar but it doesent show any result in console with dynamic allocation but it does in using of static array.

答:
The function d returns values with

```<code>d(0) == 0
</code>```

and

```<code>d(i) > i, for i != 0
</code>```

This line

```<code>arr[d(i)] = 0;
</code>```

causes undefined behavior because the index goes out of bounds. In this code example you can see, how arr[4] is accessed though the size of this array is 3.

```<code>#include<iostream>

int d(int num) {
   int dn = num;
   while (num != 0) {
      dn += num % 10;
      num = num / 10;
   }
   return dn;
}

int main() {
    constexpr unsigned int s = 3;
    int arr[s];
    for (unsigned int i = 0; i < s; i++) {
        arr[i] = i + 1;
    }
    for (unsigned int i = 0; i < s; i++) {
        arr[d(i)] = 0;
        std::cout << "d(" << i << "): " << d(i) << '\n';
    }
    for (unsigned int i = 0; i < s; i++) {
        if (arr[i] > 0) {
            std::cout << arr[i] - 1 << '\n';
        }
    }
    return 0;
}
</code>```

Output:

```<code>d(0): 0
d(1): 2
d(2): 4
1
</code>```

Undefined bevahior can express itself as a crash, seemingly correct code or anything else.

Body:
#include<iostream>
using namespace std;

int d(int num) {
   int dn = num;
   while (num != 0) {
      dn += num % 10;
      num = num / 10;
   }
   return dn;
}

int main() {
   int* arr = new int[10000];
   for (int i = 0; i < 10000; i++) {
      arr[i] = i + 1;
   }
   for (int i = 0; i < 10000; i++) {
      arr[d(i)] = 0;
   }
   for (int i = 0; i < 10000; i++) {
      if (arr[i] > 0) {
         cout << arr[i]-1<<endl;
      }
   }
   delete[] arr;
   return 0;
}

I'm tying to code Self Number of D.R. Kaprekar but it doesent show any result in console with dynamic allocation but it does in using of static array.

Body:
The function d returns values with

d(0) == 0

and

d(i) > i, for i != 0

This line

arr[d(i)] = 0;

causes undefined behavior because the index goes out of bounds. In this code example you can see, how arr[4] is accessed though the size of this array is 3.

#include<iostream>

int d(int num) {
   int dn = num;
   while (num != 0) {
      dn += num % 10;
      num = num / 10;
   }
   return dn;
}

int main() {
    constexpr unsigned int s = 3;
    int arr[s];
    for (unsigned int i = 0; i < s; i++) {
        arr[i] = i + 1;
    }
    for (unsigned int i = 0; i < s; i++) {
        arr[d(i)] = 0;
        std::cout << "d(" << i << "): " << d(i) << '\n';
    }
    for (unsigned int i = 0; i < s; i++) {
        if (arr[i] > 0) {
            std::cout << arr[i] - 1 << '\n';
        }
    }
    return 0;
}

Output:

d(0): 0
d(1): 2
d(2): 4
1

Undefined bevahior can express itself as a crash, seemingly correct code or anything else.


问:
How to write a tree with a jagged array as a branch?
I would like to write a tree with two branches. One branch contains a single number per fill and the other branch contains a variable length array per fill. From the documentation, I can see how to do the first, but not how to do the second?</p>

答:
The answer is that this is a missing feature: https://github.com/scikit-hep/uproot/issues/354

As a "writing improvement," it probably has the highest benefit-over-effort ratio, but right now, we'd need a volunteer to get it done. Reik is assigned to that item, but he's both in school and gearing up for a different project. If you know anyone who wants to deal with byte manipulation and make a big impact, let me know!


问:
Need Workaround for Outlook 2007 HTML Email Rendering Bug (Horizontal Gaps)
My HTML email newsletter design doesn't render properly in Outlook 2007. There is a white horizontal gap towards the bottom which breaks borders and backgrounds. I've had this happen before and have no idea how to work around it. Any suggestions? I've posted the source here. It renders just fine except in Outlook 2007 (Word 2007).

By the way, you can preview the problem without Outlook, by opening the source with Word 2007.

答: My experience is that this white line break normally occurs when there is an image close to the line breaks that outlook 2007 inserts. The quick workaround is to insert some text beneath the image so that instead of letting outlook 2007 insert the page break, the extra text will format the pages without any "help" from outlook 2007 hence the disappearance of the mysterious white line.</p>

ContentLicense: CC BY-SA 3.0


问:
Why echo of combined variables in for loop doesn't work?
what is wrong with "echo" line in my loop?
It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ?
After loop is done, I do "manual check" of the saver variables and they apparently exist.

Script:

```<code>#!/bin/bash
for i in {1..3}
 do
  read -p "Insert value $i: " v$i
  echo "you wrote " $v$i          #I have problem in this line
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
</code>```

Console output:

```<code>./input_2.sh
Insert value 1: what
you wrote  1              #output should be: you wrote what
Insert value 2: the
you wrote  2              #output should be: you wrote the
Insert value 3: hell
you wrote  3              #output should be: you wrote hell

check of saved values:
what
the
hell
</code>```

Thanks

答:
This line:

echo "you wrote " $v$i

Tries to write variable $v followed by $i.

What you need is to store the variable name into a variable and then use the ${!}, for example:

varname=v$i
echo "you wrote " ${!varname}
```

<p>A good practice would be to use this variable name for the <code>read</code> operation as well:</p>

<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
for i in {1..3}
 do
  varname=v$i
  read -p "Insert value $i: " $varname
  echo "you wrote " ${!varname}
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
</code>```

Body:
what is wrong with "echo" line in my loop?
It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ?
After loop is done, I do "manual check" of the saver variables and they apparently exist.

Script:

#!/bin/bash
for i in {1..3}
 do
  read -p "Insert value $i: " v$i
  echo "you wrote " $v$i          #I have problem in this line
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3

Console output:

./input_2.sh
Insert value 1: what
you wrote  1              #output should be: you wrote what
Insert value 2: the
you wrote  2              #output should be: you wrote the
Insert value 3: hell
you wrote  3              #output should be: you wrote hell

check of saved values:
what
the
hell

Thanks

Body:
This line:

echo "you wrote " $v$i

Tries to write variable $v followed by $i.

What you need is to store the variable name into a variable and then use the ${!}, for example:

varname=v$i
echo "you wrote " ${!varname}

A good practice would be to use this variable name for the read operation as well:

#!/bin/bash
for i in {1..3}
 do
  varname=v$i
  read -p "Insert value $i: " $varname
  echo "you wrote " ${!varname}
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3


问:
Input type date format and datepicker issues
I'm working with HTML5 elements input attributes and only Chrome, iOS safari and Opera seem to support it at this time. So I have created a jQuery UI datepicker fallback for browsers that do not support it yet, but there are a few issues I'm running into and haven't been able to find any answers for.

If I put in the date format that the datepickers requires and then
pick a new date, there is an extra yyyy

I think the yyyy-mm-dd format is ridiculous and would like it be displayed mm/dd/yyyy like chrome does even though the value is still yyyy-mm-dd. Is there a way to do this with datepicker or a better solution?

Example

JS

```<code>if (!Modernizr.inputtypes.date) {
  $('input[type=date]').datepicker({
    dateFormat: 'yyyy-mm-dd' // HTML 5
  });
}
</code>```

HTML

```<code><input type="date" value="2014-01-07" />
</code>```

Please look in firefox to view the datepicker fallback and chrome to view the input type date.

答:
Here is the solution I came to to use only one input (no need of a hidden input).

```<code>$('input[type="date"], input[type="datetime"]').datepicker({
    dateFormat: 'yy-mm-dd',
    altFormat: 'dd.mm.yy',
    altField: $(this)
});
</code>```

In the altFormat set the format you want to show your user, altField is your date field, dateFormat is the HTML5 date format.

Body:
I'm working with HTML5 elements input attributes and only Chrome, iOS safari and Opera seem to support it at this time. So I have created a jQuery UI datepicker fallback for browsers that do not support it yet, but there are a few issues I'm running into and haven't been able to find any answers for.

If I put in the date format that the datepickers requires and then
pick a new date, there is an extra yyyy

I think the yyyy-mm-dd format is ridiculous and would like it be displayed mm/dd/yyyy like chrome does even though the value is still yyyy-mm-dd. Is there a way to do this with datepicker or a better solution?

Example

JS

if (!Modernizr.inputtypes.date) {
  $('input[type=date]').datepicker({
    dateFormat: 'yyyy-mm-dd' // HTML 5
  });
}

HTML

<input type="date" value="2014-01-07" />

Please look in firefox to view the datepicker fallback and chrome to view the input type date.

Body:
Here is the solution I came to to use only one input (no need of a hidden input).

$('input[type="date"], input[type="datetime"]').datepicker({
    dateFormat: 'yy-mm-dd',
    altFormat: 'dd.mm.yy',
    altField: $(this)
});

In the altFormat set the format you want to show your user, altField is your date field, dateFormat is the HTML5 date format.


问:
How to inject service to helper after a promise has been fulfilled?
I am developing a simple Ember app, which retrieves all language strings from an API. I have setup a service with a translate() method, and injected that service into a helper. The problem is that the property I want to use it not available in the helper, because when it's used, the promise hasn't been fulfilled yet. How can I access the property in the helper after it has been loaded from the service?

Service (app/services/i18n.js):

```<code>export default Ember.Service.extend({
    locales: null,
    init() {
        this._super();

        Ember.$.getJSON('/api/recruiting/locales').then(function (response) {
            this.set('locales', response.data);
        }.bind(this));
    },
    translate(key) {
        // This causes the problem: locales property has not been loaded yet at this point
        return this.get('locales.' + key);
    }
});
</code>```

Helper (app/helpers/translate.js):

```<code>export default Ember.Helper.extend({
    i18n: Ember.inject.service(),
    compute(params/*, hash*/) {
        var i18n = this.get('i18n');

        return i18n.translate(params[0]);
    }
});
</code>```

答:
Using Ember Octane the result would be something like this. Note observers are considered bad practice, so you'd need to implement some kind of change listener in the i18n service to trigger changes in the i18n.locales variable.

```<code>import Helper from '@ember/component/helper';
import { inject as service } from "@ember/service";

export default class Translate extends Helper {
  @service i18n;

  init() {
    super.init(...arguments);
    this.i18n.addChangeListener(this.localeChanged);
  }

  willDestroy() {
    super.willDestroy();
    this.i18n.removeChangeListener(this.localeChanged);
  }

  localeChanged = () => {
    this.recompute();
  }

  compute([key]) {
    return this.i18n.translate(key);
  }
}
</code>```

Body:
I am developing a simple Ember app, which retrieves all language strings from an API. I have setup a service with a translate() method, and injected that service into a helper. The problem is that the property I want to use it not available in the helper, because when it's used, the promise hasn't been fulfilled yet. How can I access the property in the helper after it has been loaded from the service?

Service (app/services/i18n.js):

export default Ember.Service.extend({
    locales: null,
    init() {
        this._super();

        Ember.$.getJSON('/api/recruiting/locales').then(function (response) {
            this.set('locales', response.data);
        }.bind(this));
    },
    translate(key) {
        // This causes the problem: locales property has not been loaded yet at this point
        return this.get('locales.' + key);
    }
});

Helper (app/helpers/translate.js):

export default Ember.Helper.extend({
    i18n: Ember.inject.service(),
    compute(params/*, hash*/) {
        var i18n = this.get('i18n');

        return i18n.translate(params[0]);
    }
});

Body:
Using Ember Octane the result would be something like this. Note observers are considered bad practice, so you'd need to implement some kind of change listener in the i18n service to trigger changes in the i18n.locales variable.

import Helper from '@ember/component/helper';
import { inject as service } from "@ember/service";

export default class Translate extends Helper {
  @service i18n;

  init() {
    super.init(...arguments);
    this.i18n.addChangeListener(this.localeChanged);
  }

  willDestroy() {
    super.willDestroy();
    this.i18n.removeChangeListener(this.localeChanged);
  }

  localeChanged = () => {
    this.recompute();
  }

  compute([key]) {
    return this.i18n.translate(key);
  }
}


问:
Is a way to curry multiple ramda's assocPath methods in a redux reducer?
So wanted to know if there is any way I could curry multiple assocPath methods in redux reducer. What I wish to do is update the state of an object and array in my redux reducer without mutating it. For which I have to set a value in multiple object/ arrays. The way I am trying to do it is via creating a clone of the object and updating it and then again set it to the state, this I am doing in my components state.
So currently I am do something like this in my components state. I wish to do the similar in the redux reducer

```<code> let newState;
    newState = _.assocPath(["project", "value"], project, this.state);
    newState = _.assocPath(["project", "error"], false, newState);
    this.setState(newState);
</code>```

But the problem is in redux reducer I ma not able to do it. I have to curry the methods one after the other.

Please let me know if you want more info.
Thank you

答:
I think the solution from Ori Drori is better than this, but this seems to me to be what you're asking for:

const foo = (project, errVal) => pipe (
  prop ('state'),
  assocPath (["project", "value"], project),
  assocPath (["project", "error"], errVal)
)

this .setState (foo (project, false) (this))
```

foo (ok, so I'm terrible at naming!) accepts your project and err values and returns a function which accepts an object and returns an updated version of its state property, after setting project.value and project.error.  Is this what you're looking to do?

Terminology

You say this:

But the problem is in redux reducer I am not able to do it. I have to curry the methods one after the other.

And I just want to point out some problems with the wording.  First, Ramda does not have methods.  Methods are functions that act on an object's state.  Ramda is very careful to not mutate your state at all.  Ramda instead simply has functions.  R (or _ if you choose) serves as a namespace for a large number of independent functions.

And second, what you're doing has nothing to do with currying.  You're simply calling the functions.  My answer uses pipe to compose some functions into a new one, and perhaps that's what you meant.  Currying is the process of converting a function of multiple arguments into a nested sequence of single-argument functions.  (a, b, c) => 'foo'  ===> (a) => (b) => (c) => 'foo'.  Ramda's currying has some additional features that let you call the resulting function in more ways, but the point is that nothing in the question has anything to do with currying.

Body:
So wanted to know if there is any way I could curry multiple assocPath methods in redux reducer. What I wish to do is update the state of an object and array in my redux reducer without mutating it. For which I have to set a value in multiple object/ arrays. The way I am trying to do it is via creating a clone of the object and updating it and then again set it to the state, this I am doing in my components state.
So currently I am do something like this in my components state. I wish to do the similar in the redux reducer

 let newState;
    newState = _.assocPath(["project", "value"], project, this.state);
    newState = _.assocPath(["project", "error"], false, newState);
    this.setState(newState);

But the problem is in redux reducer I ma not able to do it. I have to curry the methods one after the other.

Please let me know if you want more info.
Thank you

Body:
I think the solution from Ori Drori is better than this, but this seems to me to be what you're asking for:

const foo = (project, errVal) => pipe (
  prop ('state'),
  assocPath (["project", "value"], project),
  assocPath (["project", "error"], errVal)
)

this .setState (foo (project, false) (this))

foo (ok, so I'm terrible at naming!) accepts your project and err values and returns a function which accepts an object and returns an updated version of its state property, after setting project.value and project.error.  Is this what you're looking to do?

Terminology

You say this:

But the problem is in redux reducer I am not able to do it. I have to curry the methods one after the other.

And I just want to point out some problems with the wording.  First, Ramda does not have methods.  Methods are functions that act on an object's state.  Ramda is very careful to not mutate your state at all.  Ramda instead simply has functions.  R (or _ if you choose) serves as a namespace for a large number of independent functions.

And second, what you're doing has nothing to do with currying.  You're simply calling the functions.  My answer uses pipe to compose some functions into a new one, and perhaps that's what you meant.  Currying is the process of converting a function of multiple arguments into a nested sequence of single-argument functions.  (a, b, c) => 'foo'  ===> (a) => (b) => (c) => 'foo'.  Ramda's currying has some additional features that let you call the resulting function in more ways, but the point is that nothing in the question has anything to do with currying.


问:
Dynamic @RequestParam in @RestController
I have a controller:

```<code>@RestController
@RequestMapping(value = UserRestController.REST_URL, produces =
MediaType.APPLICATION_JSON_VALUE)
public class UserRestController {

static final String REST_URL = "/customers";

@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}
</code>```

It succesfully handle such requests,as:

```<code>GET:    /customers/
</code>```

And I want to get users by some parameters.For example, email:

```<code>GET:   /customers?email=someemail@gmail.
</code>```

I tried:

```<code>@GetMapping("/")
public User getByEmail(@RequestParam(value = "email") String email) {
    return super.getByEmail(email);
}
</code>```

and expectedly I receive an exception, as "/" is already mapped on getAll-class.
Is there any ways to solve this problem?

答:
You have to modify your current

```<code>@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}
</code>```

method and add the email as a request parameter if you want to keep the URL mapping the same.
So it will look like:

```<code>@GetMapping
public List<User> getAll(@RequestParam(value = "email", required = false) String email) {
    if (!StringUtils.isempty(email)) {
        return super.getByEmail(email);
    } else {
        return service.getAll();
    }
}
</code>```

Body:
I have a controller:

@RestController
@RequestMapping(value = UserRestController.REST_URL, produces =
MediaType.APPLICATION_JSON_VALUE)
public class UserRestController {

static final String REST_URL = "/customers";

@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}

It succesfully handle such requests,as:

GET:    /customers/

And I want to get users by some parameters.For example, email:

GET:   /customers?email=someemail@gmail.

I tried:

@GetMapping("/")
public User getByEmail(@RequestParam(value = "email") String email) {
    return super.getByEmail(email);
}

and expectedly I receive an exception, as "/" is already mapped on getAll-class.
Is there any ways to solve this problem?

Body:
You have to modify your current

@GetMapping
public List<User> getAll() {
    return service.getAll();
  }
}

method and add the email as a request parameter if you want to keep the URL mapping the same.
So it will look like:

@GetMapping
public List<User> getAll(@RequestParam(value = "email", required = false) String email) {
    if (!StringUtils.isempty(email)) {
        return super.getByEmail(email);
    } else {
        return service.getAll();
    }
}


问:
Problem with accessing an array from inside a promise
So I have this code which essentially sends a message with results as a string then sends a message again to ask the user to select one of the elements inside the results array and then tries to assign the array content of results inside the myObj property using this which does not work (returns undefined).

I've read that this can refer to

the global object in a function.

can that apply here?.

Here is the sample:

                        let myObj = {
                           testArray: []
                        };

                        let results = [1,2,3]´;

                        send(results.join("\n"))//sends array as message
                            .then(m => { //premise returns the same array as message
                                send(`Please type a number.`)
                                    .then(m => { //same for reply, returns `Please type a number`
                                        obj = {
                                            testArray: this.results //<---- here results is undefined
                                        };
                                    })
                                    .catch(err => console.error(err));
                            })
                            .catch(err => {
                                console.error(err);
                            })
                    })
```

Would there be anyway to use the this keyword to get access to the results array defined earlier and if yes what would be it's role in this situation?
Thanks in advance.

答: Replace testArray: this.results with only testArray: results as results is a variable only

Body:
So I have this code which essentially sends a message with results as a string then sends a message again to ask the user to select one of the elements inside the results array and then tries to assign the array content of results inside the myObj property using this which does not work (returns undefined).

I've read that this can refer to

the global object in a function.

can that apply here?.

Here is the sample:

                        let myObj = {
                           testArray: []
                        };

                        let results = [1,2,3]´;

                        send(results.join("\n"))//sends array as message
                            .then(m => { //premise returns the same array as message
                                send(`Please type a number.`)
                                    .then(m => { //same for reply, returns `Please type a number`
                                        obj = {
                                            testArray: this.results //<---- here results is undefined
                                        };
                                    })
                                    .catch(err => console.error(err));
                            })
                            .catch(err => {
                                console.error(err);
                            })
                    })

Would there be anyway to use the this keyword to get access to the results array defined earlier and if yes what would be it's role in this situation?
Thanks in advance.


问:
Is it possible to extend Celery, so results would be store to several MongoDB collections?
I've started a new project and I want to make Celery save results to several MongoDB collections instead of one. Is there a way to do that through configs or do I need to extend Celery and Kombu to achieve that? </p>

答:
You don't need to modify Celery, you can extend it. That's exactly what I did for one internal project. I didn't want to touch the standard results backend (Redis in my case), but wanted to also store the tasks' state and results in MongoDB for good while enhancing the state/results at the same time.

I ended up creating a little library with class called TaskTracker that uses Celery signals machinery to achieve the goal. The key parts of the implementation look like this:

```<code>import datetime

from celery import signals, states
from celery.exceptions import ImproperlyConfigured
from pymongo import MongoClient, ReturnDocument

class TaskTracker(object):
    """Track task processing and store the state in MongoDB."""

    def __init__(self, app):
        self.config = app.conf.get('task_tracker')
        if not self.config:
            raise ImproperlyConfigured('Task tracker configuration missing')
        self.tasks = set()
        self._mongo = None

        self._connect_signals()

    @property
    def mongo(self):
        # create client on first use to avoid 'MongoClient opened before fork.'
        # warning
        if not self._mongo:
            self._mongo = self._connect_to_mongodb()
        return self._mongo

    def _connect_to_mongodb(self):
        client = MongoClient(self.config['mongodb']['uri'])
        # check connection / error handling
        # ...
        return client

    def _connect_signals(self):
        signals.task_received.connect(self._on_task_received)
        signals.task_prerun.connect(self._on_task_prerun)
        signals.task_retry.connect(self._on_task_retry)
        signals.task_revoked.connect(self._on_task_revoked)
        signals.task_success.connect(self._on_task_success)
        signals.task_failure.connect(self._on_task_failure)

    def _on_task_received(self, sender, request, **other_kwargs):
        if request.name not in self.tasks:
            return

        collection = self.mongo \
            .get_database(self.config['mongodb']['database']) \
            .get_collection(self.config['mongodb']['collection'])
        collection.find_one_and_update(
            {'_id': request.id},
            {
                '$setOnInsert': {
                    'name': request.name,
                    'args': request.args,
                    'kwargs': request.kwargs,
                    'date_received': datetime.datetime.utcnow(),
                    'job_id': request.message.headers.get('job_id')
                },
                '$set': {
                    'status': states.RECEIVED,
                    'root_id': request.root_id,
                    'parent_id': request.parent_id
                },
                '$push': {
                    'status_history': {
                        'date': datetime.datetime.utcnow(),
                        'status': states.RECEIVED
                    }
                }
            },
            upsert=True,
            return_document=ReturnDocument.AFTER)

    # similarly for other signals...
    def _on_task_prerun(self, sender, task_id, task, args, kwargs,
                        **other_kwargs):
        # ...

    def _on_task_retry(self, sender, request, reason, einfo, **other_kwargs):
        # ...

    # ...

    def track(self, task):
        """Set up tracking for given task."""
        # accept either task name or task instance (for use as a decorator)
        if isinstance(task, str):
            self.tasks.add(task)
        else:
            self.tasks.add(task.name)
            return task
</code>```

Then you need to provide configuration for MongoDB. I use YAML configuration file for Celery so it looks like this:

```<code># standard Celery settings...
# ...

task_tracker:
    # MongoDB database for storing task state and results
    mongodb:
        uri: "\
            mongodb://myuser:mypassword@\
            mymongo.mydomain.com:27017/?\
            replicaSet=myreplica&tls=true&connectTimeoutMS=5000&\
            w=1&wtimeoutMS=3000&readPreference=primaryPreferred&maxStalenessSeconds=-1&\
            authSource=mydatabase&authMechanism=SCRAM-SHA-1"
        database: 'mydatabase'
        collection: 'tasks'
</code>```

In your tasks module, you just create the class instance providing your Celery app and decorate your tasks:

```<code>import os

from celery import Celery
import yaml

from celery_common.tracking import TaskTracker  # my custom utils library

config_file = os.environ.get('CONFIG_FILE', default='/srv/celery/config.yaml')
with open(config_file) as f:
    config = yaml.safe_load(f) or {}

app = Celery(__name__)
app.conf.update(config)

tracker = TaskTracker(app)

@tracker.track
@app.task(name='mytask')
def mytask(myparam1, myparam2, *args, **kwargs):
    pass
</code>```

Now your tasks' state and results are going to be tracked in MongoDB, separate from the standard results backend. If you need to store it in multiple databases, you can adjust it a bit, create multiple TaskTracker instances and provide multiple decorators to your tasks.

Body:
You don't need to modify Celery, you can extend it. That's exactly what I did for one internal project. I didn't want to touch the standard results backend (Redis in my case), but wanted to also store the tasks' state and results in MongoDB for good while enhancing the state/results at the same time.

I ended up creating a little library with class called TaskTracker that uses Celery signals machinery to achieve the goal. The key parts of the implementation look like this:

import datetime

from celery import signals, states
from celery.exceptions import ImproperlyConfigured
from pymongo import MongoClient, ReturnDocument

class TaskTracker(object):
    """Track task processing and store the state in MongoDB."""

    def __init__(self, app):
        self.config = app.conf.get('task_tracker')
        if not self.config:
            raise ImproperlyConfigured('Task tracker configuration missing')
        self.tasks = set()
        self._mongo = None

        self._connect_signals()

    @property
    def mongo(self):
        # create client on first use to avoid 'MongoClient opened before fork.'
        # warning
        if not self._mongo:
            self._mongo = self._connect_to_mongodb()
        return self._mongo

    def _connect_to_mongodb(self):
        client = MongoClient(self.config['mongodb']['uri'])
        # check connection / error handling
        # ...
        return client

    def _connect_signals(self):
        signals.task_received.connect(self._on_task_received)
        signals.task_prerun.connect(self._on_task_prerun)
        signals.task_retry.connect(self._on_task_retry)
        signals.task_revoked.connect(self._on_task_revoked)
        signals.task_success.connect(self._on_task_success)
        signals.task_failure.connect(self._on_task_failure)

    def _on_task_received(self, sender, request, **other_kwargs):
        if request.name not in self.tasks:
            return

        collection = self.mongo \
            .get_database(self.config['mongodb']['database']) \
            .get_collection(self.config['mongodb']['collection'])
        collection.find_one_and_update(
            {'_id': request.id},
            {
                '$setOnInsert': {
                    'name': request.name,
                    'args': request.args,
                    'kwargs': request.kwargs,
                    'date_received': datetime.datetime.utcnow(),
                    'job_id': request.message.headers.get('job_id')
                },
                '$set': {
                    'status': states.RECEIVED,
                    'root_id': request.root_id,
                    'parent_id': request.parent_id
                },
                '$push': {
                    'status_history': {
                        'date': datetime.datetime.utcnow(),
                        'status': states.RECEIVED
                    }
                }
            },
            upsert=True,
            return_document=ReturnDocument.AFTER)

    # similarly for other signals...
    def _on_task_prerun(self, sender, task_id, task, args, kwargs,
                        **other_kwargs):
        # ...

    def _on_task_retry(self, sender, request, reason, einfo, **other_kwargs):
        # ...

    # ...

    def track(self, task):
        """Set up tracking for given task."""
        # accept either task name or task instance (for use as a decorator)
        if isinstance(task, str):
            self.tasks.add(task)
        else:
            self.tasks.add(task.name)
            return task

Then you need to provide configuration for MongoDB. I use YAML configuration file for Celery so it looks like this:

# standard Celery settings...
# ...

task_tracker:
    # MongoDB database for storing task state and results
    mongodb:
        uri: "\
            mongodb://myuser:mypassword@\
            mymongo.mydomain.com:27017/?\
            replicaSet=myreplica&tls=true&connectTimeoutMS=5000&\
            w=1&wtimeoutMS=3000&readPreference=primaryPreferred&maxStalenessSeconds=-1&\
            authSource=mydatabase&authMechanism=SCRAM-SHA-1"
        database: 'mydatabase'
        collection: 'tasks'

In your tasks module, you just create the class instance providing your Celery app and decorate your tasks:

import os

from celery import Celery
import yaml

from celery_common.tracking import TaskTracker  # my custom utils library

config_file = os.environ.get('CONFIG_FILE', default='/srv/celery/config.yaml')
with open(config_file) as f:
    config = yaml.safe_load(f) or {}

app = Celery(__name__)
app.conf.update(config)

tracker = TaskTracker(app)

@tracker.track
@app.task(name='mytask')
def mytask(myparam1, myparam2, *args, **kwargs):
    pass

Now your tasks' state and results are going to be tracked in MongoDB, separate from the standard results backend. If you need to store it in multiple databases, you can adjust it a bit, create multiple TaskTracker instances and provide multiple decorators to your tasks.


问:
Pythonanywhere error when accessing the homepage
I get the following error when I access my homepage (on Pythonanywhere). I believe all the settings are correct in the WSGI file. ImportError: No module named 'myproject' - even though the module is there. Is this something I have to define somewhere?

The error is as follows:

```<code>2020-02-19 02:25:26,696: Error running WSGI application
2020-02-19 02:25:26,697: ImportError: No module named 'myproject'
2020-02-19 02:25:26,697:   File "/var/www/user1_pythonanywhere_com_wsgi.py", line 16, in <module>
2020-02-19 02:25:26,697:     application = get_wsgi_application()
2020-02-19 02:25:26,697:
2020-02-19 02:25:26,697:   File "/home/user1/.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
2020-02-19 02:25:26,697:     django.setup(set_prefix=False)
2020-02-19 02:25:26,697:
2020-02-19 02:25:26,697:   File "/home/user1/.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/__init__.py", line 19, in setup
2020-02-19 02:25:26,698:     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
2020-02-19 02:25:26,698:
2020-02-19 02:25:26,698:   File "/home/user1/.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 79, in __getattr__
2020-02-19 02:25:26,698:     self._setup(name)
2020-02-19 02:25:26,698:
2020-02-19 02:25:26,698:   File "/home//.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 66, in _setup
2020-02-19 02:25:26,698:     self._wrapped = Settings(settings_module)
2020-02-19 02:25:26,698:
2020-02-19 02:25:26,699:   File "/home/user1/.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 157, in __init__
2020-02-19 02:25:26,699:     mod = importlib.import_module(self.SETTINGS_MODULE)
</code>```

答: On PythonAnywhere, just after your exception in the logs, there is a link to a help page that walks you through debugging import errors in your web app.</p>

Body:
I get the following error when I access my homepage (on Pythonanywhere). I believe all the settings are correct in the WSGI file. ImportError: No module named 'myproject' - even though the module is there. Is this something I have to define somewhere?

The error is as follows:

2020-02-19 02:25:26,696: Error running WSGI application
2020-02-19 02:25:26,697: ImportError: No module named 'myproject'
2020-02-19 02:25:26,697:   File "/var/www/user1_pythonanywhere_com_wsgi.py", line 16, in <module>
2020-02-19 02:25:26,697:     application = get_wsgi_application()
2020-02-19 02:25:26,697:
2020-02-19 02:25:26,697:   File "/home/user1/.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
2020-02-19 02:25:26,697:     django.setup(set_prefix=False)
2020-02-19 02:25:26,697:
2020-02-19 02:25:26,697:   File "/home/user1/.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/__init__.py", line 19, in setup
2020-02-19 02:25:26,698:     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
2020-02-19 02:25:26,698:
2020-02-19 02:25:26,698:   File "/home/user1/.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 79, in __getattr__
2020-02-19 02:25:26,698:     self._setup(name)
2020-02-19 02:25:26,698:
2020-02-19 02:25:26,698:   File "/home//.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 66, in _setup
2020-02-19 02:25:26,698:     self._wrapped = Settings(settings_module)
2020-02-19 02:25:26,698:
2020-02-19 02:25:26,699:   File "/home/user1/.virtualenvs/mysite-virtualenv/lib/python3.5/site-packages/django/conf/__init__.py", line 157, in __init__
2020-02-19 02:25:26,699:     mod = importlib.import_module(self.SETTINGS_MODULE)


问:
Jenkins Multi Setup Parallel Job
I have a jenkins job that requires a specific setup to run it. Since the job gets triggered multiple times often there is queue, so I want to setup jenkins to run the same job in parallel. The question is if I have two setups setupA and setupB and if job1 is being executed sing setupA, how do I configure jenkins job to take setupB for job2? SetupB should only be used if SetupA is being used by another job. Is there a way to configure the jenkins job for this?</p>

答:
Add more slaves to Jenkins Jobs, if jobs are triggered multiple times.

Make sure each and every job point to only agents instead of master. So if multiple jobs are triggered at a time, still Jenkins wont hang.

If Jenkins slave machine have more CPU and RAM, then add more executed to run parallel job on same agent.

For the master, this is set in Manage Jenkins > Configure System > # of executors

For the slaves (nodes), it is set in Manage Jenkins > Nodes > (each node) > Configure > # of executors

Title: Jenkins Multi Setup Parallel Job


问:
How to know on which physical processor and on which physical core my code is running
How can I know in a C program, on which physical processor and core my code is running?
I'm using Linux and gcc 4.4.3.</p>

答:
You may check /proc//stat file system, according to http://www.kernel.org/doc/Documentation/filesystems/proc.txt, you should just check task_cpu flag.

As example without correct types and error checking:

```<code>struct pstat
{
  int  pid;       //process id
  char tcomm[256];//filename of the executable
  char state[2];  //state (R is running, S is sleeping, D is sleeping in an
                  //uninterruptible wait, Z is zombie, T is traced or stopped)
  int ppid;//          process id of the parent process
  int pgrp;//          pgrp of the process
  int sid;//           session id
  int tty_nr;//        tty the process uses
  int tty_pgrp;//      pgrp of the tty
  int flags;//         task flags
  int min_flt;//       number of minor faults
  int cmin_flt;//      number of minor faults with child's
  int maj_flt;//       number of major faults
  int cmaj_flt;//      number of major faults with child's
  int utime;//         user mode jiffies
  int stime;//         kernel mode jiffies
  int cutime;//        user mode jiffies with child's
  int cstime;//        kernel mode jiffies with child's
  int priority;//      priority level
  int nice;//          nice level
  int num_threads;//   number of threads
  int it_real_value;//  (obsolete, always 0)
  int start_time;//    time the process started after system boot
  int vsize;//         virtual memory size
  int rss;//           resident set memory size
  int rsslim;//        current limit in bytes on the rss
  int start_code;//    address above which program text can run
  int end_code;//      address below which program text can run
  int start_stack;//   address of the start of the stack
  int esp;//           current value of ESP
  int eip;//           current value of EIP
  int pending;//       bitmap of pending signals
  int blocked;//       bitmap of blocked signals
  int sigign;//        bitmap of ignored signals
  int sigcatch;//      bitmap of catched signals
  int wchan;//         address where process went to sleep
  int i0;//             (place holder)
  int i1;//             (place holder)
  int exit_signal;//   signal to send to parent thread on exit
  int task_cpu;//      which CPU the task is scheduled on
  int rt_priority;//   realtime priority
  int policy;//        scheduling policy (man sched_setscheduler)
  int blkio_ticks;//   time spent waiting for block IO
  int gtime;//         guest time of the task in jiffies
  int cgtime;//        guest time of the task children in jiffies
} p ;

int main()
{
    char name[256];
    char state[8];
    FILE* f = fopen("/proc/self/stat", "r");

    fscanf(f,  "%d%s%s%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
           &p.pid, &p.tcomm, &p.state, &p.ppid, &p.pgrp, &p.sid, &p.tty_nr, &p.tty_pgrp, &p.flags,
           &p.min_flt, &p.cmin_flt, &p.maj_flt, &p.cmaj_flt, &p.utime, &p.stime,  &p.cutime, &p.cstime,
           &p.priority, &p.nice, &p.num_threads, &p.it_real_value, &p.start_time,  &p.vsize, &p.rss,
           &p.rsslim, &p.start_code, &p.end_code, &p.start_stack, &p.esp, &p.eip,  &p.pending, &p.blocked,
           &p.sigign, &p.sigcatch, &p.wchan, &p.i0, &p.i1, &p.exit_signal,  &p.task_cpu, &p.rt_priority, &p.policy,
           &p.blkio_ticks, &p.gtime, &p.cgtime);

     printf("CPU %d\n", p.task_cpu);
 return 0;
 }
</code>```

Body:
You may check /proc//stat file system, according to http://www.kernel.org/doc/Documentation/filesystems/proc.txt, you should just check task_cpu flag.

As example without correct types and error checking:

struct pstat
{
  int  pid;       //process id
  char tcomm[256];//filename of the executable
  char state[2];  //state (R is running, S is sleeping, D is sleeping in an
                  //uninterruptible wait, Z is zombie, T is traced or stopped)
  int ppid;//          process id of the parent process
  int pgrp;//          pgrp of the process
  int sid;//           session id
  int tty_nr;//        tty the process uses
  int tty_pgrp;//      pgrp of the tty
  int flags;//         task flags
  int min_flt;//       number of minor faults
  int cmin_flt;//      number of minor faults with child's
  int maj_flt;//       number of major faults
  int cmaj_flt;//      number of major faults with child's
  int utime;//         user mode jiffies
  int stime;//         kernel mode jiffies
  int cutime;//        user mode jiffies with child's
  int cstime;//        kernel mode jiffies with child's
  int priority;//      priority level
  int nice;//          nice level
  int num_threads;//   number of threads
  int it_real_value;//  (obsolete, always 0)
  int start_time;//    time the process started after system boot
  int vsize;//         virtual memory size
  int rss;//           resident set memory size
  int rsslim;//        current limit in bytes on the rss
  int start_code;//    address above which program text can run
  int end_code;//      address below which program text can run
  int start_stack;//   address of the start of the stack
  int esp;//           current value of ESP
  int eip;//           current value of EIP
  int pending;//       bitmap of pending signals
  int blocked;//       bitmap of blocked signals
  int sigign;//        bitmap of ignored signals
  int sigcatch;//      bitmap of catched signals
  int wchan;//         address where process went to sleep
  int i0;//             (place holder)
  int i1;//             (place holder)
  int exit_signal;//   signal to send to parent thread on exit
  int task_cpu;//      which CPU the task is scheduled on
  int rt_priority;//   realtime priority
  int policy;//        scheduling policy (man sched_setscheduler)
  int blkio_ticks;//   time spent waiting for block IO
  int gtime;//         guest time of the task in jiffies
  int cgtime;//        guest time of the task children in jiffies
} p ;

int main()
{
    char name[256];
    char state[8];
    FILE* f = fopen("/proc/self/stat", "r");

    fscanf(f,  "%d%s%s%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
           &p.pid, &p.tcomm, &p.state, &p.ppid, &p.pgrp, &p.sid, &p.tty_nr, &p.tty_pgrp, &p.flags,
           &p.min_flt, &p.cmin_flt, &p.maj_flt, &p.cmaj_flt, &p.utime, &p.stime,  &p.cutime, &p.cstime,
           &p.priority, &p.nice, &p.num_threads, &p.it_real_value, &p.start_time,  &p.vsize, &p.rss,
           &p.rsslim, &p.start_code, &p.end_code, &p.start_stack, &p.esp, &p.eip,  &p.pending, &p.blocked,
           &p.sigign, &p.sigcatch, &p.wchan, &p.i0, &p.i1, &p.exit_signal,  &p.task_cpu, &p.rt_priority, &p.policy,
           &p.blkio_ticks, &p.gtime, &p.cgtime);

     printf("CPU %d\n", p.task_cpu);
 return 0;
 }


问:
Synchronously assign get request body to variable - Dart
I have a Future function which uses a get request and I save the request body to a variable {data}. It works well, however when I run my application and try loading a page with the data the variable is accessed before being assigned the value. It is only after I hot reload that it shows.

How do I make the whole page wait until the variable is assigned?

```<code> static Future<Ticket> futureTicket;

 Map<String, dynamic> data;

 Future<Ticket> fetchTicket() async {
 final response =
    await http.get('http://hostname/getRequest');

     if (response.statusCode == 200) {
     // If the server did return a 200 OK response, then parse the JSON.
      this.data = json.decode(response.body);

     //print("Data Here: " + data.toString());
      return Ticket.fromJson(json.decode(response.body));
     } else {

    // If the server did not return a 200 OK response, then throw an exception.
    throw Exception('Failed to load Ticket');
    }

   }

   @override
     void initState(){
     futureTicket = fetchTicket();
     super.initState();
   }
</code>```

答:
You can use a FutureBuilder widget, it takes a future mathed</p>

```<code>Future<Ticket> fetchTicket() async {
 final response =
    await http.get('http://hostname/getRequest');

     if (response.statusCode == 200) {
     // If the server did return a 200 OK response, then parse the JSON.
      this.data = json.decode(response.body);

     //print("Data Here: " + data.toString());
      return Ticket.fromJson(json.decode(response.body));
     } else {

    // If the server did not return a 200 OK response, then throw an exception.
    throw Exception('Failed to load Ticket');
    }

   }

     FutureBuilder(
          future: fetchTicket()(),
          builder: (BuildContext context, snapshot) {
          if (snapshot.hasData) {
            // this means the fetching is completed
            var data = snapshot.data;
            /// you can do what ever you like with [data] variable
            return YourWidget();
          } else if (snapshot.hasError) {
            // this means incomplete get Request
            return YourErrorWidget()
          }

          return CircularProgressIndicator();
        });
</code>```

Body:
I have a Future function which uses a get request and I save the request body to a variable {data}. It works well, however when I run my application and try loading a page with the data the variable is accessed before being assigned the value. It is only after I hot reload that it shows.

How do I make the whole page wait until the variable is assigned?

 static Future<Ticket> futureTicket;

 Map<String, dynamic> data;

 Future<Ticket> fetchTicket() async {
 final response =
    await http.get('http://hostname/getRequest');

     if (response.statusCode == 200) {
     // If the server did return a 200 OK response, then parse the JSON.
      this.data = json.decode(response.body);

     //print("Data Here: " + data.toString());
      return Ticket.fromJson(json.decode(response.body));
     } else {

    // If the server did not return a 200 OK response, then throw an exception.
    throw Exception('Failed to load Ticket');
    }

   }

   @override
     void initState(){
     futureTicket = fetchTicket();
     super.initState();
   }

Body:
You can use a FutureBuilder widget, it takes a future mathed

Future<Ticket> fetchTicket() async {
 final response =
    await http.get('http://hostname/getRequest');

     if (response.statusCode == 200) {
     // If the server did return a 200 OK response, then parse the JSON.
      this.data = json.decode(response.body);

     //print("Data Here: " + data.toString());
      return Ticket.fromJson(json.decode(response.body));
     } else {

    // If the server did not return a 200 OK response, then throw an exception.
    throw Exception('Failed to load Ticket');
    }

   }

     FutureBuilder(
          future: fetchTicket()(),
          builder: (BuildContext context, snapshot) {
          if (snapshot.hasData) {
            // this means the fetching is completed
            var data = snapshot.data;
            /// you can do what ever you like with [data] variable
            return YourWidget();
          } else if (snapshot.hasError) {
            // this means incomplete get Request
            return YourErrorWidget()
          }

          return CircularProgressIndicator();
        });


问:
NativeScript Google Maps Api - Google Maps is blank
I am writing an app with NativeScript v6 and Angular 8.

tns --version 6.1.2

I am using this plugin to try to display Google Maps.

The map appears and no errors are thrown but the map is blank.

Here is my code snippet:

template

```<code><Page class="page">
    <GridLayout rows="auto,*">
        <Label row="0" class="h3" text="Maps"></Label>
        <MapView
            row="1"
            #mapView
            i-padding="50,50,50,50"
            (mapReady)="onMapReady($event)"
            iosOverflowSafeArea="true">
        </MapView>
    </GridLayout>
</Page>
</code>```

component

```<code>[![import { Component, OnInit } from '@angular/core';
//import { registerElement } from 'nativescript-angular/element-registry';
import { MapView, Marker, Position } from "nativescript-google-maps-sdk";

import { ElementRef, ViewChild } from "@angular/core";
import { registerElement } from "nativescript-angular/element-registry";

// Important - must register MapView plugin in order to use in Angular templates
registerElement('MapView', () => MapView);

@Component({
    selector: "ns-clocking",
    templateUrl: "./clocking.component.html",
    styleUrls: \["./clocking.component.css"\],
    moduleId: module.id
})
export class ClockingComponent implements OnInit {

    mapView: MapView;

    constructor() {}

    public ngOnInit() {}

    public onMapReady(event) {
        console.log(" map ready ");

        const mapView = event.object;

        this.mapView = mapView;

        const NA_CENTER_LATITUDE = 39.8283459;
        const NA_CENTER_LONGITUDE = -98.5816737;

        this.mapView.latitude = NA_CENTER_LATITUDE;
        this.mapView.longitude = NA_CENTER_LONGITUDE;
        this.mapView.zoom = 3;

        const stLouisCoordinates = {
            latitude: 38.619081,
            longitude: -90.196846
        };

        const stLouisMarker = new Marker();
        stLouisMarker.position = Position.positionFromLatLng(
            stLouisCoordinates.latitude,
            stLouisCoordinates.longitude
        );
        stLouisMarker.title = "St. Louis, MO";
        stLouisMarker.snippet = "Go Cardinals!";
        stLouisMarker.color = "#6B8E23";
        this.mapView.addMarker(stLouisMarker);

    }
}
</code>```

AndroidManifest

```<code><meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/nativescript_google_maps_api_key" />
</code>```

I used the same Key in a different setting and it worked: https://jsfiddle.net/aubz88/6frk9evm/3/

答:
Yes , I have faced the same issue . Kindly check your google developer console where the Google Maps API is enabled or not for both iOS/Android.

Also for reference check this out https://market.nativescript.org/plugins/nativescript-google-maps-sdk

this works for me , use code according to your requirement Angular 8 or Plain JS/TS

Body:
I am writing an app with NativeScript v6 and Angular 8.

tns --version 6.1.2

I am using this plugin to try to display Google Maps.

The map appears and no errors are thrown but the map is blank.

Here is my code snippet:

template

<Page class="page">
    <GridLayout rows="auto,*">

        <MapView
            row="1"
            #mapView
            i-padding="50,50,50,50"
            (mapReady)="onMapReady($event)"
            iosOverflowSafeArea="true">
        </MapView>
    </GridLayout>
</Page>

component

[![import { Component, OnInit } from '@angular/core';
//import { registerElement } from 'nativescript-angular/element-registry';
import { MapView, Marker, Position } from "nativescript-google-maps-sdk";

import { ElementRef, ViewChild } from "@angular/core";
import { registerElement } from "nativescript-angular/element-registry";

// Important - must register MapView plugin in order to use in Angular templates
registerElement('MapView', () => MapView);

@Component({
    selector: "ns-clocking",
    templateUrl: "./clocking.component.html",
    styleUrls: \["./clocking.component.css"\],
    moduleId: module.id
})
export class ClockingComponent implements OnInit {

    mapView: MapView;

    constructor() {}

    public ngOnInit() {}

    public onMapReady(event) {
        console.log(" map ready ");

        const mapView = event.object;

        this.mapView = mapView;

        const NA_CENTER_LATITUDE = 39.8283459;
        const NA_CENTER_LONGITUDE = -98.5816737;

        this.mapView.latitude = NA_CENTER_LATITUDE;
        this.mapView.longitude = NA_CENTER_LONGITUDE;
        this.mapView.zoom = 3;

        const stLouisCoordinates = {
            latitude: 38.619081,
            longitude: -90.196846
        };

        const stLouisMarker = new Marker();
        stLouisMarker.position = Position.positionFromLatLng(
            stLouisCoordinates.latitude,
            stLouisCoordinates.longitude
        );
        stLouisMarker.title = "St. Louis, MO";
        stLouisMarker.snippet = "Go Cardinals!";
        stLouisMarker.color = "#6B8E23";
        this.mapView.addMarker(stLouisMarker);

    }
}

AndroidManifest

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="@string/nativescript_google_maps_api_key" />

I used the same Key in a different setting and it worked: https://jsfiddle.net/aubz88/6frk9evm/3/


问:
React Native Expo “AppLoading threw an unexpected error when loading” error
   I have a React Native project with Expo, I installed Expo client on my Android phone. It used to work well so far. But even though I didn't change any code, I now get the following error when I scan the QR code from my phone. This error is shown on terminal and phone screen keeps blank.

```<code>    import React from 'react';
import { Image } from 'react-native';
import { AppLoading } from 'expo';
import { Asset } from 'expo-asset';
import { Block, GalioProvider } from 'galio-framework';

import Screens from './navigation/Screens';
import { Images, articles, ditsTheme } from './constants';

// cache app images
const assetImages = [
  Images.Onboarding,
  Images.LogoOnboarding,
  Images.Logo,
  Images.Pro,
  Images.DITSLogo,
  Images.iOSLogo,
  Images.androidLogo
];

// cache product images
articles.map(article => assetImages.push(article.image));

function cacheImages(images) {
  return images.map(image => {
    if (typeof image === 'string') {
      return Image.prefetch(image);
    } else {
      return Asset.fromModule(image).downloadAsync();
    }
  });
}

export default class App extends React.Component {
  state = {
    isLoadingComplete: false,
  }

  render() {
    if(!this.state.isLoadingComplete) {
      return (
        <AppLoading
          startAsync={this._loadResourcesAsync}
          onError={this._handleLoadingError}
          onFinish={this._handleFinishLoading}
        />
      );
    } else {
      return (
        <GalioProvider theme={ditsTheme}>
          <Block flex>
            <Screens />
          </Block>
        </GalioProvider>
      );
    }
  }

  _loadResourcesAsync = async () => {
    return Promise.all([
      ...cacheImages(assetImages),
    ]);
  };

  _handleLoadingError = error => {
    // In this case, you might want to report the error to your error
    // reporting service, for example Sentry
     warn(error);
  };

  _handleFinishLoading = () => {
    this.setState({ isLoadingComplete: true });
  };

}
</code>```

How can I solve this error?

答: In your _handleLoadingError method, you're using warn. While you should be using console.warn. This is what's breaking your app.

Body:
   I have a React Native project with Expo, I installed Expo client on my Android phone. It used to work well so far. But even though I didn't change any code, I now get the following error when I scan the QR code from my phone. This error is shown on terminal and phone screen keeps blank.

    import React from 'react';
import { Image } from 'react-native';
import { AppLoading } from 'expo';
import { Asset } from 'expo-asset';
import { Block, GalioProvider } from 'galio-framework';

import Screens from './navigation/Screens';
import { Images, articles, ditsTheme } from './constants';

// cache app images
const assetImages = [
  Images.Onboarding,
  Images.LogoOnboarding,
  Images.Logo,
  Images.Pro,
  Images.DITSLogo,
  Images.iOSLogo,
  Images.androidLogo
];

// cache product images
articles.map(article => assetImages.push(article.image));

function cacheImages(images) {
  return images.map(image => {
    if (typeof image === 'string') {
      return Image.prefetch(image);
    } else {
      return Asset.fromModule(image).downloadAsync();
    }
  });
}

export default class App extends React.Component {
  state = {
    isLoadingComplete: false,
  }

  render() {
    if(!this.state.isLoadingComplete) {
      return (
        <AppLoading
          startAsync={this._loadResourcesAsync}
          onError={this._handleLoadingError}
          onFinish={this._handleFinishLoading}
        />
      );
    } else {
      return (
        <GalioProvider theme={ditsTheme}>
          <Block flex>
            <Screens />
          </Block>
        </GalioProvider>
      );
    }
  }

  _loadResourcesAsync = async () => {
    return Promise.all([
      ...cacheImages(assetImages),
    ]);
  };

  _handleLoadingError = error => {
    // In this case, you might want to report the error to your error
    // reporting service, for example Sentry
     warn(error);
  };

  _handleFinishLoading = () => {
    this.setState({ isLoadingComplete: true });
  };

}

How can I solve this error?


问:
Concatenating file paths while overriding window file name length problem
I am having problems with the concatenation of a server directory path using python 3.7. I have it working but need to bring in this code (as discussed here) so as to override the max 260 character limit on windows director paths.

```<code>\\\\?\\UNC
</code>```

Just can't seem to get the syntax-correct. The function below is working (brings back matches) without the UNC added. But when it hits a long filename it crashes the program.

```<code>def file_path(data):
    latest_file_list = []
    for index, row in data.iterrows():
        log1 = row['Log number 2001']
        file_path = row['file_path_short']
        location = r"" +str(file_path)+ "*\*\*\*\**\*"+ str(log1) +"*.pdf"
        # check file on drive
        list_of_files = glob.glob(location, recursive=True)
</code>```

location equates to:

```<code>\\servername\...
</code>```

The code below is what I am testing to fix the character limit, it does not give an error but also does not return any matches.

```<code>location2 = r"\\\\?\\UNC" +str(file_path)+ "*\*\*\*\**\**\*"+ str(log1) +"*.pdf"
</code>```

location2 equates to

```<code>\\?\UNC\servername\...
</code>```

I have tried prefixing with u and r but that does not help.

Can anyone give some guidance please? Is there a better/simpler solution?

Edit

I have also tried this which works for short file names but gives [WinError 3] error for long file names.

```<code>import os
location3 = os.path.join(r"\\\\?\\UNC", str(file_path), "*\*\**", "*"+ str(log1) +"*" +".pdf" )
</code>```

Edit2

So I have been playing around with pathlib using this code:

```<code>from pathlib import Path
location4 = Path(r"\\\\?\\UNC", str(file_path), "*\*\**", "*"+ str(log1) +"*" +".pdf" )
</code>```

But I am getting this error currently TypeError: expected string or bytes-like object

答:
So the way I got this working, in the end, was to use a mapped file path. I have the network drive I am accessing mapped to my Z drive. I used this code to access it. It works fine just I have to make sure I have accessed the drive first before running the code.

```<code>location = "\\\\?\\Z:" +str(file_path)+ "*\*\*\*\**\*"+ str(log1) +"*.pdf"
</code>```

So I have moved from \\server\folder1\folder2\foldere3.. to Z:\foldere2\foldere3.. so when concatenated together \\\\?\\Z:\folder2\folder3..

Body:
I am having problems with the concatenation of a server directory path using python 3.7. I have it working but need to bring in this code (as discussed here) so as to override the max 260 character limit on windows director paths.

\\\\?\\UNC

Just can't seem to get the syntax-correct. The function below is working (brings back matches) without the UNC added. But when it hits a long filename it crashes the program.

def file_path(data):
    latest_file_list = []
    for index, row in data.iterrows():
        log1 = row['Log number 2001']
        file_path = row['file_path_short']
        location = r"" +str(file_path)+ "*\*\*\*\**\*"+ str(log1) +"*.pdf"
        # check file on drive
        list_of_files = glob.glob(location, recursive=True)

location equates to:

\\servername\...

The code below is what I am testing to fix the character limit, it does not give an error but also does not return any matches.

location2 = r"\\\\?\\UNC" +str(file_path)+ "*\*\*\*\**\**\*"+ str(log1) +"*.pdf"

location2 equates to

\\?\UNC\servername\...

I have tried prefixing with u and r but that does not help.

Can anyone give some guidance please? Is there a better/simpler solution?

Edit

I have also tried this which works for short file names but gives [WinError 3] error for long file names.

import os
location3 = os.path.join(r"\\\\?\\UNC", str(file_path), "*\*\**", "*"+ str(log1) +"*" +".pdf" )

Edit2

So I have been playing around with pathlib using this code:

from pathlib import Path
location4 = Path(r"\\\\?\\UNC", str(file_path), "*\*\**", "*"+ str(log1) +"*" +".pdf" )

But I am getting this error currently TypeError: expected string or bytes-like object

Body:
So the way I got this working, in the end, was to use a mapped file path. I have the network drive I am accessing mapped to my Z drive. I used this code to access it. It works fine just I have to make sure I have accessed the drive first before running the code.

location = "\\\\?\\Z:" +str(file_path)+ "*\*\*\*\**\*"+ str(log1) +"*.pdf"

So I have moved from \\server\folder1\folder2\foldere3.. to Z:\foldere2\foldere3.. so when concatenated together \\\\?\\Z:\folder2\folder3..