问:
nginx serve a specific directory for a specific location
I need for development purpose (not for production of course), to serve my logs that are in my folder /app/logs/.

So I've setup a configuration like this :

```<code>    server {
        listen 80;
        server_name server-name.com;
        error_log  /app/logs/error.log warn;
        access_log /app/logs/access.log compression;
        root /var/www;

        location /info/logs/ {
            alias /app/logs/;
            autoindex on;
        }

        location / {
          // others route working
        }
    }
</code>```

But everytimes i try to access to something like /app/logs/django.log using http://server-name.com/info/logs/django.log, I get a 404 and not the file I asked for.

I've tried many things like chmod -R 755 the entire folder or setting the folder to the user nginx use (in my case for now root, I know it's bad), tried root or try_files but I just can't access it...

I've seen many topics here and there but can't find a clue...

Can you help me with this please ?

PS : I need the root /var/www at the beginning for others locations.

PS2 : I'm using a Docker based on Debian 9.

答:
If you are using the standard NGINX Docker container, then the default configuration is to send the Access and Error logs to the Docker log collector. Not the standard log output for NGINX.

The result is that your log files are most likely going to:

file/var/lib/docker/containers/<container id>/<container id>-json.log
on the Docker Host. Where <container id> is the long-form version of the Container Id specified when the container was setup in the first place.

To get to the default log files you can do: docker logs <container name>

To find the <container id> you can do: docker inspect --format '{{ .Id }}' <container name>

If you want to customize where the log files go, then you need to create a helper Docker container that the log files can be written too.

Body:
I need for development purpose (not for production of course), to serve my logs that are in my folder /app/logs/.

So I've setup a configuration like this :

    server {
        listen 80;
        server_name server-name.com;
        error_log  /app/logs/error.log warn;
        access_log /app/logs/access.log compression;
        root /var/www;

        location /info/logs/ {
            alias /app/logs/;
            autoindex on;
        }

        location / {
          // others route working
        }
    }

But everytimes i try to access to something like /app/logs/django.log using http://server-name.com/info/logs/django.log, I get a 404 and not the file I asked for.

I've tried many things like chmod -R 755 the entire folder or setting the folder to the user nginx use (in my case for now root, I know it's bad), tried root or try_files but I just can't access it...

I've seen many topics here and there but can't find a clue...

Can you help me with this please ?

PS : I need the root /var/www at the beginning for others locations.

PS2 : I'm using a Docker based on Debian 9.


来源: stackexchange

问:
Chart.js label and point getting cutoff on the right
It seems as though the last date label is getting cutoff on my chart here in chart.js. There should be a data point for 2018.
When researching it I've seen it suggested to add layout padding.
I tried that but it disables the chart entirely. Anyone have an alternative solution or an idea on why my layout padding does not work?

```<code>        var myChart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: dollar.years,
            datasets: [
              {label: 'Cdn dollar in cents',
                data: dollar.vals,
                borderColor: 'rgb(153,222,101)',
                backgroundColor: 'rgb(153,222,101, 0.2)',
                pointRadius: 0,
                borderWidth: 6,
                }]
              },

options: {
responsive: true,
title: {
display: false
},

legend: {
display: false
},

labels: {
padding:1
},

scales: {
yAxes: [{
ticks: {
min: 0,
max: 5,
stepSize: 1
}
}],

xAxes: [{
type: "time",
time: {
unit: "year",
tooltipFormat: "YYYY"
},

ticks: {
display: true,
labelOffset: -1,
maxTicksLimit: 5,
drawOnChartArea: false,
autoSkip: false,
maxRotation: 0,
minRotation: 0,
padding: 5

},
}],

}
}
  });
  }
</code>```

答:
The option layout.padding work as below code snippet illustrates. You however need to carefully choose the values (number of pixels) in order to not completely hide the chart area.

I would however rather define xAxes.ticks.max to make sure the tick for 2018 is shown even if data would be available up to 2017 only.

const years = [];
const vals = [];
for (let year = 1968; year <= 2018; year++) {
  years.push(year.toString());
  vals.push(Math.floor(Math.random() * 3) + 1);
}

var myChart = new Chart(document.getElementById("myChart"), {
  type: 'line',
  data: {
    labels: years,
    datasets: [{
      label: 'Cdn dollar in cents',
      data: vals,
      borderColor: 'rgb(153,222,101)',
      backgroundColor: 'rgb(153,222,101, 0.2)',
      pointRadius: 0,
      borderWidth: 6
    }]
  },
  options: {
    responsive: true,
    layout: {
      padding: {
        left: 0,
        right: 100,
        top: 0,
        bottom: 0
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          max: 4,
          stepSize: 1
        }
      }],
      xAxes: [{
        type: "time",
        time: {
          parser: 'YYYY',
          unit: "year",
          tooltipFormat: "YYYY"
        },
        ticks: {
          max: "2018",
          maxTicksLimit: 5,
          maxRotation: 0
        }
      }]
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  max-width: 400px;
}</code>```

<canvas id="myChart" width="600" height="400"></canvas>```

ContentLicense: CC BY-SA 4.0

Body:
It seems as though the last date label is getting cutoff on my chart here in chart.js. There should be a data point for 2018.
When researching it I've seen it suggested to add layout padding.
I tried that but it disables the chart entirely. Anyone have an alternative solution or an idea on why my layout padding does not work?

        var myChart = new Chart(ctx, {
          type: 'line',
          data: {
            labels: dollar.years,
            datasets: [
              {label: 'Cdn dollar in cents',
                data: dollar.vals,
                borderColor: 'rgb(153,222,101)',
                backgroundColor: 'rgb(153,222,101, 0.2)',
                pointRadius: 0,
                borderWidth: 6,
                }]
              },

options: {
responsive: true,
title: {
display: false
},

legend: {
display: false
},

labels: {
padding:1
},

scales: {
yAxes: [{
ticks: {
min: 0,
max: 5,
stepSize: 1
}
}],

xAxes: [{
type: "time",
time: {
unit: "year",
tooltipFormat: "YYYY"
},

ticks: {
display: true,
labelOffset: -1,
maxTicksLimit: 5,
drawOnChartArea: false,
autoSkip: false,
maxRotation: 0,
minRotation: 0,
padding: 5

},
}],

}
}
  });
  }

Body:
The option layout.padding work as below code snippet illustrates. You however need to carefully choose the values (number of pixels) in order to not completely hide the chart area.

I would however rather define xAxes.ticks.max to make sure the tick for 2018 is shown even if data would be available up to 2017 only.

const years = [];
const vals = [];
for (let year = 1968; year <= 2018; year++) {
  years.push(year.toString());
  vals.push(Math.floor(Math.random() * 3) + 1);
}

var myChart = new Chart(document.getElementById("myChart"), {
  type: 'line',
  data: {
    labels: years,
    datasets: [{
      label: 'Cdn dollar in cents',
      data: vals,
      borderColor: 'rgb(153,222,101)',
      backgroundColor: 'rgb(153,222,101, 0.2)',
      pointRadius: 0,
      borderWidth: 6
    }]
  },
  options: {
    responsive: true,
    layout: {
      padding: {
        left: 0,
        right: 100,
        top: 0,
        bottom: 0
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          max: 4,
          stepSize: 1
        }
      }],
      xAxes: [{
        type: "time",
        time: {
          parser: 'YYYY',
          unit: "year",
          tooltipFormat: "YYYY"
        },
        ticks: {
          max: "2018",
          maxTicksLimit: 5,
          maxRotation: 0
        }
      }]
    }
  }
});

canvas {
  max-width: 400px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>
<canvas id="myChart" width="600" height="400"></canvas>


问:
Azure build Pipeline gets failed. Unable to find a dependent package
I am building the project through the Azure pipeline. The project is building locally but failing in the pipeline.
.

Error:- The type or namespace name 'CommonModules' could not be found (are you missing a using directive or an assembly reference?)

答:
I am able to solve the issue by adding ProjectRefernce in csproj file.
Actually earlier I am adding a reference of the file locally. Azure deployment is not able to find it. To host our solution, one needs to add ProjectRefernce</p>


问:
ng command giving error, SyntaxError: Unexpected token ). centos 7
I faced an issue on the centOs7 server while checking the version of angular-cli by ng -v.
I got the output as below:

```<code>/usr/lib/node_modules/@angular/cli/bin/ng:23
  );
  ^
SyntaxError: Unexpected token )
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.runMain (module.js:611:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:160:9)
</code>```

Even not able to build the project because of this issue, I am using Jenkins for making build.

答:
To resolve this issue,
I performed the following steps:

sudo vi /usr/lib/node_modules/@angular/cli/bin/ng

find the syntax,

```<code>var version = process.versions.node.split('.').map(part => Number(part));
if (version[0] < 10 || version[0] === 11 || (version[0] === 10 && version[1] < 13)) {
  process.stderr.write(
    'Node.js version ' + process.version + ' detected.\n' +
    'The Angular CLI requires a minimum Node.js version of either v10.13 or v12.0.\n\n' +
    'Please update your Node.js version or visit https://nodejs.org/ for additional instructions.\n',
  );
}
</code>```

remove extra comma(,) after \n

save the file and exit

This will resolve the issue.
I hope this will help.

Body:
I faced an issue on the centOs7 server while checking the version of angular-cli by ng -v.
I got the output as below:

/usr/lib/node_modules/@angular/cli/bin/ng:23
  );
  ^
SyntaxError: Unexpected token )
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.runMain (module.js:611:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:160:9)

Even not able to build the project because of this issue, I am using Jenkins for making build.

Body:
To resolve this issue,
I performed the following steps:

sudo vi /usr/lib/node_modules/@angular/cli/bin/ng

find the syntax,

var version = process.versions.node.split('.').map(part => Number(part));
if (version[0] < 10 || version[0] === 11 || (version[0] === 10 && version[1] < 13)) {
  process.stderr.write(
    'Node.js version ' + process.version + ' detected.\n' +
    'The Angular CLI requires a minimum Node.js version of either v10.13 or v12.0.\n\n' +
    'Please update your Node.js version or visit https://nodejs.org/ for additional instructions.\n',
  );
}

remove extra comma(,) after \n

save the file and exit

This will resolve the issue.
I hope this will help.


问:
How do I store the key and value into hashmap and print it out accordingly?
Currently, I am retrieving data from a csv file and storing the data into a hashmap. However, when I print out the content of the hashmap, it is not in the order that I thought it would be. How do I format the hashmap such that it would print in the order of dec -> jan -> feb ?

CODE

```<code>public static void main(String[] args) throws ParseException {
    //readXLSXFile("C:\\Users\\User\\Desktop\\AllSgStuffdata2.xlsx");
    HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
    int febCounter = 0;
    int janCounter = 0;
    int decCounter = 0;
    String pattern = "MMM";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    try (Reader reader = Files.newBufferedReader(Paths.get("file_path"));
            CSVReader csvReader = new CSVReader(reader);){
        String [] nextRecord;
        while((nextRecord = csvReader.readNext()) != null) {
            //Date date = sdf.parse(nextRecord[2]);
            //System.out.println(date);
            String retrievedate = nextRecord[2];
            Date date = sdf.parse(retrievedate);
            String strDate = sdf.format(date);
            //System.out.println(strDate);

            if(strDate.equals("Dec")) {
                decCounter++;
            }
            else if (strDate.equals("Jan")) {
                janCounter++;
            }
            else if (strDate.equals("Feb")) {
                febCounter++;
            }
        }
        numberOfPost.put("December", decCounter);
        numberOfPost.put("January", janCounter);
        numberOfPost.put("Feburary", febCounter);
        System.out.println(numberOfPost);
    } catch(IOException | ParseException e) {
        System.out.print("File can't be found");
    }
}
</code>```

CURRENT OUTPUT

```<code>{Feburary=365, December=303, January=582}
</code>```

DESIRED OUTPUT

```<code>{December=303, January=582, Feburary=365}
</code>```

答:
You can use linked hash map which maintain the order of insertion

```<code> LinkedHashMap<String, String> lhm =
                       new LinkedHashMap<String, String>();
        lhm.put("one", "1");
        lhm.put("two", "2");
        lhm.put("four", "3");
System.out.println(lhm);
</code>```

output->

{one=1, two=2,four=3}

Body:
Currently, I am retrieving data from a csv file and storing the data into a hashmap. However, when I print out the content of the hashmap, it is not in the order that I thought it would be. How do I format the hashmap such that it would print in the order of dec -> jan -> feb ?

CODE

public static void main(String[] args) throws ParseException {
    //readXLSXFile("C:\\Users\\User\\Desktop\\AllSgStuffdata2.xlsx");
    HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
    int febCounter = 0;
    int janCounter = 0;
    int decCounter = 0;
    String pattern = "MMM";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    try (Reader reader = Files.newBufferedReader(Paths.get("file_path"));
            CSVReader csvReader = new CSVReader(reader);){
        String [] nextRecord;
        while((nextRecord = csvReader.readNext()) != null) {
            //Date date = sdf.parse(nextRecord[2]);
            //System.out.println(date);
            String retrievedate = nextRecord[2];
            Date date = sdf.parse(retrievedate);
            String strDate = sdf.format(date);
            //System.out.println(strDate);

            if(strDate.equals("Dec")) {
                decCounter++;
            }
            else if (strDate.equals("Jan")) {
                janCounter++;
            }
            else if (strDate.equals("Feb")) {
                febCounter++;
            }
        }
        numberOfPost.put("December", decCounter);
        numberOfPost.put("January", janCounter);
        numberOfPost.put("Feburary", febCounter);
        System.out.println(numberOfPost);
    } catch(IOException | ParseException e) {
        System.out.print("File can't be found");
    }
}

CURRENT OUTPUT

{Feburary=365, December=303, January=582}

DESIRED OUTPUT

{December=303, January=582, Feburary=365}

Body:
You can use linked hash map which maintain the order of insertion

 LinkedHashMap<String, String> lhm =
                       new LinkedHashMap<String, String>();
        lhm.put("one", "1");
        lhm.put("two", "2");
        lhm.put("four", "3");
System.out.println(lhm);

output->

{one=1, two=2,four=3}


问:
Flutter App Running Error: Dart can not be opened, Developer can not be verified after upgrading to Catalina
I was using the latest version of Android Studio IDE for creating flutter apps. But when I upgraded from Mojave to Catalina and tried to open my flutter code on IDE it gave me an error saying:

Dart can not be opened because the Developer can not be verified

What is the reason behind the error and how can I solve the issue?

Do I have to install flutter and relative development tools from scratch again or is there any other way to resolve the issue?

答: This issue can be resolved by deleting the artefacts directory and running flutter doctor once again - More Info Here


问:
How to change state (src of img) clojurescript component after reagent-render with click events
We have touching clojurescript code, but when the image changes when clicking a thumbnail the selected image needs to render with zoomer.

We start clicking the thumbnail, this changes the atom with the selected image, and passes to the zoomer code:

```<code>    (r/with-let [selected (r/atom (-> images first))]
        [:img.mx-auto.d-block.img-thumbnail {
          :src        thumbnail_small
          :on-click   #(reset! selected img)}]

        [:div.col-sm-10
              [zoomer selected]
         ]
        ]])
</code>```

To mount the component with the image url. Passes url of the original size of the image zoomer [image] when rendering the component-did-mount (first time) works [:img {:src   image, but when clicking in another image, the atom reacts but does not "rerender":

```<code>(defn zoomer [image]
   (let [!hammer-manager (atom nil)
         !zoom           (atom {:x 0 :y 0 :scale 1})
         !start-zoom     (atom {:x 0 :y 0 :scale 1})]

    (r/create-class
     {:component-did-mount
     (fn [this]
       (let [mc (new js/Hammer.Manager (r/dom-node this))]
       (println this.add)
       ;; Pinch
       (js-invoke mc "add" (new js/Hammer.Pinch))
       (js-invoke mc "on" "pinchstart" #(do (reset! !start-zoom @!zoom)
                                            (.preventDefault %)))
       (js-invoke mc "on" "pinchmove" #(let [{:keys [x y scale]} @!start-zoom]
                                        (reset! !zoom {:x     (+ x (.-deltaX %))
                                                       :y     (+ y (.-deltaY %))
                                                       :scale (* scale (.-scale %))})
                                        (.preventDefault %)))
       (reset! !hammer-manager mc)
      ))

   :reagent-render
   (fn [_]
     [:div.zoomer
      [:img {:src   image
             :style (transform @!zoom)}]])

   :component-will-unmount
   (fn [_]
     (when-let [mc @!hammer-manager]
       (js-invoke mc "destroy")))})))
</code>```

I saw this example Using Stateful JS Components with G Maps.

答:
I found a solution.

1.- Change :reagent-render to :render.

2.- In :render add a let with reagent/argv to take the params. This forever take the second [_ **image**]:

```<code> :render
 (fn [this]
   (let [[_ image] (r/argv this)]
     [:div.zoomer
      [:img {:src   image
             :style (transform @!zoom)}]]))
</code>```

Is optional to write a param here: (defn zoomer [image]. This works (defn zoomer [] if we use r/argv it this found the params.

This example helped me
Allowing lifecycle metadata on inner component fns and this documentation of reagent method form 3.

Body:
We have touching clojurescript code, but when the image changes when clicking a thumbnail the selected image needs to render with zoomer.

We start clicking the thumbnail, this changes the atom with the selected image, and passes to the zoomer code:

    (r/with-let [selected (r/atom (-> images first))]
        [:img.mx-auto.d-block.img-thumbnail {
          :src        thumbnail_small
          :on-click   #(reset! selected img)}]

        [:div.col-sm-10
              [zoomer selected]
         ]
        ]])

To mount the component with the image url. Passes url of the original size of the image zoomer [image] when rendering the component-did-mount (first time) works [:img {:src   image, but when clicking in another image, the atom reacts but does not "rerender":

(defn zoomer [image]
   (let [!hammer-manager (atom nil)
         !zoom           (atom {:x 0 :y 0 :scale 1})
         !start-zoom     (atom {:x 0 :y 0 :scale 1})]

    (r/create-class
     {:component-did-mount
     (fn [this]
       (let [mc (new js/Hammer.Manager (r/dom-node this))]
       (println this.add)
       ;; Pinch
       (js-invoke mc "add" (new js/Hammer.Pinch))
       (js-invoke mc "on" "pinchstart" #(do (reset! !start-zoom @!zoom)
                                            (.preventDefault %)))
       (js-invoke mc "on" "pinchmove" #(let [{:keys [x y scale]} @!start-zoom]
                                        (reset! !zoom {:x     (+ x (.-deltaX %))
                                                       :y     (+ y (.-deltaY %))
                                                       :scale (* scale (.-scale %))})
                                        (.preventDefault %)))
       (reset! !hammer-manager mc)
      ))

   :reagent-render
   (fn [_]
     [:div.zoomer
      [:img {:src   image
             :style (transform @!zoom)}]])

   :component-will-unmount
   (fn [_]
     (when-let [mc @!hammer-manager]
       (js-invoke mc "destroy")))})))

I saw this example Using Stateful JS Components with G Maps.

Body:
I found a solution.

1.- Change :reagent-render to :render.

2.- In :render add a let with reagent/argv to take the params. This forever take the second [_ **image**]:

 :render
 (fn [this]
   (let [[_ image] (r/argv this)]
     [:div.zoomer
      [:img {:src   image
             :style (transform @!zoom)}]]))

Is optional to write a param here: (defn zoomer [image]. This works (defn zoomer [] if we use r/argv it this found the params.

This example helped me
Allowing lifecycle metadata on inner component fns and this documentation of reagent method form 3.


问:
Kivy Weather App How to Print Output to label?
I am trying to figure out how to print the result of the weather from the tellweather () class into a text label in kivy.But it wont work Error:
TypeError: __init __ () takes 1 positional argument but 2 were given  . Normally the result is "its 24 Temp".I now have the following code:

```<code>import kivy
import requests
import json
from kivy.app import App
from kivy.uix.label import Label
class tell_weather():
    url ='http://api.openweathermap.org/data/2.5/weather?q=appid=xxxxxx"'
    json_data = requests.get(url).json()
    format_add = json_data['main']['temp']
    print("Its", format_add, "Temp")

    kivy.require("1.9.1")

class MyLabelApp(App):
    def build(self):
        label display the text on screen
            lbl = Label(tell_weather())
        #lbl = Label(tellweather())
        return lbl

    # creating the object

label = MyLabelApp()
label.run()

</code>```

答:
Label works another way, to put text there you just should use parameter 'text', so your code should be like:</p>

```<code># it's not a class, it's a function!
def tell_weather():
    url ='http://api.openweathermap.org/data/2.5/weather?q=appid=xxxxxx"'
    json_data = requests.get(url).json()
    format_add = json_data['main']['temp']
    # print makes output to console, it's wrong, here you should return string
    return("Its " + str(format_add) + " Temp")

class MyLabelApp(App):
    def build(self):
        # what's that line doing here? Comment it!
        # label display the text on screen

            # so here we use text parameter that will be equal to string that function tell_weather returns
            lbl = Label(text=tell_weather())
        return lbl
</code>```

Body:
I am trying to figure out how to print the result of the weather from the tellweather () class into a text label in kivy.But it wont work Error:
TypeError: __init __ () takes 1 positional argument but 2 were given  . Normally the result is "its 24 Temp".I now have the following code:

import kivy
import requests
import json
from kivy.app import App
from kivy.uix.label import Label
class tell_weather():
    url ='http://api.openweathermap.org/data/2.5/weather?q=appid=xxxxxx"'
    json_data = requests.get(url).json()
    format_add = json_data['main']['temp']
    print("Its", format_add, "Temp")

    kivy.require("1.9.1")

class MyLabelApp(App):
    def build(self):
        label display the text on screen
            lbl = Label(tell_weather())
        #lbl = Label(tellweather())
        return lbl

    # creating the object

label = MyLabelApp()
label.run()

Body:
Label works another way, to put text there you just should use parameter 'text', so your code should be like:

# it's not a class, it's a function!
def tell_weather():
    url ='http://api.openweathermap.org/data/2.5/weather?q=appid=xxxxxx"'
    json_data = requests.get(url).json()
    format_add = json_data['main']['temp']
    # print makes output to console, it's wrong, here you should return string
    return("Its " + str(format_add) + " Temp")

class MyLabelApp(App):
    def build(self):
        # what's that line doing here? Comment it!
        # label display the text on screen

            # so here we use text parameter that will be equal to string that function tell_weather returns
            lbl = Label(text=tell_weather())
        return lbl


问:
Training Spacy NER on custom dataset gives error
I am trying to train spacy NER model on custom dataset. Basically I want to use this model to extract Name, Organization, Email, phone number etc from resume.

Below is the code I am using.

```<code>import json
import random
import spacy
import sys
import logging
from sklearn.metrics import classification_report
from sklearn.metrics import precision_recall_fscore_support
from spacy.gold import GoldParse
from spacy.scorer import Scorer
from sklearn.metrics import accuracy_score
from spacy.gold import biluo_tags_from_offsets
def convert_dataturks_to_spacy(dataturks_JSON_FilePath):

    try:
        training_data = []
        lines=[]
        with open(dataturks_JSON_FilePath, encoding='utf-8') as f:
            lines = f.readlines()
        for line in lines:
            data = json.loads(line)
            text = data['content']
            entities = []
            for annotation in data['annotation']:
                #only a single point in text annotation.
                point = annotation['points'][0]
                labels = annotation['label']
                if not isinstance(labels, list):
                    labels = [labels]

                for label in labels:
                    entities.append((point['start'], point['end'] + 1 ,label))

            training_data.append((text, {"entities" : entities}))
        return training_data
    except Exception as e:
        logging.exception("Unable to process " + dataturks_JSON_FilePath + "\n" + "error = " + str(e))
        return None

def reformat_train_data(tokenizer, examples):
    output = []
    for i, (text, entity_offsets) in enumerate(examples):
        doc = tokenizer(text.strip())
        ner_tags = biluo_tags_from_offsets(tokenizer(text), entity_offsets['entities'])
        words = [w.text for w in doc]
        tags = ['-'] * len(doc)
        heads = [0] * len(doc)
        deps = [''] * len(doc)
        sentence = (range(len(doc)), words, tags, heads, deps, ner_tags)
        output.append((text, [(sentence, [])]))
    print("output",output)
    return output
################### Train Spacy NER.###########
def train_spacy():
    TRAIN_DATA = convert_dataturks_to_spacy("C:\\Users\\akjain\\Downloads\\Entity-Recognition-In-Resumes-SpaCy-master\\traindata.json")
    nlp = spacy.blank("en")
    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)
    # add labels
    for _, annotations in TRAIN_DATA:
        for ent in annotations.get('entities'):
            ner.add_label(ent[2])

    def get_data(): return reformat_train_data(nlp.tokenizer, TRAIN_DATA)
    optimizer = nlp.begin_training(get_data)
    for itn in range(10):
        print("Starting iteration " + str(itn))
        random.shuffle(TRAIN_DATA)
        losses = {}
        for text, annotations in TRAIN_DATA:
            nlp.update(
                [text],  # batch of texts
                [annotations],  # batch of annotations
                drop=0.2,  # dropout - make it harder to memorise data
                sgd=optimizer,  # callable to update weights
                losses=losses)
        print(losses)
train_spacy()
</code>```

I am getting the below error. Also, I came across a link (https://github.com/explosion/spaCy/issues/3558)  with some suggestion to fix this code. But even after implementing that I am still getting error.

I am using Python 3.6.5 and Spacy 2.2.3

Dataset:

```<code>{"content": "Nida Khan\nTech Support Executive - Teleperformance for Microsoft\n\nJaipur, Rajasthan - Email me on Indeed: indeed.com/r/Nida-Khan/6c9160696f57efd8\n\n• To be an integral part of the organization and enhance my knowledge to utilize it in a productive\nmanner for the growth of the company and the global.\n\nINDUSTRIAL TRAINING\n\n• BHEL, (HEEP) HARIDWAR\nOn CNC System& PLC Programming.\n\nWORK EXPERIENCE\n\nTech Support Executive\n\nTeleperformance for Microsoft -\n\nSeptember 2017 to Present\n\nprocess.\n• 21 months of experience in ADFC as Phone Banker.\n\nEDUCATION\n\nBachelor of Technology in Electronics & communication Engg\n\nGNIT institute of Technology -  Lucknow, Uttar Pradesh\n\n2008 to 2012\n\nClass XII\n\nU.P. Board -  Bareilly, Uttar Pradesh\n\n2007\n\nClass X\n\nU.P. Board -  Bareilly, Uttar Pradesh\n\n2005\n\nSKILLS\n\nMicrosoft office, excel, cisco, c language, cbs. (4 years)\n\nhttps://www.indeed.com/r/Nida-Khan/6c9160696f57efd8?isid=rex-download&ikw=download-top&co=IN","annotation":[{"label":["Email Address"],"points":[{"start":872,"end":910,"text":"indeed.com/r/Nida-Khan/6c9160696f57efd8"}]},{"label":["Skills"],"points":[{"start":800,"end":857,"text":"Microsoft office, excel, cisco, c language, cbs. (4 years)"}]},{"label":["Graduation Year"],"points":[{"start":676,"end":679,"text":"2012"}]},{"label":["College Name"],"points":[{"start":612,"end":640,"text":"GNIT institute of Technology "}]},{"label":["Degree"],"points":[{"start":552,"end":609,"text":"Bachelor of Technology in Electronics & communication Engg"}]},{"label":["Companies worked at"],"points":[{"start":420,"end":448,"text":"Teleperformance for Microsoft"}]},{"label":["Designation"],"points":[{"start":395,"end":417,"text":"\nTech Support Executive"}]},{"label":["Email Address"],"points":[{"start":106,"end":144,"text":"indeed.com/r/Nida-Khan/6c9160696f57efd8"}]},{"label":["Location"],"points":[{"start":66,"end":71,"text":"Jaipur"}]},{"label":["Companies worked at"],"points":[{"start":35,"end":63,"text":"Teleperformance for Microsoft"}]},{"label":["Designation"],"points":[{"start":10,"end":32,"text":"Tech Support Executive "}]},{"label":["Designation"],"points":[{"start":9,"end":31,"text":"\nTech Support Executive"}]},{"label":["Name"],"points":[{"start":0,"end":8,"text":"Nida Khan"}]}]}
</code>```

答:
The problem is you are feeding training data to model optimizer.

As mentioned in https://github.com/explosion/spaCy/issues/3558, use the following function to remove leading and trailing white spaces from entity spans.

```<code>def trim_entity_spans(data: list) -> list:
    """Removes leading and trailing white spaces from entity spans.

    Args:
    data (list): The data to be cleaned in spaCy JSON format.

    Returns:
    list: The cleaned data.
    """
    invalid_span_tokens = re.compile(r'\s')

    cleaned_data = []
    for text, annotations in data:
        entities = annotations['entities']
        valid_entities = []
        for start, end, label in entities:
            valid_start = start
            valid_end = end
            # if there's preceding spaces, move the start position to nearest character
            while valid_start < len(text) and invalid_span_tokens.match(
                    text[valid_start]):
                valid_start += 1
            while valid_end > 1 and invalid_span_tokens.match(
                    text[valid_end - 1]):
                valid_end -= 1
            valid_entities.append([valid_start, valid_end, label])
        cleaned_data.append([text, {'entities': valid_entities}])
    return cleaned_data
</code>```

Then use the following function for training:

```<code>def train_spacy():

    TRAIN_DATA = convert_dataturks_to_spacy("C:\\Users\\akjain\\Downloads\\Entity-Recognition-In-Resumes-SpaCy-master\\traindata.json")
    TRAIN_DATA = trim_entity_spans(TRAIN_DATA)
    nlp = spacy.blank('en')  # create blank Language class
    # create the built-in pipeline components and add them to the pipeline
    # nlp.create_pipe works for built-ins that are registered with spaCy
    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)

    # add labels
    for _, annotations in TRAIN_DATA:
         for ent in annotations.get('entities'):
            ner.add_label(ent[2])

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
    with nlp.disable_pipes(*other_pipes):  # only train NER
        optimizer = nlp.begin_training()
        for itn in range(10):
            print("Statring iteration " + str(itn))
            random.shuffle(TRAIN_DATA)
            losses = {}
            for text, annotations in TRAIN_DATA:
                nlp.update(
                [text],  # batch of texts
                [annotations],  # batch of annotations
                drop=0.2,  # dropout - make it harder to memorise data
                sgd=optimizer,  # callable to update weights
                losses=losses)
            print(losses)
</code>```

Body:
I am trying to train spacy NER model on custom dataset. Basically I want to use this model to extract Name, Organization, Email, phone number etc from resume.

Below is the code I am using.

import json
import random
import spacy
import sys
import logging
from sklearn.metrics import classification_report
from sklearn.metrics import precision_recall_fscore_support
from spacy.gold import GoldParse
from spacy.scorer import Scorer
from sklearn.metrics import accuracy_score
from spacy.gold import biluo_tags_from_offsets
def convert_dataturks_to_spacy(dataturks_JSON_FilePath):

    try:
        training_data = []
        lines=[]
        with open(dataturks_JSON_FilePath, encoding='utf-8') as f:
            lines = f.readlines()
        for line in lines:
            data = json.loads(line)
            text = data['content']
            entities = []
            for annotation in data['annotation']:
                #only a single point in text annotation.
                point = annotation['points'][0]
                labels = annotation['label']
                if not isinstance(labels, list):
                    labels = [labels]

                for label in labels:
                    entities.append((point['start'], point['end'] + 1 ,label))

            training_data.append((text, {"entities" : entities}))
        return training_data
    except Exception as e:
        logging.exception("Unable to process " + dataturks_JSON_FilePath + "\n" + "error = " + str(e))
        return None

def reformat_train_data(tokenizer, examples):
    output = []
    for i, (text, entity_offsets) in enumerate(examples):
        doc = tokenizer(text.strip())
        ner_tags = biluo_tags_from_offsets(tokenizer(text), entity_offsets['entities'])
        words = [w.text for w in doc]
        tags = ['-'] * len(doc)
        heads = [0] * len(doc)
        deps = [''] * len(doc)
        sentence = (range(len(doc)), words, tags, heads, deps, ner_tags)
        output.append((text, [(sentence, [])]))
    print("output",output)
    return output
################### Train Spacy NER.###########
def train_spacy():
    TRAIN_DATA = convert_dataturks_to_spacy("C:\\Users\\akjain\\Downloads\\Entity-Recognition-In-Resumes-SpaCy-master\\traindata.json")
    nlp = spacy.blank("en")
    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)
    # add labels
    for _, annotations in TRAIN_DATA:
        for ent in annotations.get('entities'):
            ner.add_label(ent[2])

    def get_data(): return reformat_train_data(nlp.tokenizer, TRAIN_DATA)
    optimizer = nlp.begin_training(get_data)
    for itn in range(10):
        print("Starting iteration " + str(itn))
        random.shuffle(TRAIN_DATA)
        losses = {}
        for text, annotations in TRAIN_DATA:
            nlp.update(
                [text],  # batch of texts
                [annotations],  # batch of annotations
                drop=0.2,  # dropout - make it harder to memorise data
                sgd=optimizer,  # callable to update weights
                losses=losses)
        print(losses)
train_spacy()

I am getting the below error. Also, I came across a link (https://github.com/explosion/spaCy/issues/3558)  with some suggestion to fix this code. But even after implementing that I am still getting error.

I am using Python 3.6.5 and Spacy 2.2.3

Dataset:

{"content": "Nida Khan\nTech Support Executive - Teleperformance for Microsoft\n\nJaipur, Rajasthan - Email me on Indeed: indeed.com/r/Nida-Khan/6c9160696f57efd8\n\n• To be an integral part of the organization and enhance my knowledge to utilize it in a productive\nmanner for the growth of the company and the global.\n\nINDUSTRIAL TRAINING\n\n• BHEL, (HEEP) HARIDWAR\nOn CNC System& PLC Programming.\n\nWORK EXPERIENCE\n\nTech Support Executive\n\nTeleperformance for Microsoft -\n\nSeptember 2017 to Present\n\nprocess.\n• 21 months of experience in ADFC as Phone Banker.\n\nEDUCATION\n\nBachelor of Technology in Electronics & communication Engg\n\nGNIT institute of Technology -  Lucknow, Uttar Pradesh\n\n2008 to 2012\n\nClass XII\n\nU.P. Board -  Bareilly, Uttar Pradesh\n\n2007\n\nClass X\n\nU.P. Board -  Bareilly, Uttar Pradesh\n\n2005\n\nSKILLS\n\nMicrosoft office, excel, cisco, c language, cbs. (4 years)\n\nhttps://www.indeed.com/r/Nida-Khan/6c9160696f57efd8?isid=rex-download&ikw=download-top&co=IN","annotation":[{"label":["Email Address"],"points":[{"start":872,"end":910,"text":"indeed.com/r/Nida-Khan/6c9160696f57efd8"}]},{"label":["Skills"],"points":[{"start":800,"end":857,"text":"Microsoft office, excel, cisco, c language, cbs. (4 years)"}]},{"label":["Graduation Year"],"points":[{"start":676,"end":679,"text":"2012"}]},{"label":["College Name"],"points":[{"start":612,"end":640,"text":"GNIT institute of Technology "}]},{"label":["Degree"],"points":[{"start":552,"end":609,"text":"Bachelor of Technology in Electronics & communication Engg"}]},{"label":["Companies worked at"],"points":[{"start":420,"end":448,"text":"Teleperformance for Microsoft"}]},{"label":["Designation"],"points":[{"start":395,"end":417,"text":"\nTech Support Executive"}]},{"label":["Email Address"],"points":[{"start":106,"end":144,"text":"indeed.com/r/Nida-Khan/6c9160696f57efd8"}]},{"label":["Location"],"points":[{"start":66,"end":71,"text":"Jaipur"}]},{"label":["Companies worked at"],"points":[{"start":35,"end":63,"text":"Teleperformance for Microsoft"}]},{"label":["Designation"],"points":[{"start":10,"end":32,"text":"Tech Support Executive "}]},{"label":["Designation"],"points":[{"start":9,"end":31,"text":"\nTech Support Executive"}]},{"label":["Name"],"points":[{"start":0,"end":8,"text":"Nida Khan"}]}]}

Body:
The problem is you are feeding training data to model optimizer.

As mentioned in https://github.com/explosion/spaCy/issues/3558, use the following function to remove leading and trailing white spaces from entity spans.

def trim_entity_spans(data: list) -> list:
    """Removes leading and trailing white spaces from entity spans.

    Args:
    data (list): The data to be cleaned in spaCy JSON format.

    Returns:
    list: The cleaned data.
    """
    invalid_span_tokens = re.compile(r'\s')

    cleaned_data = []
    for text, annotations in data:
        entities = annotations['entities']
        valid_entities = []
        for start, end, label in entities:
            valid_start = start
            valid_end = end
            # if there's preceding spaces, move the start position to nearest character
            while valid_start < len(text) and invalid_span_tokens.match(
                    text[valid_start]):
                valid_start += 1
            while valid_end > 1 and invalid_span_tokens.match(
                    text[valid_end - 1]):
                valid_end -= 1
            valid_entities.append([valid_start, valid_end, label])
        cleaned_data.append([text, {'entities': valid_entities}])
    return cleaned_data

Then use the following function for training:

def train_spacy():

    TRAIN_DATA = convert_dataturks_to_spacy("C:\\Users\\akjain\\Downloads\\Entity-Recognition-In-Resumes-SpaCy-master\\traindata.json")
    TRAIN_DATA = trim_entity_spans(TRAIN_DATA)
    nlp = spacy.blank('en')  # create blank Language class
    # create the built-in pipeline components and add them to the pipeline
    # nlp.create_pipe works for built-ins that are registered with spaCy
    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)

    # add labels
    for _, annotations in TRAIN_DATA:
         for ent in annotations.get('entities'):
            ner.add_label(ent[2])

    # get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
    with nlp.disable_pipes(*other_pipes):  # only train NER
        optimizer = nlp.begin_training()
        for itn in range(10):
            print("Statring iteration " + str(itn))
            random.shuffle(TRAIN_DATA)
            losses = {}
            for text, annotations in TRAIN_DATA:
                nlp.update(
                [text],  # batch of texts
                [annotations],  # batch of annotations
                drop=0.2,  # dropout - make it harder to memorise data
                sgd=optimizer,  # callable to update weights
                losses=losses)
            print(losses)


问:
Calculate manual week number of year in Oracle SQL
i have a date column and along that i need to calculate another column in oracle for week number of they year, the weeks should be from sunday to saturday, starting first day of the year.

for example for current year

```<code>Week 1 : 1 Jan 2020 (Wednesday) - 4 Jan 2020(Saturday)

Week 2 : 5 Jan 2020 (Sunday)        - 11 Jan 2020(Saturday)

. . . . .

Week 5 : 26 Jan 2020 (Sunday) - 1 Feb 2020 (Saturday)
</code>```

and so on...

答:
You need to write your own logic using a hierarchy query.

Something like the following:

```<code>SQL> SELECT WEEKNUMBER,
  2  WEEK_START,
  3  CASE WHEN WEEKNUMBER = 1 THEN FIRST_WEEKEND ELSE WEEK_START + 6 END AS WEEK_END
  4  FROM
  5  (SELECT
  6      CASE
  7          WHEN LEVEL = 1 THEN FIRST_DAY
  8          ELSE FIRST_WEEKEND + ( LEVEL - 2 ) * 7 + 1
  9      END AS WEEK_START,
 10      FIRST_WEEKEND,
 11      LEVEL AS WEEKNUMBER
 12  FROM
 13      ( SELECT
 14              TRUNC(SYSDATE, 'YEAR') FIRST_DAY,
 15              NEXT_DAY(TRUNC(SYSDATE, 'YEAR'), 'SATURDAY') FIRST_WEEKEND
 16          FROM DUAL )
 17  CONNECT BY
 18      CASE WHEN LEVEL = 1 THEN FIRST_DAY
 19          ELSE FIRST_WEEKEND + ( LEVEL - 2 ) * 7 + 1
 20      END < ADD_MONTHS(TRUNC(SYSDATE, 'YEAR'), 12));

WEEKNUMBER WEEK_STAR WEEK_END
---------- --------- ---------
         1 01-JAN-20 04-JAN-20
         2 05-JAN-20 11-JAN-20
         3 12-JAN-20 18-JAN-20
         4 19-JAN-20 25-JAN-20
         5 26-JAN-20 01-FEB-20
         6 02-FEB-20 08-FEB-20
         7 09-FEB-20 15-FEB-20
         8 16-FEB-20 22-FEB-20
         9 23-FEB-20 29-FEB-20
        10 01-MAR-20 07-MAR-20
        11 08-MAR-20 14-MAR-20
        .......
        .......
        53 27-DEC-20 02-JAN-21
</code>```

Cheers!!

Body:
i have a date column and along that i need to calculate another column in oracle for week number of they year, the weeks should be from sunday to saturday, starting first day of the year.

for example for current year

Week 1 : 1 Jan 2020 (Wednesday) - 4 Jan 2020(Saturday)

Week 2 : 5 Jan 2020 (Sunday)        - 11 Jan 2020(Saturday)

. . . . .

Week 5 : 26 Jan 2020 (Sunday) - 1 Feb 2020 (Saturday)

and so on...

Body:
You need to write your own logic using a hierarchy query.

Something like the following:

SQL> SELECT WEEKNUMBER,
  2  WEEK_START,
  3  CASE WHEN WEEKNUMBER = 1 THEN FIRST_WEEKEND ELSE WEEK_START + 6 END AS WEEK_END
  4  FROM
  5  (SELECT
  6      CASE
  7          WHEN LEVEL = 1 THEN FIRST_DAY
  8          ELSE FIRST_WEEKEND + ( LEVEL - 2 ) * 7 + 1
  9      END AS WEEK_START,
 10      FIRST_WEEKEND,
 11      LEVEL AS WEEKNUMBER
 12  FROM
 13      ( SELECT
 14              TRUNC(SYSDATE, 'YEAR') FIRST_DAY,
 15              NEXT_DAY(TRUNC(SYSDATE, 'YEAR'), 'SATURDAY') FIRST_WEEKEND
 16          FROM DUAL )
 17  CONNECT BY
 18      CASE WHEN LEVEL = 1 THEN FIRST_DAY
 19          ELSE FIRST_WEEKEND + ( LEVEL - 2 ) * 7 + 1
 20      END < ADD_MONTHS(TRUNC(SYSDATE, 'YEAR'), 12));

WEEKNUMBER WEEK_STAR WEEK_END
---------- --------- ---------
         1 01-JAN-20 04-JAN-20
         2 05-JAN-20 11-JAN-20
         3 12-JAN-20 18-JAN-20
         4 19-JAN-20 25-JAN-20
         5 26-JAN-20 01-FEB-20
         6 02-FEB-20 08-FEB-20
         7 09-FEB-20 15-FEB-20
         8 16-FEB-20 22-FEB-20
         9 23-FEB-20 29-FEB-20
        10 01-MAR-20 07-MAR-20
        11 08-MAR-20 14-MAR-20
        .......
        .......
        53 27-DEC-20 02-JAN-21

Cheers!!


问:
Divide by zero runtime error while using a loop
I had gotten a divide by zero runtime error while using a loop and I do not know why. Don't worry, the code is unfinished yet. I am trying to convert an array using the ulj function if you can help. Here's the code:

```<code>import numpy as np
def ulj(x,epsilon = 4*(10**-4),sigma=6):
"""Compute Lennard-Jones potential as a function of inter-atomic distance"""
return epsilon*((((sigma)/(x))**12)-((((sigma)/(x))**6)))

 positions=np.array([0., 7.0,5,6,2,6,2,2,4,3]) # Initial position of the two objects (in atomic            units)

i = 0

x1 = []
x2 = []
while i <(len(positions)):
    x1.append(ulj(positions[i]))

print(x1)
</code>```

Thanks for your help

答:
While Mohit Sharma is correct, you should be incrementing i inside of the loop (to avoid an infinite loop), the answer to why a divide by zero error is happening is the following.

When i == 0, positions[i] == 0.

Therefore, ulj(positions[i]) is ulj(0).

This means that inside your function, x == 0, and sigma/x will be raise a divide by zero exception.

Body:
I had gotten a divide by zero runtime error while using a loop and I do not know why. Don't worry, the code is unfinished yet. I am trying to convert an array using the ulj function if you can help. Here's the code:

import numpy as np
def ulj(x,epsilon = 4*(10**-4),sigma=6):
"""Compute Lennard-Jones potential as a function of inter-atomic distance"""
return epsilon*((((sigma)/(x))**12)-((((sigma)/(x))**6)))

 positions=np.array([0., 7.0,5,6,2,6,2,2,4,3]) # Initial position of the two objects (in atomic            units)

i = 0

x1 = []
x2 = []
while i <(len(positions)):
    x1.append(ulj(positions[i]))

print(x1)

Thanks for your help


问:
How to automatically trigger intent in schedule time in dialogflow
I am trying to trigger intents in Dialogflow automatically for getting the contact detail of the user in schedule time. please provide the code if it is possible by JavaScript?</p>

答:
Well, there are multiple ways to achieve this. You can use one of them mentioned below:

Create an intent with slot filling. Here how it works
a. Bot prompt user for name and number and until it gets the required parameter, the intent will not trigger its fulfillment.
b. Once it has the parameter, fulfillment will trigger your webhook server. where you can save these data in db or chat sessions.

Here you can check how to implement intent with required parameter

This is more specific to user who has a google account, you can use authorization in the assistant and request for this information, once user-approved you can get these data.

You can use the helper intent to get the authorization and required data.

```<code>actions.intent.SIGN_IN
</code>```

here you can check all the required helper intent

Body:
Well, there are multiple ways to achieve this. You can use one of them mentioned below:

Create an intent with slot filling. Here how it works
a. Bot prompt user for name and number and until it gets the required parameter, the intent will not trigger its fulfillment.
b. Once it has the parameter, fulfillment will trigger your webhook server. where you can save these data in db or chat sessions.

Here you can check how to implement intent with required parameter

This is more specific to user who has a google account, you can use authorization in the assistant and request for this information, once user-approved you can get these data.

You can use the helper intent to get the authorization and required data.

actions.intent.SIGN_IN

here you can check all the required helper intent


问:
My multidex is not resolving (it is still red)
My android.support.multidex.MultiDexApplication is still red after all the steps. I am not able to resolve this. I'm following a course online but can't find the answer. Can I omit multidex?

```<code>android {
    compileSdkVersion 28
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.ping"
        minSdkVersion 21
        targetSdkVersion 28
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'

    implementation 'com.android.support:support-v4:28.0.0'

    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
    implementation 'com.google.firebase:firebase-auth:19.2.0'
    implementation 'com.google.firebase:firebase-firestore:21.4.0'
    implementation 'com.google.firebase:firebase-storage:19.1.1'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ping">

    <application
        android:name="android.support.multidex.MultiDexApplication"
          (this part is showing error)
        >
</code>```

答:
You need to have an application class that extends MultiDexApplication

You need to have this dependency for AndroidX

```<code>implementation 'androidx.multidex:multidex:2.0.1'
</code>```

Or for the normal support library

```<code>implementation 'com.android.support:multidex:1.0.3'
</code>```

Below is the code if you want it in Kotlin

```<code>class YourAppName : MultiDexApplication()
</code>```

Or for Java

```<code>class YourAppName extends MultiDexApplication
</code>```

And in your manifest file in the application tag

```<code>android:name:".YourAppName"
</code>```

If you're thinking why to have an application class here is some reading you can do

https://stackoverflow.com/a/33315717/10752944

Body:
My android.support.multidex.MultiDexApplication is still red after all the steps. I am not able to resolve this. I'm following a course online but can't find the answer. Can I omit multidex?

android {
    compileSdkVersion 28
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.ping"
        minSdkVersion 21
        targetSdkVersion 28
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'

    implementation 'com.android.support:support-v4:28.0.0'

    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
    implementation 'com.google.firebase:firebase-auth:19.2.0'
    implementation 'com.google.firebase:firebase-firestore:21.4.0'
    implementation 'com.google.firebase:firebase-storage:19.1.1'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
apply plugin: 'com.google.gms.google-services'

Manifest:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ping">

    <application
        android:name="android.support.multidex.MultiDexApplication"
          (this part is showing error)
        >

Body:
You need to have an application class that extends MultiDexApplication

You need to have this dependency for AndroidX

implementation 'androidx.multidex:multidex:2.0.1'

Or for the normal support library

implementation 'com.android.support:multidex:1.0.3'

Below is the code if you want it in Kotlin

class YourAppName : MultiDexApplication()

Or for Java

class YourAppName extends MultiDexApplication

And in your manifest file in the application tag

android:name:".YourAppName"

If you're thinking why to have an application class here is some reading you can do

https://stackoverflow.com/a/33315717/10752944


问:
Clearing ListBox from another Form
I have been stuck on this and don't know what I am doing wrong here. I am trying to clear a ListBox from another Form via a button.

On my main Form where I have the ListBox I have this function:

```<code>public void test()
{
    this.DeviceList.Items.Clear();
}
</code>```

And on the other Form where I have my button I have:

```<code>Form1 mainform = new Form1();
mainform.test();
</code>```

But when I press the button nothing happens. Now if I switch out this.DeviceList.Items.Clear(); to MessageBox.Show("test"); that works just fine. But not if I am using this.DeviceList.Items.Clear();.

I tried using without this but still the same issue.

答:
In your current code:

```<code>Form1 mainform = new Form1();
mainform.test();
</code>```

you create a new form don't Show it but clear its DeviceList. You should find out an existing form, e.g.:

```<code>using System.Linq;

...

var mainform  = Application
  .OpenForms
  .OfType<Form1>()     //TODO: put the right type if required
  .LastOrDefault();    // if you have several intances, let's take the last one

if (mainform  != null) // if MainForm instance has been found...
  mainform .test();    // ... we clear its DeviceList
</code>```

Title: Clearing ListBox from another Form

Body:
I have been stuck on this and don't know what I am doing wrong here. I am trying to clear a ListBox from another Form via a button.

On my main Form where I have the ListBox I have this function:

public void test()
{
    this.DeviceList.Items.Clear();
}

And on the other Form where I have my button I have:

Form1 mainform = new Form1();
mainform.test();

But when I press the button nothing happens. Now if I switch out this.DeviceList.Items.Clear(); to MessageBox.Show("test"); that works just fine. But not if I am using this.DeviceList.Items.Clear();.

I tried using without this but still the same issue.

Body:
In your current code:

Form1 mainform = new Form1();
mainform.test();

you create a new form don't Show it but clear its DeviceList. You should find out an existing form, e.g.:

using System.Linq;

...

var mainform  = Application
  .OpenForms
  .OfType<Form1>()     //TODO: put the right type if required
  .LastOrDefault();    // if you have several intances, let's take the last one

if (mainform  != null) // if MainForm instance has been found...
  mainform .test();    // ... we clear its DeviceList


问:
mysql update query takes too long
i have a table with 2255440 records,

a cron job works every minute and inserts upto 50-100 records on every execution

inserts are working fine

the problem is that there is another cron job which is also running every minute.. this cron job updates these records according to the data recieved from other server

the problem is that the update query is taking around 6 - 7 seconds per update query

this is the table information and update query example

records are updated with this query

Query:

```<code>UPDATE `$month`
SET `acctstoptime`='$data->acctstoptime',
    `acctsessiontime`='$data->acctsessiontime',
    `acctinputoctets`='$data->acctinputoctets',
    `acctoutputoctets`='$data->acctoutputoctets',
    `acctterminatecause`='$data->acctterminatecause'
WHERE `radacctid`=$data->radacctid
</code>```

答:
CREATE INDEX:

Indexes are used to retrieve data from the database more quickly than
  otherwise. The users cannot see the indexes, they are just used to
  speed up searches/queries.

Syntax:

```<code>CREATE INDEX [index name] ON [table name]([column name]);
</code>```

Arguments

```<code>Name            Description

index name      Name of the index.
table name      Name of the table.
column name     Name of the column.
</code>```

Example

Code:

```<code>CREATE  INDEX radacctid ON table_name(radacctid);
</code>```

Title: mysql update query takes too long

Body:
i have a table with 2255440 records,

a cron job works every minute and inserts upto 50-100 records on every execution

inserts are working fine

the problem is that there is another cron job which is also running every minute.. this cron job updates these records according to the data recieved from other server

the problem is that the update query is taking around 6 - 7 seconds per update query

this is the table information and update query example

records are updated with this query

Query:

UPDATE `$month`
SET `acctstoptime`='$data->acctstoptime',
    `acctsessiontime`='$data->acctsessiontime',
    `acctinputoctets`='$data->acctinputoctets',
    `acctoutputoctets`='$data->acctoutputoctets',
    `acctterminatecause`='$data->acctterminatecause'
WHERE `radacctid`=$data->radacctid

Body:
CREATE INDEX:

Indexes are used to retrieve data from the database more quickly than
  otherwise. The users cannot see the indexes, they are just used to
  speed up searches/queries.

Syntax:

CREATE INDEX [index name] ON [table name]([column name]);

Arguments

Name            Description

index name      Name of the index.
table name      Name of the table.
column name     Name of the column.

Example

Code:

CREATE  INDEX radacctid ON table_name(radacctid);


问:
TEZ parameter equivalent to "mapreduce.map.failures.maxpercent"
In previous versions of Hadoop where MR is used we have a set parameter for ignoring certain percentage of vertex failures.In the new versions where MR is deprecated, is there any equivalent parameter for mapreduce.map.failures.maxpercent in TEZ? </p>

答:
I this Jira new configuration property tez.vertex.failures.maxpercent was added:

Float value. Specifies the allowable percentage in the range
  0.0-100.0f of task failures per vertex that will allow the vertex to succeed with failures. Default is 0.0f

See also TezConfiguration.java


问:
Error building Ionic app: Failed to execute aapt (CordovaLib:processDebugResources)
I'm trying to use Ionic framework to build hybrid mobile apps but I'm facing the following problem since a few days.

When I want to build the application (which is actually a blank project), the command "ionic cordova build android" returns this error (detailed logs below) when executing CordovaLib:processDebugResources task:

/home/pi/android-sdk/build-tools/23.0.1/aapt: Syntax error: newline unexpected (expecting ")")

I tried to reinstall many times Android SDK. I also tried different versions of Android tools/platforms (23, 26) but it did nothing.

I didn't find on the web any solution to solve this problem.
So, if someone has an idea or already faced this problem and solved it, do not hesitate!

Detailled logs when building the app:

:CordovaLib:generateDebugBuildConfig UP-TO-DATE
:CordovaLib:processDebugResources/home/pi/android-sdk/build-tools/23.0.1/aapt:
2:
/home/pi/android-sdk/build-tools/23.0.1/aapt: Syntax error: newline unexpected (expecting ")")

```<code>      FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':CordovaLib:processDebugResources'.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

    BUILD FAILED

    Total time: 55.363 secs
    Error: /home/pi/IonicPJ/platforms/android/gradlew: Command failed with exit code 1 Error output:
    Picked up _JAVA_OPTIONS: -Xmx256M
    /home/pi/android-sdk/build-tools/23.0.1/aapt: 2: /home/pi/android-sdk/build-tools/23.0.1/aapt: Syntax error:
    newline unexpected (expecting ")")

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':CordovaLib:processDebugResources'.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt
</code>```

You will find below different element concerning the components installed.

```<code>Ionic 3.8.1
Cordova 7.0.1
Gradle 4.1
JAVA 8
</code>```

I set the variables $JAVA_HOME, $ANDROID_HOME and added $ANDROID_HOME/tools and $ANDROID_HOME/platform-tools to $PATH variable

This is the packages I installed via Android SDKManager:

```<code>    Installed packages:
  Path                        | Version | Description                    | Location
  -------                     | ------- | -------                        | -------
  build-tools;23.0.1          | 23.0.1  | Android SDK Build-Tools 23.0.1 | build-tools/23.0.1/
  emulator                    | 26.1.3  | Android Emulator               | emulator/
  extras;android;m2repository | 47.0.0  | Android Support Repository     | extras/android/m2repository/
  extras;google;m2repository  | 57      | Google Repository              | extras/google/m2repository/
  patcher;v4                  | 1       | SDK Patch Applier v4           | patcher/v4/
  platform-tools              | 26.0.0  | Android SDK Platform-Tools     | platform-tools/
  platforms;android-23        | 3       | Android SDK Platform 23        | platforms/android-23/
  platforms;android-25        | 3       | Android SDK Platform 25        | platforms/android-25/
  tools                       | 26.0.2  | Android SDK Tools              | tools/
</code>```

When I run "ionic cordova platform ls", I have:

```<code>Installed platforms:
android 6.2.3
</code>```

And everything is running on a raspberry with Raspbian Jessie:

```<code>Linux raspberrypi 4.9.35-v7+ #1014 SMP Fri Jun 30 14:47:43 BST 2017 armv7l GNU/Linux
</code>```

答:
Me too faced this issue, This issue occurred when I've added allowClearTextTraffic in config.xml for fixing the clear text issue. I've fixed the cleartext issue in another way and then run

ionic cordova resources android

Then the build issue was fixed!

Body:
I'm trying to use Ionic framework to build hybrid mobile apps but I'm facing the following problem since a few days.

When I want to build the application (which is actually a blank project), the command "ionic cordova build android" returns this error (detailed logs below) when executing CordovaLib:processDebugResources task:

/home/pi/android-sdk/build-tools/23.0.1/aapt: Syntax error: newline unexpected (expecting ")")

I tried to reinstall many times Android SDK. I also tried different versions of Android tools/platforms (23, 26) but it did nothing.

I didn't find on the web any solution to solve this problem.
So, if someone has an idea or already faced this problem and solved it, do not hesitate!

Detailled logs when building the app:

:CordovaLib:generateDebugBuildConfig UP-TO-DATE
:CordovaLib:processDebugResources/home/pi/android-sdk/build-tools/23.0.1/aapt:
2:
/home/pi/android-sdk/build-tools/23.0.1/aapt: Syntax error: newline unexpected (expecting ")")

      FAILED

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':CordovaLib:processDebugResources'.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

    BUILD FAILED

    Total time: 55.363 secs
    Error: /home/pi/IonicPJ/platforms/android/gradlew: Command failed with exit code 1 Error output:
    Picked up _JAVA_OPTIONS: -Xmx256M
    /home/pi/android-sdk/build-tools/23.0.1/aapt: 2: /home/pi/android-sdk/build-tools/23.0.1/aapt: Syntax error:
    newline unexpected (expecting ")")

    FAILURE: Build failed with an exception.

    * What went wrong:
    Execution failed for task ':CordovaLib:processDebugResources'.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt

You will find below different element concerning the components installed.

Ionic 3.8.1
Cordova 7.0.1
Gradle 4.1
JAVA 8

I set the variables $JAVA_HOME, $ANDROID_HOME and added $ANDROID_HOME/tools and $ANDROID_HOME/platform-tools to $PATH variable

This is the packages I installed via Android SDKManager:

    Installed packages:
  Path                        | Version | Description                    | Location
  -------                     | ------- | -------                        | -------
  build-tools;23.0.1          | 23.0.1  | Android SDK Build-Tools 23.0.1 | build-tools/23.0.1/
  emulator                    | 26.1.3  | Android Emulator               | emulator/
  extras;android;m2repository | 47.0.0  | Android Support Repository     | extras/android/m2repository/
  extras;google;m2repository  | 57      | Google Repository              | extras/google/m2repository/
  patcher;v4                  | 1       | SDK Patch Applier v4           | patcher/v4/
  platform-tools              | 26.0.0  | Android SDK Platform-Tools     | platform-tools/
  platforms;android-23        | 3       | Android SDK Platform 23        | platforms/android-23/
  platforms;android-25        | 3       | Android SDK Platform 25        | platforms/android-25/
  tools                       | 26.0.2  | Android SDK Tools              | tools/

When I run "ionic cordova platform ls", I have:

Installed platforms:
android 6.2.3

And everything is running on a raspberry with Raspbian Jessie:

Linux raspberrypi 4.9.35-v7+ #1014 SMP Fri Jun 30 14:47:43 BST 2017 armv7l GNU/Linux


问:
how to get the date of last week's (tuesday or any other day) in php?
I think its possible but i cant come up with the right algorithm for it.

What i wanted to do was:

If today is monday feb 2 2009, how would i know the date of last week's tuesday? Using that same code 2 days after, i would find the same date of last week's tuesday with the current date being wednesday, feb 4 2009.

答:
Do not use manual calculation, use DateTime object instead. It has proper implementation, takes into account leap years, yeap seconds, etc.

```<code>$today = new \DateTime();
$today->modify('tuesday last week');
</code>```

The modify method modifies the date relative to it's state, so if you set the date to a different date, it calculates it relative to it.

```<code>$date = new \DateTime('2020-01-01');
echo $date->format('Y-m-d'); // 2020-01-01

$date->modify('tuesday last week');
echo $date->format('Y-m-d'); // 2019-12-24
</code>```

OwnerDisplayName: lock

ContentLicense: CC BY-SA 2.5

Body:
Do not use manual calculation, use DateTime object instead. It has proper implementation, takes into account leap years, yeap seconds, etc.

$today = new \DateTime();
$today->modify('tuesday last week');

The modify method modifies the date relative to it's state, so if you set the date to a different date, it calculates it relative to it.

$date = new \DateTime('2020-01-01');
echo $date->format('Y-m-d'); // 2020-01-01

$date->modify('tuesday last week');
echo $date->format('Y-m-d'); // 2019-12-24


问:
Raise event in one thread to invoke methods in a second thread
I'm working on a program which reacts to events coming from an internet socket, and possibly from timers as well. It seems natural to use two threads:

One for the main program

A second one which listens to the socket, parses the input, and raises an appropriate event.

Additional requirements:

The application should not rely on a UI thread (it may be run as a console application).

The main program should process messages synchronously, i.e. in the order in which they arrived.

The main thread must not block on waiting for timers (I guess this means I have to run timers on different threads).

And now for some questions :-):

I'm guessing requirement #1 means that I don't have a built-in message pump, so I can't use Invoke() from the socket listener / timer threads. Is this correct?

How can I safely raise events on one thread (e.g. the listener), and have the subscribers run synchronously on another (the main thread)?

It is very likely that new events will be raised before the subsequent handler is done. What will happen in this case? Will the event be buffed somewhere by the CLR, or will it be ignored?

And last but not least: I guess I'm aiming for the parallel for the message Producer/Consumer paradigm, but instead of messages, I want to use events. Do you think there is a better approach?

Thanks,

Boaz

EDIT

I want to explain my motivation for using events in the first place. The application is an automated trading engine which has to respond to events that happen in the market (e.g. a change in the price of a stock). When this happens, there may be multiple subscribers on the main thread which should be invoked, which is a classical scenario to use events.

I guess I can always use the Producer/Consumer with some message queue, and have the consumer raise events on the main thread, but I figured there might be a more direct way.

答:
I think using messages will be the simplest way. If you are using C# 4 this is very easy thanks to the BlockingCollection<>

So have a shared BlockingCollection, where Message is your message class.

Then in your worker thread you do this

```<code>var msgEnum = blockingCollection.GetConsumingEnumerable();

//Per thread
foreach( Message message in msgEnum )
{
   //Process messages here
}
</code>```

That is it.

The GetConsumingEnumerable() will block until there is a message to process. It will then remove the message from the queue and your loop will process it.

What is nice about this is that you can add more threads and in each one you just have the foreach loop.

When you are done call blockingCollection.CompletedAdding();

BTW the queue handles concurrency and will queue messages sent at the same time etc.

Hope this helps

Andre

ContentLicense: CC BY-SA 3.0

Body:
I think using messages will be the simplest way. If you are using C# 4 this is very easy thanks to the BlockingCollection<>

So have a shared BlockingCollection, where Message is your message class.

Then in your worker thread you do this

var msgEnum = blockingCollection.GetConsumingEnumerable();

//Per thread
foreach( Message message in msgEnum )
{
   //Process messages here
}

That is it.

The GetConsumingEnumerable() will block until there is a message to process. It will then remove the message from the queue and your loop will process it.

What is nice about this is that you can add more threads and in each one you just have the foreach loop.

When you are done call blockingCollection.CompletedAdding();

BTW the queue handles concurrency and will queue messages sent at the same time etc.

Hope this helps

Andre


问:
Hidden Navigation bar (bottom bar with Home, Back and Overview button) is visible after showing a dialog or if the EditText gains focus
There is a full screen activity with the following code blocks used to achieve the same:

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

// ….
}

@Override
    protected void onResume() {
        Log.i(TAG, "onResume");

        super.onResume();
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        // Set the content to appear under the system bars so that the
                        // content doesn't resize when the system bars hide and show.
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        // Hide the nav bar and status bar
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }
</code>```

However, when a custom dialog is shown or if the edittext gains focus, the bottom navigation bar becomes visible and sticks around.
 The official doc says:

If a new activity or dialog appears in the foreground, taking focus
  and partially covering the activity in progress, the covered activity
  loses focus and enters the Paused state. Then, the system calls
  onPause() on it.

When the covered activity returns to the foreground and regains focus,
  it calls onResume().

But onResume() is not invoked when the dialog looses focus (checked with logs).

Also tried adding the following code in onCreate() of custom dialog:

```<code>View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        // Set the content to appear under the system bars so that the
                        // content doesn't resize when the system bars hide and show.
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        // Hide the nav bar and status bar
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
</code>```

After adding the above code, the navigation bar hides when the custom dialog is in foreground, but when it goes out of focus, the navigation bar pops back onto the screen.

Also tried setting fullscreen mode using styles. Please refer below the same.

```<code><style name="FullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:windowContentTransitions">true</item>
</style>
</code>```

Same is the case with edittext. Activity starts up in fullscreen mode, but as soon as edittext gains focus, the bottom navigation bar is visible and sticks around.

Any input would be appreciated.

Cheers!

答:
Try this code.</p>

```<code>fun View.setImmersiveMode() {
    isFocusableInTouchMode = false
    setOnClickListener {
        requestFocusFromTouch()
    }
}
editText.setImmersiveMode()
</code>```

Body:
There is a full screen activity with the following code blocks used to achieve the same:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

// ….
}

@Override
    protected void onResume() {
        Log.i(TAG, "onResume");

        super.onResume();
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        // Set the content to appear under the system bars so that the
                        // content doesn't resize when the system bars hide and show.
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        // Hide the nav bar and status bar
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }

However, when a custom dialog is shown or if the edittext gains focus, the bottom navigation bar becomes visible and sticks around.
 The official doc says:

If a new activity or dialog appears in the foreground, taking focus
  and partially covering the activity in progress, the covered activity
  loses focus and enters the Paused state. Then, the system calls
  onPause() on it.

When the covered activity returns to the foreground and regains focus,
  it calls onResume().

But onResume() is not invoked when the dialog looses focus (checked with logs).

Also tried adding the following code in onCreate() of custom dialog:

View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        // Set the content to appear under the system bars so that the
                        // content doesn't resize when the system bars hide and show.
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        // Hide the nav bar and status bar
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);

After adding the above code, the navigation bar hides when the custom dialog is in foreground, but when it goes out of focus, the navigation bar pops back onto the screen.

Also tried setting fullscreen mode using styles. Please refer below the same.

Same is the case with edittext. Activity starts up in fullscreen mode, but as soon as edittext gains focus, the bottom navigation bar is visible and sticks around.

Any input would be appreciated.

Cheers!

Body:
Try this code.

fun View.setImmersiveMode() {
    isFocusableInTouchMode = false
    setOnClickListener {
        requestFocusFromTouch()
    }
}
editText.setImmersiveMode()


问:
After finetuning Faster RCNN object detection model, how to visualize bbox prediction?
I finetuned pytorch torchvision model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) on my own custom dataset.

I followed this guide https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html#torchvision-object-detection-finetuning-tutorial but only trained Faster RCNN, not Mask RCNN.

I successfully finished training with no error, and the model returned a dict containing predicted boxes, labels, and scores.

In the guide I followed, they show how to visualize masks predicted by the model trained.
Is there a similar method to visualize bounding box? I'm having a lot of trouble figuring this out.

Thank you

答:
The prediction from FasterRCNN is of the form:

```<code>>>> predictions = model([input_img_tensor])
[{'boxes': tensor([[419.6865, 170.0683, 536.0842, 493.7452],
          [159.0727, 180.3606, 298.8194, 434.4604],
          [439.7836, 222.6208, 452.0138, 271.8359],
          [444.3562, 224.4628, 456.1511, 265.5336],
          [437.7808, 226.5965, 446.2904, 271.2691]], grad_fn=<StackBackward>),
  'labels': tensor([ 1,  1, 32, 32, 32]),
  'scores': tensor([0.9997, 0.9996, 0.5827, 0.2102, 0.0943], grad_fn=<IndexBackward>)}]
</code>```

where the predicted boxes are of [x1, y1, x2, y2] format, with values between 0 and H and 0 and W.

You can use OpenCV's rectangle function to overlay bounding boxes on image.

```<code>import cv2
img = cv2.imread('input_iamge.png', cv2.COLOR_BGR2RGB)

for i in range(len(predictions[0]['boxes'])):
    x1, x2, x3, x4 = map(int, predictions[0]['boxes'][i].tolist())
    print(x1, x2, x3, x4)
    image = cv2.rectangle(img, (x1, x2), (x3, x4), (255, 0, 0), 1)

cv2_imshow('img', image)
</code>```

Body:
The prediction from FasterRCNN is of the form:

>>> predictions = model([input_img_tensor])
[{'boxes': tensor([[419.6865, 170.0683, 536.0842, 493.7452],
          [159.0727, 180.3606, 298.8194, 434.4604],
          [439.7836, 222.6208, 452.0138, 271.8359],
          [444.3562, 224.4628, 456.1511, 265.5336],
          [437.7808, 226.5965, 446.2904, 271.2691]], grad_fn=<StackBackward>),
  'labels': tensor([ 1,  1, 32, 32, 32]),
  'scores': tensor([0.9997, 0.9996, 0.5827, 0.2102, 0.0943], grad_fn=<IndexBackward>)}]

where the predicted boxes are of [x1, y1, x2, y2] format, with values between 0 and H and 0 and W.

You can use OpenCV's rectangle function to overlay bounding boxes on image.

import cv2
img = cv2.imread('input_iamge.png', cv2.COLOR_BGR2RGB)

for i in range(len(predictions[0]['boxes'])):
    x1, x2, x3, x4 = map(int, predictions[0]['boxes'][i].tolist())
    print(x1, x2, x3, x4)
    image = cv2.rectangle(img, (x1, x2), (x3, x4), (255, 0, 0), 1)

cv2_imshow('img', image)


问:
How to generate the terrain of specific area
I want to create the 3d geographical terrain in unity 3d. I want the landscapes like mountain area, desert area etc type areas in unity 3d which should meet the reality.</p>

答:
First you have to get the height-map of the area which you want to generate terrain. From that height-map you need to generate the terrain.
For terrain texturing you have to use the 'Map Puzzle' software and get the terrain texturing by giving the latitude and longitude of the area you chosen, as input. This will create the texture of the area. Import that to unity and apply to terrain(tiling size and terrain size to be same).

Here is my detailed tutorial on the same where you can find the step by step procedure to generate geographical terrains. Follow the below link.
https://u3dtutsbh.blogspot.com/2019/06/building-geographical-terrain-in-unity.html


答:
You're mixing androidX with Support libraries.

You should replace:

```<code>implementation 'com.android.support:support-v4:28.0.0'
</code>```

with

```<code>implementation 'androidx.multidex:multidex:2.0.1'
</code>```

and replace

```<code>android.support.multidex.MultiDexApplication
</code>```

with

```<code>androidx.multidex.MultiDexApplication
</code>```

Title: My multidex is not resolving (it is still red)

Body:
You're mixing androidX with Support libraries.

You should replace:

implementation 'com.android.support:support-v4:28.0.0'

with

implementation 'androidx.multidex:multidex:2.0.1'

and replace

android.support.multidex.MultiDexApplication

with

androidx.multidex.MultiDexApplication


问:
Making the back and next button fixed on top of line chart
I'm using line chart and I have two navigational buttons which user can use to scroll the graph. Currently when I'm scrolling the graph, 2 buttons also getting scrolled. I need to make these 2 buttons fixed regardless of the scrolling of graph.

In addition, I want to hide the scrollbar without losing the scrollbar functionality.

```<code><div class = "col-5">
   <div id="wrapperChart" className="hideScroll wrapperScroll sc-line-chart">
      <div className="chartContainer">
         <canvas id="chart"></canvas>
      </div>
      <span type="button" className="sc-btn-icon sc-btn-icon--small sc-line-chart__icon sc-line-chart__icon--left">
         <i className="sc-kiosk-arrow-left2"></i>
      </span>
      <span type="button" className="sc-btn-icon sc-btn-icon--small sc-line-chart__icon sc-line-chart__icon--right">
         <i className="sc-kiosk-arrow-right2"></i>
      </span>
   </div>
</code>```

CSS:

```<code>.sc-line-chart{
    position: relative;
    overflow-x: auto;
    &__icon{
        position: absolute;
        &--left{
            bottom: 0;
            left: 0.15rem;
        }
        &--right{
            bottom: 0;
            right: 0;
        }
    }
}
</code>```

答:
Change bottom:0 to top:0

```<code>.sc-line-chart{
    position: relative;
    overflow-x: auto;
    &__icon{
        position: absolute;
        &--left{
            top: 0;
            left: 0.15rem;
        }
        &--right{
            top: 0;
            right: 0;
        }
    }
}
</code>```

Body:
I'm using line chart and I have two navigational buttons which user can use to scroll the graph. Currently when I'm scrolling the graph, 2 buttons also getting scrolled. I need to make these 2 buttons fixed regardless of the scrolling of graph.

In addition, I want to hide the scrollbar without losing the scrollbar functionality.

         <canvas id="chart"></canvas>

CSS:

.sc-line-chart{
    position: relative;
    overflow-x: auto;
    &__icon{
        position: absolute;
        &--left{
            bottom: 0;
            left: 0.15rem;
        }
        &--right{
            bottom: 0;
            right: 0;
        }
    }
}

Body:
Change bottom:0 to top:0

.sc-line-chart{
    position: relative;
    overflow-x: auto;
    &__icon{
        position: absolute;
        &--left{
            top: 0;
            left: 0.15rem;
        }
        &--right{
            top: 0;
            right: 0;
        }
    }
}


问:
How to convert multiple array to single array
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.

I want to convert this array to single array like.

Convert this :-

```<code>Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )
</code>```

Convert To :-

```<code>Array("user", "user1", "user2", "user3", "user4", "user5", "user6");
</code>```

答:
Pack or collect all arrays into a parent array.
Then you only need to pass an array as a parameter when calling array_merge.
Update: it is better to use array_column.

```<code>$arr  = [];
$arr[] = array('user');
$arr[] = array('user1');
$arr[] = array('user2');

$one_dim_array = array_merge(...$arr);

//or better
$one_dim_array =  array_column($arr,0);

echo "```".var_export($one_dim_array, true);
```

<p>Result:</p>

```array (
  0 => 'user',
  1 => 'user1',
  2 => 'user2',
)
```

Try it yourself : Sandbox

Body:
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.

I want to convert this array to single array like.

Convert this :-

Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )

Convert To :-

Array("user", "user1", "user2", "user3", "user4", "user5", "user6");

Body:
Pack or collect all arrays into a parent array.
Then you only need to pass an array as a parameter when calling array_merge.
Update: it is better to use array_column.

$arr  = [];
$arr[] = array('user');
$arr[] = array('user1');
$arr[] = array('user2');

$one_dim_array = array_merge(...$arr);

//or better
$one_dim_array =  array_column($arr,0);

echo "<pre>".var_export($one_dim_array, true);

Result:

array (
  0 => 'user',
  1 => 'user1',
  2 => 'user2',
)

Try it yourself : Sandbox


问:
Chrome Autoplay Policy - Chrome 76
I'm building a kiosk media which runs on Chrome that plays video with audio. I know that chrome by default only allows autoplay for videos with muted props.

And i know that i WAS able to override this by enabling a flag in chrome via chrome://flags/#autoplay-policy

I have just updated to Chrome 76 and this flag seems to be gone and the autoplaying of video doesn't seem to work anymore!

Any idea how do i overcome this?

[Chrome 76.0.3809.100 (Official Build) (64-bit)]  Mac OS Mojave

答:
I just add a div in my page and call click trigger on load page!
it works correctly!    </p>

```<code><div id="test"></div>
<script>
    $(function(){
        $("#test").trigger("click");
    })
</script>
</code>```

Title: Chrome Autoplay Policy - Chrome 76

Body:
I just add a div in my page and call click trigger on load page!
it works correctly!

<div id="test"></div>
<script>
    $(function(){
        $("#test").trigger("click");
    })
</script>


问:
Why and how to fix? IIS Express "The specified port is in use"
We know a random port number is assigned to a web application in Visual Studio. It works fine in my office desktop. But when I pull the code onto my laptop (from VisualStudio.com) and run the web app. I got a message, saying,

The specified port is in use

Port 10360 is already being used by another application.

Recommendations

Try switching to port other than 10360 and higher than 1024.

Stop the application that is using port 10360.

I can fix it using Recommendation #1 by changing the port into something else like 13333. But I am very curious what happened to port 10360. How can I check what application is using port 10360? How can I stop that application?

答:
You need to configre this parameter by running the following in the administrative command prompt:

netsh http add iplisten ipaddress=::


问:
Is there any way to restart Solr using Java?
I'm using SolrJ to index my datas in my solr core. I use Solr's autocommit and I want to restart my solr when indexing is finish. Is there any way to do this with java codes??

I did something like this

```<code>    String urlReload="http://localhost:8983/solr";
    HttpSolrClient solr_reload=new HttpSolrClient.Builder(urlReload).build();
    CoreAdminRequest adminRequest=new CoreAdminRequest();
    adminRequest.setAction(CoreAdminAction.RELOAD);
    adminRequest.setCoreName("archiveCore");
    adminRequest.process(solr_reload);
</code>```

答: Do solr_reload.commit() at last. Then you don't need to restart solr.

Body:
I'm using SolrJ to index my datas in my solr core. I use Solr's autocommit and I want to restart my solr when indexing is finish. Is there any way to do this with java codes??

I did something like this

    String urlReload="http://localhost:8983/solr";
    HttpSolrClient solr_reload=new HttpSolrClient.Builder(urlReload).build();
    CoreAdminRequest adminRequest=new CoreAdminRequest();
    adminRequest.setAction(CoreAdminAction.RELOAD);
    adminRequest.setCoreName("archiveCore");
    adminRequest.process(solr_reload);


问:
how to send send the data using python django?
How to send the json data using post request in django python.
I have a code for get the data and I don't use any html file.

```<code>class employeeList(APIView):
    def get(self, request):
        employee1 = employees.objects.all()
        serializer = employeeSerializer(employee1, many=True)
        return Response(serializer.data)
    def post(self,request):
        pass
</code>```

can you please help for post request.Now I want to create post function to send the data

答:
You can simply dump query set into Json format like:</p>

```<code>def post(self, request):
    data = list(employees.objects.values())
    return JsonResponse(data, safe=False)
               # or
    return JsonResponse({'data': data})
</code>```

Body:
How to send the json data using post request in django python.
I have a code for get the data and I don't use any html file.

class employeeList(APIView):
    def get(self, request):
        employee1 = employees.objects.all()
        serializer = employeeSerializer(employee1, many=True)
        return Response(serializer.data)
    def post(self,request):
        pass

can you please help for post request.Now I want to create post function to send the data

Body:
You can simply dump query set into Json format like:

def post(self, request):
    data = list(employees.objects.values())
    return JsonResponse(data, safe=False)
               # or
    return JsonResponse({'data': data})


问:
Xamarin.Forms - Problem creating Android Wear Application
When running the tutorial:
https://learn.microsoft.com/en-gb/xamarin/android/wear/get-started/hello-wear?tabs=windows#feedback
example on Visual Studio to build an Android Wear application - I get the below errors:

02-13 20:13:24.035 E/eglCodecCommon( 9352): glUtilsParamSize: unknow param 0x000082da
02-13 20:13:24.035 E/eglCodecCommon( 9352): glUtilsParamSize: unknow param 0x000082da

I am running this using Android 9.0 API 28 and using an AndroidWear (Round) emulator.
For my IDE I am using Visual Studio 2019 V16.4.5

Can anyone advise a workaround as this is a Uni Project so just need to create a simple demo application with a couple buttons and using some Xamarin Widgets etc?

Thanks

答:
If you search this error message, you can easily find the answer in this thread:

This is caused if you use the "Use host GPU" setting of the emulator
  and it will disappear after you uncheck this option.

It is specific to the GPU emulation of the Android emulator.

So you can edit the gpu.mode when you create a Android wear round emulator to get rid of the error. There are also descriptions of each option at the right side:


答: You could implement a shared queue between your threads. Whenever an event is raised you could push it in the queue. The main thread is an endless loop that checks for new events, removes them from the queue,  handles the event and when there are no more events it sleeps for some time.</p>

Title: Raise event in one thread to invoke methods in a second thread

Body:
I'm working on a program which reacts to events coming from an internet socket, and possibly from timers as well. It seems natural to use two threads:

One for the main program

A second one which listens to the socket, parses the input, and raises an appropriate event.

Additional requirements:

The application should not rely on a UI thread (it may be run as a console application).

The main program should process messages synchronously, i.e. in the order in which they arrived.

The main thread must not block on waiting for timers (I guess this means I have to run timers on different threads).

And now for some questions :-):

I'm guessing requirement #1 means that I don't have a built-in message pump, so I can't use Invoke() from the socket listener / timer threads. Is this correct?

How can I safely raise events on one thread (e.g. the listener), and have the subscribers run synchronously on another (the main thread)?

It is very likely that new events will be raised before the subsequent handler is done. What will happen in this case? Will the event be buffed somewhere by the CLR, or will it be ignored?

And last but not least: I guess I'm aiming for the parallel for the message Producer/Consumer paradigm, but instead of messages, I want to use events. Do you think there is a better approach?

Thanks,

Boaz

EDIT

I want to explain my motivation for using events in the first place. The application is an automated trading engine which has to respond to events that happen in the market (e.g. a change in the price of a stock). When this happens, there may be multiple subscribers on the main thread which should be invoked, which is a classical scenario to use events.

I guess I can always use the Producer/Consumer with some message queue, and have the consumer raise events on the main thread, but I figured there might be a more direct way.


问:
Get Vuejs Store variable by String Value
I'm trying to get a vuejs store variable like this :

const pathFile = `#pathFile_${this.devisDTO.code_produit}`;
const pathApp = this.$store.state.parameters.urls.${pathFile};

So in the second line ${pathFile} is not interpreted in that way. Please could you help on how to write this ?

答:
you need to modify your code remove brackets from parameters.urls.${pathFile} to .urls.pathFile;

here is code..

```<code>const pathFile = `#pathFile_${this.devisDTO.code_produit}`;
const pathApp = this.$store.state.parameters.urls.pathFile;
</code>```

Body:
you need to modify your code remove brackets from parameters.urls.${pathFile} to .urls.pathFile;

here is code..

const pathFile = `#pathFile_${this.devisDTO.code_produit}`;
const pathApp = this.$store.state.parameters.urls.pathFile;