text:
Q: equalize the values by variables, taking into account the category and groups in R In my data
#EDIT DPUT
mydat=structure(list(ItemRelation = c(11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L,
11202L, 11202L, 11202L, 11202L), ReturnCount = c(0L, 2L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 3L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L,
0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 3L, 0L, 0L, 0L,
0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L), DocumentNum = c(514L, 514L, 514L, 514L,
514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L,
514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L,
514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L,
514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L, 514L,
514L, 514L, 514L, 514L, 896L, 896L, 896L, 896L, 896L, 896L, 896L,
896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L,
896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L,
896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L,
896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L, 896L,
896L), IsPromo = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), CalendarYear = c(2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L), output = c(0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, NA, NA, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, NA, NA, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L)), .Names = c("ItemRelation", "ReturnCount", "DocumentNum",
"IsPromo", "CalendarYear", "output"), class = "data.frame", row.names = c(NA,
-104L))

I have group vars
ItemRelation    DocumentNum
11202                 514
11202                  96

There is Ispromo column. It can take values only 0 and 1.
So ReturnCount is numeric variable.
I need to replace the values of output column, by values of returncount which go before 1 category of ispromo.
It is mean that the values by zero category of ispromo which go before one category  of ispromo, for returncount and output colums must be same.
BUT, values of these columns for zero category of ispromo AFTER one category, we don't touch.
How to do it for each group ItemRelation+DocumentNum?
Cause desired output
Edit expected output
    ItemRelation ReturnCount DocumentNum IsPromo output
1          11202           0         514       0      0
2          11202           2         514       0  **2**
3          11202           0         514       0      0
4          11202           0         514       0      0
5          11202           0         514       0      0
6          11202           0         514       0      0
7          11202           0         514       0      0
8          11202           0         514       0      0
9          11202           0         514       0      0
10         11202           0         514       0      0
11         11202           1         514       0  **1**
12         11202           0         514       0      0
13         11202           1         514       0  **1**
14         11202           1         514       0  **1**
15         11202           0         514       0      0
16         11202           0         514       0      0
17         11202           0         514       0      0
18         11202           0         514       0      0
19         11202           0         514       0      0
20         11202           0         514       0      0
21         11202           0         514       0      0
22         11202           0         514       0      0
23         11202           0         514       0      0
24         11202           0         514       0      0
25         11202           0         514       0      0
26         11202           0         514       0      0
27         11202           0         514       0      0
28         11202           1         514       0  **1**
29         11202           0         514       0      0
30         11202           0         514       0      0
31         11202           0         514       0      0
32         11202           0         514       0      0
33         11202           0         514       0      0
34         11202           0         514       0      0
35         11202           0         514       0      0
36         11202           0         514       1   <NA>
37         11202           0         514       1   <NA>
38         11202           0         514       0      0
39         11202           0         514       0      0
40         11202           0         514       0      0
41         11202           3         514       0      0
42         11202           0         514       0      0
43         11202           0         514       0      0
44         11202           0         514       0      0
45         11202           0         514       0      0
46         11202           1         514       0      1
47         11202           1         514       0      1
48         11202           0         514       0      0
49         11202           0         514       0      0
50         11202           0         514       0      0
51         11202           0         514       0      0
52         11202           0         514       0      0
53         11202           1         896       0  **1**
54         11202           0         896       0      0
55         11202           0         896       0      0
56         11202           0         896       0      0
57         11202           0         896       0      0
58         11202           0         896       0      0
59         11202           0         896       0      0
60         11202           0         896       0      0
61         11202           0         896       0      0
62         11202           0         896       0      0
63         11202           0         896       0      0
64         11202           0         896       0      0
65         11202           0         896       0      0
66         11202           0         896       0      0
67         11202           1         896       0  **1**
68         11202           0         896       0      0
69         11202           0         896       0      0
70         11202           0         896       0      0
71         11202           0         896       0      0
72         11202           0         896       0      0
73         11202           0         896       0      0
74         11202           0         896       0      0
75         11202           0         896       0      0
76         11202           0         896       0      0
77         11202           0         896       0      0
78         11202           0         896       0      0
79         11202           0         896       0      0
80         11202           3         896       0  **3**
81         11202           0         896       0      0
82         11202           0         896       0      0
83         11202           0         896       0      0
84         11202           0         896       0      0
85         11202           1         896       0  **1**
86         11202           1         896       0  **1**
87         11202           0         896       0      0
88         11202           0         896       1   <NA>
89         11202           0         896       1   <NA>
90         11202           0         896       0      0
91         11202           0         896       0      0
92         11202           0         896       0      0
93         11202           0         896       0      0
94         11202           0         896       0      0
95         11202           0         896       0      0
96         11202           0         896       0      0
97         11202           0         896       0      0
98         11202           0         896       0      0
99         11202           0         896       0      0
100        11202           0         896       0      0
101        11202           0         896       0      0
102        11202           0         896       0      0
103        11202           0         896       0      0
104        11202           0         896       0      0

** is marked the values of output by zero category of ispromo before one category of ispromo. I.e. we take value of returncount in this row and replace by it, the value of output in this row.
2          11202           2         514       0  **2**

for second row returncount =2 ,so 0 by output replaced by it.
Note this operation perform only for zero category of ispromo before 0ne category. AFTER one category, we don't touch zero category.

A: If I understand correctly, there is always a contiguous streak of zeros in IsPromo followed by a streak of contiguous 1s (called one category by the OP), and completed by a contiguous streak of zeros in each ItemRelation, DocumentNum group.
Then this can be solved by using the rleid() function and update by reference:
library(data.table)
# clean sample dataset: remove output column
setDT(mydat)[, output := NULL]
# add grouping variable for ISPromo categories
setDT(mydat)[, promo.cat := rleid(IsPromo), by = .(ItemRelation, DocumentNum)][
  # copy only first category in each group
  promo.cat == 1L & IsPromo == 0L, output := ReturnCount][
    # remove helper column
    , promo.cat := NULL][]
mydat

     ItemRelation ReturnCount DocumentNum IsPromo CalendarYear output
  1:        11202           0         514       0         2018      0
  2:        11202           2         514       0         2018      2
  3:        11202           0         514       0         2018      0
  4:        11202           0         514       0         2018      0
  5:        11202           0         514       0         2018      0
 ---
100:        11202           0         896       0         2018     NA
101:        11202           0         896       0         2018     NA
102:        11202           0         896       0         2018     NA
103:        11202           0         896       0         2018     NA
104:        11202           0         896       0         2018     NA

# check
mydat[ReturnCount > 0 & ReturnCount == output]

    ItemRelation ReturnCount DocumentNum IsPromo CalendarYear output
 1:        11202           2         514       0         2018      2
 2:        11202           1         514       0         2018      1
 3:        11202           1         514       0         2018      1
 4:        11202           1         514       0         2018      1
 5:        11202           1         514       0         2018      1
 6:        11202           1         896       0         2018      1
 7:        11202           1         896       0         2018      1
 8:        11202           3         896       0         2018      3
 9:        11202           1         896       0         2018      1
10:        11202           1         896       0         2018      1

These lines correspond to those marked by the OP in the expected result.


text:
Q: how to connect multiple voltage supplies to a PCB I need to connect +/-5V and +/-12V supplies to a PCB and want to know the best way to design the connecting cable. Should I tie the GNDs together at the supplies and then bring a single ground wire to the PCB? I'm thinking about ground loops. The power cables also need to be shielded so should I just connect one end to ground at the power supply?

A: By "tie the GNDs together" I assume you mean tying the DC Common terminals of the power supplies together. So, yes in generalit is better to tie the grounds together as close to the  power supplies as you can manage.
There are two reasons for doing this. First, you won't be relying on the PCB connections to connect the supplies. So, for example, if one of the ground connections fails at the PCB, the supply outputs will not float with respect to each other, potentially causing a problem in the connected circuitry.
Second, you may introduce voltage offsets between the two supply voltage pairs due to IR drops in separate connection geometries. This could also cause problems or accuracy issues in the connected circuitry.
Having said this, it is also possible under certain circumstances that you would want to tie the grounds together on the PCB for a specific reason of performance, accuracy, IR wire drop isolation, and similar. However, in this case you would still be susceptible to the first issue I described above.
You would tie only the one end of the power supply cable shield to the shared DC common connection at the power supplies to avoid a ground loop issue. If earth ground is available you might want to connect the shield to it instead of DC Common. It depends on the purpose of the shield. If, for instance, you run into EMI problems, you may want to try the earth ground connection to see if it helps the EMI situation. If you need to connect earth ground to some aspect of your internal circuitry (e.g. a shield around a component or circuit section), you may be forced to connect to both ends of the shield and live with the potential of an AC-coupled ground loop of some sort.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check whether the android device can connecto to the network or not? I am a beginner in Android programming, I am trying to make Http requests to a remote server and I would like to check whether the user can connect to the net or not in order to avoid my app to crash due to the fail of an AsyncTask I am making.
I found this method:
 private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
 }

But when I try to call it inside the doInBackground AsyncTask method implementation the app crashes:
 class RemoteThread extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(IMieiDati.this);
        pDialog.setMessage("Caricamento...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... strings ){
        // checking whether the network is not available
        // but the app crashes here
        if (!isNetworkAvailable()) {
            Log.d("Message", "No Network Connection. Aborting.");
        }

       // here I should make the request if the network is available
    }
            ...etc, etc...

How can I resolve and e.g. show a message to the user that says something like "We are sorry, in order to use the app properly, you should connect to the network" or anything like that?
Thanks!

A: First it will better to check for network before executing the RemoteThread class.
And also make sure you've added permissions to you application
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
Also check that your are importing right package
import android.content.Context;


text:
Q: What Eclipse IDE support JSF 2.0? I downloaded the Eclipse Galileo and Juno Eclipse (Eclipse IDE for Java EE Developers) but I can not run my JSF2 project. I've tried changing the Project Facets/JavaServer Faces for 2.0 but doesn´t allow the change. What Eclipse IDE support JSF 2.0?
Thanks!

A: I am using Eclipse indigo. Its working fine for me.

A: For JSF 2.0, upgrade your Eclipse to version Helios (v3.6) onward, it has full support of Java EE 6 support, including JSF 2.0.
See: Does the Eclipse IDE support JSF 2.0?
You can Google this answer relatively quickly.


text:
Q: Obtain User Input Inside An NgRepeat Directive In AngularJS I have an AngularJS app which has an ngRepeat directive. Inside the directive, I have a textbox that a user can use to enter numeric values. When the textbox changes, I want to take the user input and act on it. How do I pass the user input into my ngChange event?

    <input type="number" value="{{ d }}" ng-change="vm.onChange(userInput)" />

(function () {
  var app = angular.module('TestApp', []);
  app.controller('TestCtrl', [function () {
    var vm = this;
    vm.data = [1, 2, 3];

    vm.onChange = function (inputValue) {
      // act on the change event...
    };

  }]);
})();

A: Observations

*

*You need to add the model to the $scope i.e: $scope.data = [1, 2, 3];.

*Directive ng-change works alongside with ng-model, so your need to set that directive to each input, i.e: <input ng-model='d' ng-change='onChange(d)' type="number" value="{{ d }}">
Look at this code snippet:

var app = angular.module('TestApp', []);
app.controller('TestCtrl', ['$scope', function($scope) {
  $scope.data = [1, 2, 3];

  $scope.onChange = function(inputValue) {
    console.log(inputValue);
  };
}]);

        <input ng-model='d' ng-change='onChange(d)' type="number" value="{{ d }}">

As you can see, now the onChange function is being called for every change in input.

A: You need to bind the value to something in the VM. Here's an example:

(function () {
  var app = angular.module('TestApp', []);
  app.controller('TestCtrl', [function () {
    var vm = this;
    vm.data = [1, 2, 3];
    vm.nums = [];

    vm.onChange = function (i) {
      console.log(nums[i]);
    };
  }]);
})();

      <input type="number" ng-model="vm.nums[$index]"
             ng-change="vm.onChange($index)">

A: First thing first, your input syntax is missing a ">".
Second you need to have ng-model on your input.
This is the code:

    <input type="number" ng-change="vm.onChange(d.val)" ng-model="d.val">

var vm = this;
    vm.data = [{val:1}, {val:2}, {val:3}];

    vm.onChange = function (val) {
      console.log(val);
    };


text:
Q: Can I use $P(x_1+x_2+...+x_nSuppose that we have $n$ independent Bernoulli random variables, $x_1,\ldots,x_n$ such that each $x_i$ takes value 1 with success probability $p_i$ and value $0$ with failure probability $1-p_i$ ,i.e.,
\begin{align}
P(x_1=1) & = p_1,\  P(x_1=0)= 1-p_1 \\
P(x_2=1) & = p_2,\ P(x_2=0) = 1-p_2 \\
& \vdots \\
P(x_n=1) & = p_n,\ P(x_n=0)=1-p_n
\end{align}
So $x_1+...+x_n$ has Poisson binomial distribution since it is a sum of independent Bernoulli trials that are not necessarily identically distributed with the following pdf:
$$
  \mathsf{Pr}\left(K=k\right) = \sum_{A \in F_k} \prod_{i \in A} p_i \prod_{j \in A^c} (1-p_j)
$$
where $F_k$ is the set of all subsets of k integers that can be selected from $\{1,\ldots,n\}$. and $A^c$ is the complement of A.
Suppose that I have calculated the following probability $$P(x_1+x_2+...+x_n<k)$$
Now I substitute one of $x_i$'s with another Bernoulli random variable (let say we substitute  $x_1$ with $y_1$ with success probability $p'_1$) now I want to calculate $$P(y_1+x_2+...+x_n<k)$$
My question is :
Can I use $P(x_1+x_2+...+x_n<k)$ to calculate $P(y_1+x_2+...+x_n<k)$ ?

A: Write $z = x_2 + \ldots + x_n$.  You have $$P(x_1 + z = k) = p_1 P(z = k-1) + (1-p_1) P(z=k)$$ so
$$ \eqalign{P(z = 0) &=  \frac{P(x_1 + z = 0)}{1-p_1} \cr
            P(z = 1) &= \frac{P(x_1 + z = 1) - p_1 P(z = 0)}{1 - p_1} = \frac{P(x_1 + z = 1)}{1-p_1} - \frac{p_1 P(x_1 + z = 0)}{(1 - p_1)^2}\cr
P(z = 2) &= \frac{P(x_1 + z = 2)}{1-p_1} - \frac{p_1 P(x_1+z=1)}{(1-p_1)^2}
+ \frac{p_1^2 P(x_1 + z = 0)}{(1-p_1)^3}\cr
P(z = k) &= \sum_{j=0}^k \frac{(-p_1)^j P(x_1 + z = k-j)}{(1-p_1)^{j+1}}}$$
and then
$$P(y+z = k) = p'_1 P(z=k-1) + (1-p'_1) P(z=k)$$


text:
Q: Strange issues with expanding and collapsing list elements in a Wordpress generated form I'm hoping someone might be able to show me
a) what is causing the current issues
b) an altogether more elegant solution
for the following problem:
I am extracting all the pages out of a Wordpress blog and the idea is to create a menu where sub navigation expands and contracts as the user interacts.
The nested menu markup is essentially as follows:

        Selected projects

Level 2

Level 2

Level 2

        Archive

                Level 2

Level 3

Level 3

                Level 2

Level 3

Level 3

Level 3

Level 3

The jQuery is as follows :
$(".page_item a").click( function(){

    /* Set vars */
    var $this = $(this);
    var isActive = false;
    var hasSublinks = false;
    var nextLevel = $(this).next("ul");

    if ( $this.next().html() !== null ) {hasSublinks = true;}
    if ( $this.hasClass('active') ) {isActive = true;}

    if ( !hasSublinks ) {
        return true;
    } else {
        /* I have sub links... */
        if (!isActive) {
            /* I am not active */
            $(".active").removeClass("active");
            $(".children").slideUp();

            $(this).next("ul").slideDown();
            $(this).addClass('active');

        } else {
            $(nextLevel).slideUp();
            $(this).removeClass('active');

        }
        return false;
    }

});

When I click on 'Archive', it expands its child list as expected. However, when I click on a link here, I expect it to slide down and reveal the next level (Level 3) but it has the opposite effect of sliding up to go back to where I started from.
I've spent a lot of time in the console, on Wordpress Codex trying to see what might be the issue, particularly challenging for me is that this code was working before (or seemed to). I'm aware that the code isn't the cleanest so I'm really hoping can show me where I'm going wrong!
Thanks

A: You don't seem to have the class active anywhere, so when you are doing this :
  if ( $this.hasClass('active') ) {isActive = true;}

It set is Active to false
So you go in this part of code :
if (!isActive) {
        /* I am not active */
        $(".active").removeClass("active");
        $(".children").slideUp();

There is clearly a problem with your logic, try fixing it, i'll give you a hint if you find nothing


text:
Q: Changing columns position in attributes table using PyQGIS Well, I'm new to PyQGIS and I was creating a new shapefile and layer using some information from other layer.
I inserted the data that I wanted inside attributes table and styled it, but I wanted the table to follow my feature position and it's not working the way I want.
Here's what I want:
Ex: TIPO_VIA |NOME_VIA | N_POLICI  | COMPLEMENTO | CODEPOSTAL | etc..
Here's how it goes:
Ex: CODEPOSTAL  | etc.. | TIPO_VIA |NOME_VIA | N_POLICIA  | COMPLEMENTO| etc..
root = QgsProject.instance().layerTreeRoot()
group = root.addGroup("RBAL_BYSAT_TEMP")
path = QgsProject.instance().readPath("./")
group_name = "RBAL_BYSAT_TEMP"
rbal_bysat_path = path + "/TEMP_SHAPE_FILE_FOLDER/"+group_name+".shp"

layerFields = QgsFields()
field_list = [QgsField("TIPO_VIA", QVariant.String),
            QgsField("NOME_VIA",  QVariant.String),
            QgsField("N_POLICIA", QVariant.Int),
            QgsField("COMPLEMENTO", QVariant.String),
            QgsField("CODEPOSTAL", QVariant.Int),
            QgsField("COMMUNE", QVariant.String),
            QgsField("INSEE", QVariant.String),
            QgsField("HEXACLE_N", QVariant.Int),
            QgsField("COORD_X", QVariant.Double),
            QgsField("COORD_Y", QVariant.Double),
            QgsField("PRECISION", QVariant.String),
            QgsField("BAL_LOG", QVariant.Int),
            QgsField("BAL_ENT", QVariant.Int),
            QgsField("BAL", QVariant.Int),
            QgsField("TIPO_CONEXAO", QVariant.String),
            QgsField("FOTO_MURO", QVariant.String),
            QgsField("FOTO_CAIXA", QVariant.String),
            QgsField("HPs_TOTAL", QVariant.Int),
            QgsField("NOVA_RUA", QVariant.String),
            QgsField("COMENTARIO", QVariant.String)]

for field in field_list:
    layerFields.append(field)

layer = iface.activeLayer()
rbal_france = layer.selectedFeatures()

feature_list = []
for feature in rbal_france:

    feat = QgsFeature(layerFields)
    feat.setGeometry(feature.geometry())
    attr = feature.attributes()
    list = [ attr[4],attr[7], NULL,NULL, attr[0], NULL,attr[1],attr[6],attr[28],attr[29],attr[14], NULL, NULL,NULL, NULL, NULL, NULL, NULL, NULL, NULL]

    feat.setAttributes(list)
    feature_list.append(feat)

writer_rbal = QgsVectorFileWriter(rbal_bysat_path, "UTF-8", layerFields, QgsWkbTypes.Point, QgsCoordinateReferenceSystem("EPSG:4326"), "ESRI Shapefile")
writer_rbal.addFeatures(feature_list)

layer_rbal = QgsVectorLayer(rbal_bysat_path, group_name , "ogr")

layer_rbal.startEditing()

layer_rbal.loadNamedStyle(path + "/TEMP_SHAPE_FILE_FOLDER/STYLE_QML/RBAL_BYSAT.qml")
layer_rbal.triggerRepaint()

layer_rbal.dataProvider().addFeatures(feature_list)

crs = layer_rbal.crs()
crs.createFromId(4326)
layer_rbal.setCrs(crs)

layer_rbal.commitChanges()

QgsProject.instance().addMapLayer(layer_rbal,False)
group.insertChildNode(0, QgsLayerTreeLayer(layer_rbal))

A: The order of the fields must be ordered in the qml file as in the second example. If you add the file RBAL_BYSAT_TEMP.shp to QGIS by drag-and-drop you will see that the order is as you want. Applying the qml to the layer changes the order of fields.
To solve the issue,

*

*sort the fields in the attribute table as you desire, save the style (using "Layer Properties > Style Button > Save Style...") as a new qml file and use that qml file for the layer in loadNamedStyle method.

Or

*

*remove loadNamedStyle line.


text:
Q: Ubuntu 16.04 Server Network Delay I am running Ubuntu 16.04 server standard and when booting without a network cable plugged in it takes almost 5 minutes for the system to boot. Is there a way to make this so it only retries to get an answer from the DHCP server once instead of multiple times. Thanks in advance for any help on this issue.
Adam


text:
Q: Theme Customization API and child themes I've recently developed a parent theme that makes heavy use of the Theme Customization API. Is there an easy way to port these settings when a user activates one of my child themes? Currently, the data previously saved in the Customize screen disappears when activating a child theme. Of course, once they reactivate the parent theme, the settings return.
Any dealt with this yet?

A: There is already an answer about this question with explicable examples How do I get a parent theme modification from a child theme?.
You can also check about get_theme_mod here https://developer.wordpress.org/reference/functions/get_theme_mod/


text:
Q: How to get the percentage of non Matching at particular Element value in an two arrays I have an array like: import numpy as np
 a=np.array([[1,0,0,0,0,1],
        [0,0,1,0,1,0],
        [0,0,0,1,0,0],
        [0,0,1,0,0,0]])

 b=np.array([[0,0,0,0,0,1],
        [0,0,1,0,1,1],
        [1,0,0,0,0,1],
        [0,0,1,0,0,1]])

Requirement:
  where the elementvalue of 1 in an array 'a' is equal to element value of 1 in array 'b'.
  Need to access the percentage of matching only with element value 1,not at zero

I tried with:
  matching_error=(np.mean(a!=b)

Output:
   0.25
   # because out of 24 elements in an array 18 are matching(here 0,1 both the values are
   in matching action), I need matching action at only element value 1

Required Output:
   0.83
   #because out of 24 elements, the element value is matching at 4 points

A: Following your previous logic, you can do:
1-np.mean((a==b) & (a==1))  # 1 - mean(values are equal AND equal to 1)

Alternative:
np.mean((a!=b) | (a!=1))    # mean(values are different OR not equal to 1)

output: 0.8333333333333334

A: Since your data is (implicitly) binary, i.e. only consisting of 0s and 1s, one could use
np.mean(a+b<2)
0.8333333333333334

which takes a mere 14 characters.
Similarly,
1 - np.mean(a+b==2)
>0.8333333333333334

A: Given the specified result, I believe what the question is attempting to ask is equivalent to this:

For what percentage of array positions is the item in at least one of the arrays equal to zero.

This can be calculated like this:
np.mean( (a==0) | (b==0) )

Output:
0.8333333333333334


text:
Q: group and sum multiple variables R I have a somewhat simple question (i think), but can't seem to find a solution. I would like to create a new dataframe that groups and sums multiple variables.
My data:
ID  Test    result  ped adult
AB  a   0   0   1
AB  b   1   0   1
FM  a   1   1   0
FM  c   0   1   0
WD  a   0   0   1
WD  b   1   0   1
WD  c   0   0   1
WD  d   1   0   1
WD  a   0   0   1
WD  a   1   0   1

The output I would like:
Test    No of ID's test with test performed     No of ID's positive     ped adult
a   3   2   1   1
b   2   2   0   2
c   2   0   0   0
d   1   1   0   1

I have tried using aggregate and dplyr using group_by and sum, but have not had success.
NB: edited to add ped and adult columns. I would like to sum the positive tests and then have a sum for ped and adult positive tests.

A: We can use aggregate from R base
> aggregate(result~Test, data=df1, function(x) c(N = length(x), Sum=sum(x)))
  Test result.N result.Sum
1    a        5          2
2    b        2          2
3    c        2          0
4    d        1          1


text:
Q: Background Image Not scalable in Mobile view /* background image and overlay */

body {
  background: #212121 url("img/bg.jpg") no-repeat top center fixed;
  background-size:cover;
  **strong text**margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  }

Website: https://ejive2k18-07.firebaseapp.com/ -Working perfect in widescreen but not compatible with mobile view.Will be glad if anyone solve this issuse!

A: If you want the same image to scale based on the size of the browser window:
background-image:url('../images/bg.png');
background-repeat:no-repeat;
background-size:contain;
background-position:center;
Do not set width, height, or margins.


text:
Q: Unable to generate script I am having one azure sql database.
When I try to genearate database script by selecting "Schema and data" or "data only" option, sql server is throwing error: can not generate script.
When I select schema only, then it successfully generates script.
is this related to some permission?

A: I just did mine and it worked perfectly. Check if you can find the error message - the answer lies there. And yes, I think the most likely cause is permissions. Also, check circular references - I had that issue in the past.
I used SSMS from my local machine.


text:
Q: Data Model for Boolean Expressions Do you know a way to organize boolean expressions in a database while allowing infinite nesting of the expressions?
Example:
a = 1 AND (b = 1 OR b = 2)

The expression as a whole shouldn't be stored as varchar to preserve data integrity.

A: An expression is a treelike structure. So you need a way to present the tree in a table.
You can for example use the fields:

*

*ID

*TypeExpression (and, or etc...)

*FirstChildID

*SecondChildID

In this case, you have the following types:

*

*AND, Children point to other expression.

*OR, Children point to other expression.

*Equal, Children point to other expression.

*Literal, FirstChild points to an entry in a literal table.

*VariableLookup, FirstChild points to an entry in a varable table.

But I think there are better ways to organise expression. I once made a simple expression evaluator that accepts a string and produces a numeric result.

A: I would store the expression in polish form, in a varchar/text column. An expression in polish form (operand before operands, no brackets) is much easier to parse with a recursive function (or a stack of course).
a = 1 AND (b = 1 OR b = 2)
in polish form shows like this:
AND = a 1 OR = b 1 = b 2

A: This type of expression is most usually expressed as a tree (a hierarchy), which are notoriously annoying to query in SQL.
We'll assume that a and b are numeric for the moment and that literals ('1', '2') are distinguished from variables.
Table Nodes
id
type (Variable|Literal)
name (nullable for literal)
value

Table Operators
id
name (=, AND, OR, NOT)
leftNodeId
rightNodeId

This structure is very flexible, but querying it to retrieve a complex expression is going to be "fun" (read that "challenging").
And you still have to parse the structure to begin with and evaluate the expression after it has been reconstructed.

A: This is going to be difficult to represent relationally, because by its nature it is both hierarchical and polymorphic (the leaves of your tree can be either variables or constants).

A: The traditional way to model Boolean functions is to use Binary Decision Diagrams, especially Reduced Order Binary Decision Diagrams. It's possible you can find an extension for your DBMS that provides good support for the concept.
UPDATE:
Alternately, if you don't need to query on the Boolean logic, you could use a BDD library and just serialize the BDD into a BLOB or equivalent. It beats using a varchar field because the BDD library would ensure the data was valid.

A: Option 1 would be to use a nested table (a tree with id / parent_id structure), like Gamecat suggested. This is relatively expensive to do, and requires issuing SQL queries repetitively to build the equivalent of a single nested expression.
Option 2 would be to use a serialized object and store it into a varchar column. For example, JSON would be a good choice. It is not white-space sensitive, can be created and parsed in a vast number of languages, and it retains data integrity.
As soon as you have parsed your expression string into a tree object in memory, you can serialize it and store it. If there was no need to manipulate the expression on the database level, I guess I would go that route.

A: Ok withe the answers but what if there are more than 2 expressions in an expression group ?
a = 1 AND (b = 1 OR b = 2 OR b = 3)

I propose this :
-------------------
|    Condition    |
-------------------
| - id            |
| - value1        |
| - value2        |
| - operation     |
-------------------
    |(1)
    |        --------------
    |       |              |
    |       |(*)           |
-------------------        |
| ConditionGroup  |        |
-------------------        |
| - id            |--------
| - groupType     |
| - condition     |
| - subConditionGroups
-------------------

*

*value1, value2 and operation model a final comparison like 'b = 3' (in my case value1 = 'b', value2 = '3' and operation = 'EQUALS')

*groupeType can be 'AND' or 'OR'

*a ConditionGroup can have either a sub-list of ConditionGroups OR a final Condition but not both.

*Now your start expression is a ConditionGroup, recursively dig into its subConditionGroups until you find a final condition, then return the value and apply the proper condition.

Actually that is what I'm about to try.

A: Adding to @Gamechat answer
I think it should be like this
ID
TypeExpression (and, or etc...)
FirstChildID --This can be a leaf node or a pointer to another row in same table
SecondChildID --This can be a leaf node or a pointer to another row in same table
isFirstChildLeaf
isSecondChildLeaf


text:
Q: Save hearts with PlayerPrefs I am building a 2d asteroid shooter game in unity c#. What I need is saving the hearts of the player for the next level. So I just made the score save what I need now is heart saving. The score is saved for the next level, so it works like this, in first level you have for example at the end 3000 points and you go to the nesxt level, then it will start form 3000, but if you click on restart or if oyu quit you start from 0 and fro first level. That's how the score works the same needs to be with the hearts. So if you finish first level with 1 heart then you need to go to 2 with 1 heart. if you finish 2 with 3 hearts tn 3 with 3 hearts will be started , if ou click restart or if you quit then it will start form default. The hearts are images UI, I was thinking to do like the scor with player prefs but I am not sure how.
if (col.gameObject.tag == "AsteroidBig") {
            if (heart.enabled == true && heart1.enabled == true && heart2.enabled == true) {
                heart.enabled = false;
                Instantiate (explosion, col.transform.position, col.transform.rotation);
                Vector3 pos = new Vector3 (0f, 0f, 0f);
                Instantiate (player, pos, Quaternion.identity);
                Destroy (col.gameObject);
                Destroy (this.gameObject);
                Instantiate (medast[Random.Range(0,medast.Length)],col.transform.position,col.transform.rotation);
                Instantiate (medast[Random.Range(0,medast.Length)],col.transform.position,col.transform.rotation);
            } else if (heart1.enabled == true && heart2.enabled == true) {
                heart1.enabled = false;
                Instantiate (explosion, col.transform.position, col.transform.rotation);
                Vector3 pos = new Vector3 (0f, 0f, 0f);
                Instantiate (player, pos, Quaternion.identity);
                Destroy (col.gameObject);
                Destroy (this.gameObject);
                Instantiate (medast[Random.Range(0,medast.Length)],col.transform.position,col.transform.rotation);
                Instantiate (medast[Random.Range(0,medast.Length)],col.transform.position,col.transform.rotation);
            } else if (heart2.enabled == true) {
                heart2.enabled = false;
                Instantiate (explosion, col.transform.position, col.transform.rotation);
                Vector3 pos = new Vector3 (0f, 0f, 0f);
                Instantiate (player, pos, Quaternion.identity);
                Destroy (col.gameObject);
                Destroy (this.gameObject);
                Instantiate (medast[Random.Range(0,medast.Length)],col.transform.position,col.transform.rotation);
                Instantiate (medast[Random.Range(0,medast.Length)],col.transform.position,col.transform.rotation);
            } else if (heart.enabled == false && heart1.enabled == false && heart2.enabled == false) {
                Instantiate (explosion, col.transform.position, col.transform.rotation);
                Destroy (col.gameObject);
                Destroy (this.gameObject);
                Instantiate (medast[Random.Range(0,medast.Length)],col.transform.position,col.transform.rotation);
                Instantiate (medast[Random.Range(0,medast.Length)],col.transform.position,col.transform.rotation);
                GameOverPanel.SetActive (true);
            }
        }

An if statement with hearts looks like that, it is a bit messed up, but it is like this. If you touch the asteroid it checks if 3 hearts are on, one of them is seting to false, then if you have 2 hearts on, then another one is going to false, and so on, till you have no hearts and you loose. That is th logic of the collision. Please help to save this hearts, ask any question becaue I know it is messed up.

A: You have two options here, depending on what's easier for you
1) Create a static class
Static classes aren't reset when you load a new level, so you can store any information about your player there
public class GameData
{
    public static int NumberOfHearts = 3;
}

In your code you would then update NumberOfHearts to reflect how many hearts you have when you get touched by an asteroid. For example,
GameData.NumberOfHearts--; //We just got touched by an asteroid
2) Scene Manager (doesn't apply if you're using Application.LoadLevel())
You could create a GameObject for your player at the root of the scene.
Then when it's time to load your level, you would call
SceneManager.MoveGameObjectToScene(playerObject, "sceneName")
See here for more information about MoveGameObjectToScene.
In this case, the object would be carried over with any scripts and subobjects, so you would already have all the hearts in the next level.


text:
Q: Oracle Apex, Clear page when reloading in browser I have a question, how can I clear all filters, tables and diagrams when the page gets reloaded in the browser?
Kind regards

A: Try to

*

*create a "Page load" dynamic action

*whose action is "Clear"

*and affected element's type is "Triggering element"


text:
Q: Screen brightness and touchpad issues on Dell XPS13 - Ubuntu 12.04 LTS Last week I bought the Dell XPS 13 (L322X) ultrabook only for Ubuntu.
To make sure that I will not have any issues I installed the 12.04 LTS version instead the Sputnik image. In Ubuntu forums, some people said that this version (12.04 LTS) had all the Sputnik features (drivers...).
Everything´s fine, I´m pretty satisfied and Ubuntu works almost ¨out the box¨ except for some issues:

*

*I can´t adjust the screen brightness with the function keys (Fn + f4/f5). Actually the both keys works fine. The brightness bar appears at the left top side of the desktop, but the screen don´t respond the commands...

*I can´t adjust the touchpad speed and sensitivity. The pointer speed it´s at the max, but still too slow...
Sorry about my English, I´m from Brazil and I´m kind rusty with the language.

A: I don't have real answers but:
I installed Linux Mint 13 on the same Dell XPS 13 with full HD screen and everything works fine.
Including the brightness and the touchpadspeed, but I think this speed is good for the laptop with normal resolution and for full HD we need double that speed, I'll try to find out how to alter this.
After some searching I found that there is a PPA for this machine:
Will I need a PPA for my Dell XPS 13 "Sputnik" laptop?
In this link you can find the PPA:
http://www.calazan.com/how-to-install-the-ubuntu-12-04-sputnik-image-on-your-dell-xps-13-ultrabook/
To add the ppa: sudo add-apt-repository ppa:canonical-hwe-team/sputnik-kernel
Edit: I also found that the kernel since 3.9 should support everything out-of-the-box, but only the brightness controls still are not reliable.
A procedure to update the kernel can be found at http://www.upubuntu.com/
It worked for me until my last apt-get dist-upgrade, so I advise against that, it stopped my touchpad doubleclick and sidescroll.
You can try Linux Mint 13-64 bit from a Unetbootin live USB after disabling Secure boot and UEFI.
I still have Windows8 on the machine under Secure boot and UEFI but only see it after I change my bios settings.
I did some partitioning from Windows before installing Mint.
Love the machine :-)
Please let me know if you want some more information.
Good luck.
Kees , the Netherlands.

A: Solution for brightness issue that helped me:
sudo gedit /etc/default/grub

Find string with GRUB_CMDLINE_LINUX_DEFAULT and change it to:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"

Than reboot.
If it won't fix the issue also try to change GRUB_CMDLINE_LINUX="" to:
GRUB_CMDLINE_LINUX="acpi_osi=Linux"

In the same file and reboot.


text:
Q: AirTag can't be used to recover stolen item if thief has an iPhone? The AirTag has an anti-stalking mechanism, so than when an unknown AirTag moves with your iPhone you will get a notification.
This would mean that a thief who has an iPhone will get notified that the stolen item is being tracked. The thief then can locate the AirTag with their own iPhone and disable it.
So for theft situations the AirTag seems to be pretty useless to me.
Am I missing something? Is there a solution to this built in?

A: AirTags are not marketed by Apple as an anti-theft solution. It is for lost items only (i.e. when you can't remember where you left your car keys in your home).
If an AirTag is stolen, the thieve can detect the tag (given that they have an iPhone running a sufficiently new version of iOS) and disable it. Indeed even if they haven't, the AirTag will after a time emit a sound when moved, alerting the thief to its presence. However, you will still be able to see its last known location in Find My.


text:
Q: Time function seems to always be increasing in my Python Fibonacci program I'm trying to use a timer to see how fast each function is.  My codes work but after running it many times I get slightly different results and wonder if I'm implementing function correctly.  I am only going to the 10th Fibonacci number which is 55 for testing.  Each time I run the "A" option the clockTime() function returns a slightly larger number than before.  Any thoughts would be appreciated.
import math
import time

#create a time variable
start_time = time.time()

#create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2

#the runtime function
def clockTime():
    print("\nrun time: " + str(time.time()-start_time))

#the golden ration function
def fibGen(num):
        for number in range(0,num+1):
            val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
            print('{i:3}: {v:3}'.format(i=number, v=round(val)))

#the find element < Max number function
def elemFib(num):
        for number in range(0,num+1):
            val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
            if val < num:
                print('Fib({}): {}'.format(number, round(val)))

#Pythonic way
def pythonic():
    a, b = 0,1
    while a < 57:
        print(a, sep=" ", end="\n")
        a, b = b, a+b

#display the Main Menu
def dispMenu():
    print('---------------------Fibonacci Series ------------------\n')
    print('(A) Print Fibonacci numbers to the nth term')
    print('(B) Print Fibonacci numbers until element is less than Max number')
    print('(C) pythonic print')
    print('(Q) Quit the program\n')

def  main():
          # set boolean control variable for loop
          loop = True

          #Create while loop for menu
          while loop:

              #Display the menu
              dispMenu()

              #Get user's input
              choice = (input('Please make a selection: '))

              #Perform the selected action
              if choice.upper() == 'A':
                  num = int(input("How many Fibonacci numbers should I print? "))
                  fibGen(num)
                  clockTime()
              elif choice.upper() == 'B':
                  num = int(input("the element should be less than? "))
                  elemFib(num)
                  clockTime()
              elif choice.upper() =='C':
                  pythonic()
                  clockTime()
              elif choice.upper() == 'Q':
                  print('\nExiting program, Thank you and Goodbye')
                  loop = False
              else:
                  print('\nInvalid selection, try again\n')

main()

A: The problem is you initialized start_time at the start of the program rather than right before you ran the function to be timed.  You were adding in the times of previous runs as well as the time the user took to read the instructions and make a decision, etc.  Here's a rework of your code that should do what you want:
import math
import time

# create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2

# the runtime function
def clockTime(start_time):
    print("\nrun time:", time.time() - start_time)

# the golden ration function
def fibGen(num):
    for number in range(num+1):
        val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
        print('{i:3}: {v:3}'.format(i=number, v=round(val)))

# the find element < Max number function
def elemFib(num):
    for number in range(num + 1):
        val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
        if val < num:
            print('Fib({}): {}'.format(number, round(val)))

# Pythonic way
def pythonic():
    a, b = 0, 1

    while a < 57:
        print(a, sep=" ", end="\n")
        a, b = b, a + b

# display the Main Menu
def dispMenu():
    print('---------------------Fibonacci Series ------------------\n')
    print('(A) Print Fibonacci numbers to the nth term')
    print('(B) Print Fibonacci numbers until element is less than Max number')
    print('(C) pythonic print')
    print('(Q) Quit the program\n')

def  main():
    # set boolean control variable for loop
    loop = True

    # Create while loop for menu
    while loop:

        # Display the menu
        dispMenu()

        # Get user's input
        choice = input('Please make a selection: ').upper()

        # Perform the selected action
        if choice == 'A':
            num = int(input("How many Fibonacci numbers should I print? "))
            start_time = time.time()
            fibGen(num)
            clockTime(start_time)
        elif choice == 'B':
            num = int(input("the element should be less than? "))
            start_time = time.time()
            elemFib(num)
            clockTime(start_time)
        elif choice == 'C':
            start_time = time.time()
            pythonic()
            clockTime(start_time)
        elif choice == 'Q':
            print('\nExiting program, Thank you and Goodbye')
            loop = False
        else:
            print('\nInvalid selection, try again\n')

main()


text:
Q: How can I select for the last JSON entry in Javascript/Google Apps Script? Let's say that I got this from a JSON file.

[{
    "data": {
      "member": "Feufoe, Robert",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "Hefo, Talia",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "Mossler, John",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "McEvans, Nora",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  }
]

In my script, I want to query the properties of the last entry (in this case, the entry belonging to Nora McEvans) when defining different variables.
However, the file containing the above JSON is dynamic, constantly being added to. So I need the script to reference only the last entry every time.
How can I do this?

A: Just reference YOUR_ARRAY[YOUR_ARRAY.length - 1]
Example:
var data = [{
    "data": {
      "member": "Feufoe, Robert",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "Hefo, Talia",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "Mossler, John",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  },
  {
    "data": {
      "member": "McEvans, Nora",
      "project": "Random Event",
    },
    "folder": null,
    "id": 1062110,
    "spam": null
  }
];
console.log(data[data.length - 1]);

A: Just to add what I think is a neater solution for the last item in an Array
var lastItem = data.slice(-1);

It's only better if you are following the maxim of less typing is better.


text:
Q: How can I check if an email has been exchanged in cleartext? How can I check that an email that I received has been transmitted in encrypted form between all MTAs by which it passed? This is not a question about end-to-end encryption, i.e., it's OK that the MTAs saw the message in the clear; but I'd like to know if the message was exchanged in cleartext at some point.

A: This can be checked by inspecting the "with XXX" part of the "Received" headers of the email, to check if the methods XXX are secure (see methods here: https://www.iana.org/assignments/mail-parameters/mail-parameters.xhtml#mail-parameters-7). This is what is done by the Paranoia Thunderbird extension in its source code: https://github.com/gjedeer/paranoia/blob/master/content/overlay.js


text:
Q: is it possible to write entire python output to a text or csv file? i'm new to python and working on traceroute so I was wondering if it's possible to write entire python traceroute result output to txt and Csv file? any idea how can i achieve that because i can't find any proper one which shows how to do it.
thanks

A: import subprocess

with open("hostlist.txt", "r") as hostlist, open("results.txt", "a") as output:
    for host in hostlist:
        host = host.strip()

        print "Tracing", host

        trace = subprocess.Popen(["tracert", "-w", "100", host], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        while True:
            hop = trace.stdout.readline()

            if not hop: break

            print '-->', hop.strip()
            output.write(hop)

        # When you pipe stdout, the doc recommends that you use .communicate()
        # instead of wait()
        # see: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait
        trace.communicate()

I am reading host details from hostlist and writing o/p in a file


text:
Q: login and register screen in silverlight using wcf web service i have implemented an application using silverlight mvvm and prism, mef, wcf services, now my requirement is how to use wcf web services to create  login and register screen to redirect into application . Please suggest a  good approach to do this task
Advance thanks

A: That is not really a technical question.  It is more of an "How do I create my app" type of question.  That being said, I would try looking at the demo applications on silverlight.net and see if you can find something close to what you are looking for there.  Those usually come with full source code.


text:
Q: Which technology is behind intel's realsense depth sensor? Which technology is behind intel's realsense depth sensor?
Is it a structured light or ToF approach?
Where can I find specs?

A: You might be able to find some more information on the RealSense Website
As far as specs go, this is all I could find:
Full VGA depth resolution
1080p RGB camera
0.2 – 1.2 meter range (Specific algorithms may have different range and accuracy)
USB 3.0 interface

A: The IR Laser Projector on the Intel RealSense F200 camera sends non visible patterns (coded light) onto the object. The reflected patterns are captured by the IR camera and processed by the ASIC  which assigns depth values to each pixel to create a depth video frame.
Applications see 2 (depth and color) video streams.
The ASIC syncs depth with color stream (texture mapping) using UVC time stamp and generates data flags for each depth value (valid, invalid, or motion detected.)

A: At least for the front-facing camera, it seems to be structured light.


text:
Q: Linker LNK2005 Error I have searched around here and found this question tons of times but the author usually didn't provide a code example, I ran into this problem today and I'm not quite sure how to fix it.
1 of the errors lists bool Init(?@@A_NA) already defined in Client.obj. Here is portions of my code for Client.cpp, Main.cpp, and Main.h.
Client.cpp
#include "stdafx.h"
#include "Main.h"
// the rest of the code doesn't have anything to do with this error..

Main.h
#include "stdafx.h"
bool Init;
// the rest of the code doesn't have anything to do with this error..

Main.cpp
#include "stdafx.h"
#include "Main.h"

int main()
{
    Init = false;
    return 0;
}

A: In #include "Main.h" you have defined bool Init;, so every-time you include Main.h, you will get Init redefined. If you make Init static,
static bool Init;

Here Init will have page level scope, and your code should work fine.
Or better, you make Init extern in Math.h,
extern bool Init;

Then in .cpp file define it, so that you will have multiple declaration, but one definition.


text:
Q: how to close ajax modal popup with clicking outside I am writing a web page in c# asp.net . The page is using a master page . I have an ajax modal popup window in the page. I want to add 2 features for this popup:

*

*Close the popup when user clicks outside the modal popup

*Trigger a serverside code after modal popup is closed.

There are similar questions on stackoverflow but almost all of them are related to jquery modal popups.
here is my code:
<asp:Button ID="Button1" runat="server" Style="display: none" />
    <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" OkControlID="btnOkay"
        TargetControlID="Button1" PopupControlID="Panel1" PopupDragHandleControlID="PopupHeader"
        Drag="true" BackgroundCssClass="ModalPopupBG">
    </asp:ModalPopupExtender>
    <asp:Panel ID="Panel1" runat="server" CssClass="PopupCss">
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>

                                JW Player goes here

                            <div class="fb-comments" data-href="<%=videoLink%>" data-num-posts="3" data-width="470">

                            <asp:Rating ID="Rating1" runat="server" MaxRating="5" StarCssClass="ratingStar" FilledStarCssClass="ratingStarFilled"
                                AutoPostBack="false" OnChanged="VideoRatingChanged" EmptyStarCssClass="ratingStarEmpty"
                                WaitingStarCssClass="ratingStarEmpty">
                                <asp:HiddenField ID="HiddenField1" runat="server" Value='<%=videoId%>' />
                            </asp:Rating>
                            &nbsp (<%=voteCount%>)

                            Minder Score:
                            <%=minderScore %>

                                <input id="btnOkay" type="button" value="Kapat" />

            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>

and in the code behind i show the popup with this line:
ModalPopupExtender1.Show();

Any help would be appreciated.
Thanks in advanced.

A: to hide / show modalpopuextender using javascript, pls try:
function hidemodal() {
$find('ModalPopupExtender1').hide();
}

function showmodal() {
$find('ModalPopupExtender1').show();
}

you can raise that hidemodal() method on click event or else.
Also you can add code inside hidemodal() method with calling a server side script from javascript using PageMethods to triggers server side function. Find on net about asp.net PageMethods
function hidemodal() {
$find('ModalPopupExtender1').hide();
PageMethods.AnyServerFunction(param, onsuccess_callback);
}

function onsuccess_callback() {
}

Regards,

A: You can bind the click event on the body, and set e.stopPropagation(); inside the click, after that you can check if the clicked element is the popup element, if it is, do nothing, if it's not, close the popup


text: Q: StartMenuExperienceHost.exe keeps waking my computer Did anybody find a solution for this? I have tried all posted answers to similar topics and could stop most of the issues that were causing windows to return from hibernation except this last one. I'm running Windows 10 Pro, latest update.


text:
Q: SpeechRecognizer fails after minutes I am working on an iOS project that uses SFSpeechRecognizer, it works fine in the beginning. I speak some word and it responds. But after one or two minutes, it just fails. It does not give any feedbacks of recognized results.
I wonder if that's related to the buffer, but I don't know how to fix it.
I basically used the demo of SpeechRecognizer to build the project. The difference is that I store the recognized result word by word in an array. And the program analyzes the array and responds to certain words like "play" or some other commands that were set previously. After the program responds to commands, it deletes this element of the array.
Talk is cheap, here is the code:

*

*The recognizer, you can see the supportedCommands array that filter some specific words for the program to respond. The other parts are similar to the demo at https://developer.apple.com/library/content/samplecode/SpeakToMe/Listings/SpeakToMe_ViewController_swift.html#//apple_ref/doc/uid/TP40017110-SpeakToMe_ViewController_swift-DontLinkElementID_6
class SpeechRecognizer: NSObject, SFSpeechRecognizerDelegate {

    private var speechRecognizer: SFSpeechRecognizer!
    private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest!
    private var recognitionTask: SFSpeechRecognitionTask!
    private let audioEngine = AVAudioEngine()
    private let locale = Locale(identifier: "en-US")

    private var lastSavedString: String = ""
    private let supportedCommands = ["more", "play"]

    var speechInputQueue: [String] = [String]()

    func load() {
        print("load")
        prepareRecognizer(locale: locale)

        authorize()
    }

    func start() {
        print("start")
        if !audioEngine.isRunning {
            try! startRecording()
        }
    }

    func stop() {
        if audioEngine.isRunning {
            audioEngine.stop()
            recognitionRequest?.endAudio()

        }
    }

    private func authorize() {
        SFSpeechRecognizer.requestAuthorization { authStatus in
            OperationQueue.main.addOperation {
                switch authStatus {
                case .authorized:
                    print("Authorized!")
                case .denied:
                    print("Unauthorized!")
                case .restricted:
                    print("Unauthorized!")
                case .notDetermined:
                    print("Unauthorized!")
                }
            }
        }
    }

    private func prepareRecognizer(locale: Locale) {
        speechRecognizer = SFSpeechRecognizer(locale: locale)!
        speechRecognizer.delegate = self
    }

    private func startRecording() throws {

        // Cancel the previous task if it's running.
        if let recognitionTask = recognitionTask {
            recognitionTask.cancel()
            self.recognitionTask = nil
        }

        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
        try audioSession.setMode(AVAudioSessionModeDefault)
        try audioSession.setActive(true, with: .notifyOthersOnDeactivation)

        recognitionRequest = SFSpeechAudioBufferRecognitionRequest()

        let inputNode = audioEngine.inputNode
        guard let recognitionRequest = recognitionRequest else { fatalError("Unable to created a SFSpeechAudioBufferRecognitionRequest object") }

        // Configure request so that results are returned before audio recording is finished
        recognitionRequest.shouldReportPartialResults = true

        // A recognition task represents a speech recognition session.
        // We keep a reference to the task so that it can be cancelled.
        recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in
            var isFinal = false

            if let result = result {

                let temp = result.bestTranscription.formattedString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).lowercased()
                //print("temp", temp)
                if temp != self.lastSavedString && temp.count > self.lastSavedString.count {

                    var tempSplit = temp.split(separator: " ")
                    var lastSplit = self.lastSavedString.split(separator: " ")
                    while lastSplit.count > 0 {
                        if String(tempSplit[0]) == String(lastSplit[0]) {
                            tempSplit.remove(at: 0)
                            lastSplit.remove(at: 0)
                        }
                        else {
                            break
                        }
                    }

                    for command in tempSplit {
                        if self.supportedCommands.contains(String(command)) {
                            self.speechInputQueue.append(String(command))
                        }
                    }
                    self.lastSavedString = temp

                }
                isFinal = result.isFinal
            }

            if error != nil || isFinal {
                self.audioEngine.stop()
                inputNode.removeTap(onBus: 0)
                self.recognitionRequest = nil
                self.recognitionTask = nil
            }
        }

        let recordingFormat = inputNode.outputFormat(forBus: 0)
        inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
            self.recognitionRequest?.append(buffer)
        }

        audioEngine.prepare()

        try audioEngine.start()

    }
}

*How we use it:
    if self.speechRecognizer.speechInputQueue.count > 0 {
    if self.speechRecognizer.speechInputQueue[0] == "more" {
        print("temp", temp)
        print("content", content)
       // isSpeakingContent = true
        self.textToSpeech(text: content)
    }
    else if self.speechRecognizer.speechInputQueue[0] == "play" {
        print("try to play")
        let soundURL = URL(fileURLWithPath: Bundle.main.path(forResource: "cascade", ofType: "wav")!)

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
        }
        catch {
            print(error)
        }
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
    else {
        self.textToSpeech(text: "unrecognized command")
    }
    self.speechRecognizer.speechInputQueue.remove(at: 0)
    print("after :", self.speechRecognizer.speechInputQueue)
}

It responds to certain commands and plays some audio.
Is there any problem with the Buffer? Maybe after one or two minutes' recognization, the buffer is full? The recognizer just fails over time.

A: From WWDC 2016 Session 509: Speech Recognition API:

For iOS 10 we're starting with a strict audio duration limit of about one minute which is similar to that of keyboard dictation.


text:
Q: Convert incomplete 12h datetime-like strings into appropriate datetime type I've got a pandas Series containing datetime-like strings with 12h format, but without the am/pm abbreviations. It covers an entire month of data :
40    01/01/2017 11:51:00
41    01/01/2017 11:51:05
42    01/01/2017 11:55:05
43    01/01/2017 11:55:10
44    01/01/2017 11:59:30
45    01/01/2017 11:59:35
46    02/01/2017 12:00:05
47    02/01/2017 12:00:10
48    02/01/2017 12:13:20
49    02/01/2017 12:13:25
50    02/01/2017 12:24:50
51    02/01/2017 12:24:55
52    02/01/2017 12:33:30
Name: TS, dtype: object
(318621,) # shape

My goal is to convert it to datetime format, so as to obtain the appropriate unix timestamps values, and make comparisions/arithmetics with other datetime data with, this time, 24h format. So I already tried this :
pd.to_datetime(df.TS, format = '%d/%m/%Y %I:%M:%S') # %I for 12h format

Which outputs me :
64     2017-01-02 00:46:50
65     2017-01-02 00:46:55
66     2017-01-02 01:01:00
67     2017-01-02 01:01:05
68     2017-01-02 01:05:00

But the am/pm informations are not taken into account. I know that, as a rule, the am/pm first have to be specified in the strings, then one can use dt.dt.strptime() or pd.to_datetime() to parse them with the %p indicator.
So I wanted to know if there's an other way to deal with this issue through datetime or pandas datetime modules ? Or, do I have to manualy add the abbreviations 'am/pm' before the parsing ?

A: You have data in 5 second intervals throughout multiple days.  The desired end format is like this (with AM/PM column we need to add, because Pandas cannot possibly guess, since it looks at one value at a time):
31/12/2016 11:59:55 PM
01/01/2017 12:00:00 AM
01/01/2017 12:00:05 AM
01/01/2017 11:59:55 AM
01/01/2017 12:00:00 PM
01/01/2017 12:59:55 PM
01/01/2017 01:00:00 PM
01/01/2017 01:00:05 PM
01/01/2017 11:59:55 PM
02/01/2017 12:00:00 AM

First, we can parse the whole thing without AM/PM info, as you already showed:
ts = pd.to_datetime(df.TS, format = '%d/%m/%Y %I:%M:%S')

We have a small problem: 12:00:00 is parsed as noon, not midnight.  Let's normalize that:
ts[ts.dt.hour == 12] -= pd.Timedelta(12, 'h')

Now we have times from 00:00:00 to 11:59:55, twice per day.
Next, note that the transitions are always at 00:00:00.  We can easily detect these, as well as the first instance of each date:
twelve = ts.dt.time == datetime.time(0,0,0)
newdate = ts.dt.date.diff() > pd.Timedelta(0)
midnight = twelve & newdate
noon = twelve & ~newdate

Next, build an offset series, which should be easy to inspect for correctness:
offset = pd.Series(np.nan, ts.index, dtype='timedelta64[ns]')
offset[midnight] = pd.Timedelta(0)
offset[noon] = pd.Timedelta(12, 'h')
offset.fillna(method='ffill', inplace=True)

And finally:
ts += offset


text:
Q: javascript: public array with object (sorry for my english=/)
I create an array when 'onload'.
(this:
var $ = {
    ratio: 0.7,
    screen: 500,
    margin: 10,
    canvas: document.getElementById("canvas"),
    ctx: document.getElementById("canvas").getContext("2d"),
}

and $.canvas and $.ctx is give 'null'.
this work if i rewrite it
...
canvas: function(){return document.getElementById("canvas")}
...

but if i want to call this the variable looks like this $.canvas ()
how can i make this variable without '()'???

A: Try this:
window.onload = function(){
    window.$ = {
        ratio: 0.7,
        screen: 500,
        margin: 10,
        canvas: document.getElementById("canvas"),
        ctx: document.getElementById("canvas").getContext("2d"),
    }
}

A: Looks like it's a problem with the scope of your $ variable. By declaring it with the var keyword inside the window.onload function, its scope is the local function and not the global scope.
You could define it outside of the onload function instead:
var $; // in the global scope

window.onload = function(){
    $ = {
        ratio: 0.7,
        screen: 500,
        margin: 10,
        canvas: document.getElementById("canvas"),
        ctx: document.getElementById("canvas").getContext("2d")
    };

    console.log($.canvas);
    console.log($.ctx);
};

By declaring it in the global scope, it can be accessed from outside of the onload function.
Fiddle


text:
Q: populate dropdown AngularJs <select class="form-control" ng-model="companyId" style="height: 40px;" ng-options="id for id in companyId">
</select>

Hi.I have an array scope.companyId in controller which gets populated with the result of controller.array contains say [1,2,3].I need to populate this in dropdown.What is the mistake im doing?.
Thanks.

A: Change ng-model to something else. Your array name and ng-model are same.
<select class="form-control" ng-model="selectedId" style="height: 40px;" ng-options="id for id in companyId">
</select>

Since your ng-model and array (companyId) are same. After selecting a number, companyId will become variable not an array.

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
$scope.companyId=[1,2,3,4];
});

  <select class="form-control" ng-model="selectedId" style="height: 40px;" ng-options="id for id in companyId">
</select>

A: Try this:
<select class="form-control" ng-model="companyIdModel" style="height: 40px;" ng-options="company_id as id for id in companyId">

A: you can set any item which should be pre-selected as value of select's ngModel
you try like this,

A: Lets use this
<select ng-model="companyId" class="dropdown form-control input-sm"
                        ng-options="company as company for company in companyList"></select>

I suggest you to rename this $scope.companyId to $scope.companyList. or rename the binded model to your dropdown. Suggest you the following in js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.companyList= [1,2,3];
})

Here is the plnkr for you.
https://plnkr.co/edit/eNVKGeE0M92keNRDoQEE?p=preview


text:
Q: Why does `ul` have ARIA role `menu` but `menuitem` is forbidden for `li`? Just covered out some strage specs regarding ARIA roles. Why does ul have ARIA role menu but menuitem is forbidden for li?
I would like to describe a navigation bar using ul, li and HTML5's nav element in combination with the ARIA roles navigation, menu and menuitem.
<!DOCTYPE html>

  <title>ARIA role bug?</title>

example.com

W3's HTML5 validator nag me here:

Bad value menuitem for attribute role on element li.

A: The following HTML markup is in the ARIA spec itself (the one you linked), and clearly shows a LI (nested, even) being used as a menuitem. Im guessing the particular markup you are using is forcing it to non-conform but thats just a hunch.

File

New

Open…

      …

  …

A: Jukka is incorrect here. The W3C validator does not check against the WHATWG LS, instead it checks against the W3C HTML specification. The W3C HTML spec is the authoritative source for conformance checking requirements for the W3C Validator.
In regards to menuitem not being allowed as per the HTML spec, I believe this is a bug. And as such I have filed a bug. It is now in my bug queue to be resolved.
I have filed a bug against the W3C validator and wai-aria in HTML doc as well.
Until such times the validator is fixed, I suggest you use the roles as per the WAI-ARIA spec and ignore the validator.
addendum:
I looked back at history of ARIA integration into HTML could not find any reason why menuitem was not allowed, so believe it was an oversight. I fixed and resolved the bug I referenced above.

A: You shouldn't put role="menuitem" on an li element when it contains an a element since a menuitem widget cannot contain any intereactive elements (e.g links).
Take a look at the aria-practices examples for menu.

  my menuitem here

or

my menuitem here

A: The W3C validator, when applying HTML5 rules, actually checks against (some version of) the WHATWG "Living HTML standard", which currently says, in clause 3.2.7 WAI-ARIA, about "li element whose parent is an ol or ul element" the following: "Role must be either listitem, menuitemcheckbox, menuitemradio, option, tab, or treeitem".
This corresponds to the rules in the "Using WAI-ARIA in HTML" W3C draft, in 2.9 Recommendations Table.

A: I was using a similar DOM and changing an li submenu's role to presentation made the the page validate. Although perhaps semantically incorrect, in my situation it is inconsequential.


text:
Q: using a webview to play videos from youtube in iphone app I am trying to watch videos in my iphone app using the following code:
-(void) viewDidLoad{
[super viewDidLoad];

UIWebView *webView = [[UIWebView alloc]initWithFrame:self.view.frame];

    NSString *youTubeVideoHTML = @"\
    \
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    ";

    // Populate HTML with the URL and requested frame size
    NSString *html = [NSString stringWithFormat:youTubeVideoHTML,@"http://www.youtube.com/watch?v=ZiIcqZoQQwg" , 100, 100];

    // Load the html into the webview
    [webView loadHTMLString:html baseURL:nil];
    [self.view addSubview:webView];
}

Can anyone tell me what I am doing wrong? I've seen this in a couple examples but still I can't work it out!

A: It looks like your HTML string isn't properly formed.
Try this:
- (void)viewDidLoad {

    [super viewDidLoad];

    float width = 200.0f;
    float height = 200.0f;

    NSString *youTubeURL = @"http://www.youtube.com/watch?v=ZiIcqZoQQwg";

    UIWebView *webView = [UIWebView new];
    webView.frame = CGRectMake(60, 60, width, height);

    NSMutableString *html = [NSMutableString string];
    [html appendString:@""];
    [html appendString:@""];
    [html appendString:@""];
    [html appendFormat:@"<embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\"", youTubeURL];
    [html appendFormat:@"width=\"%0.0f\" height=\"%0.0f\"></embed>", width, height];
    [html appendString:@""];

    [webView loadHTMLString:html baseURL:nil];

    [self.view addSubview:webView];

}

It's worth noting that this code will only work on a device, it won't work in the simulator.
UPDATE...
Due to changes made by YouTube, the method above is now incorrect. Use the method below instead.
- (void)viewDidLoad {

    [super viewDidLoad];

    float width = 200.0f;
    float height = 200.0f;

    NSString *youTubeToken = @"K95Q0VFyhA8";

    UIWebView *wv = [UIWebView new];
    webView.frame = CGRectMake(60, 60, width, height);

    NSMutableString *html = [NSMutableString string];
    [html appendString:@""];
    [html appendString:@""];
    [html appendString:@""];
    [html appendString:@""];
    [html appendString:@""];
    [html appendFormat:@"", width, height, videoToken];
    [html appendString:@""];
    [html appendString:@""];

    [wv loadHTMLString:html baseURL:nil];

    [self.view addSubview:wv];

}

A: Replace the URL.
Use
http://www.youtube.com/v/XXXXXXX

instead of
http://www.youtube.com/watch?v=XXXXXXX

A: try this simple one :
//get the youtube video token from youtube url //https://www.youtube.com/watch?v=youTubeToken

 NSString *youTubeToken = @"K95Q0VFyhA8";

//create webview..
    UIWebView *webView = [UIWebView new];
    webView.frame = CGRectMake(10, 10, 300, 300);

//load webview with the load request..
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://www.youtube.com/embed/%@",youTubeToken]]]];
    [self.view addSubview:webView];


text:
Q: Plot datetime vs values using pandas I have three columns "Date", "Time" and "Values" which I need to plot.
df = pd.read_excel(r'C:\Users\markl\OneDrive\Dokument\Downloads\file.xlsx')

df['DateTime'] = pd.to_datetime(df.pop('Date')) + pd.to_timedelta(df.pop('Time'))
#Combine columns "Date" and "Time"

df['DateTime'] = df['DateTime'].map(lambda x: datetime.strptime(str(x), "%Y-%m-%d %H:%M:%S.%f"))

this yeilds the Value error: time data '2021-02-22 12:31:59' does not match format '%Y-%m-%d %H:%M:%S.%f'
Why is this??

A: I believe the ".%f" at the end of the format strings means that it is expecting some sort of microsecond number after the seconds number, whereas your time data appears to stop after the seconds number. I did the following and it works:
import datetime

string = "2021-02-22 12:31:59"
datetime.datetime.strptime(string, '%Y-%m-%d %H:%M:%S')


text:
Q: How to make multiple network requests one by one so I don't lose data? I have the following scenario - I have an app that needs to get some audio files from the server in background and asynchronously. The audio files are a big number - like 10000. They are 1-2 sec mp3 files (like 5-10 kb each). For each of these files I have to make a network request and get the files using its ID. There are two types of audio files - for your native language and for your learning language. So I go through all the IDs like this - 1. get me native audio with ID 1, then get me learning audio with ID 1 ---> ID+1 and again the same scenario.
The problem is that when I go like this, some of the audio files are corrupted at the end. I guess it's because I am not doing the async requests properly. Here is my code:
DispatchQueue.global(qos: .background).async {
let myGroup = DispatchGroup()

for category in arrCategories {
    for library in category.libraries {
        for group in library.groups {
            for word in group.words {

                myGroup.enter()

                User.current.getAudioFile(forWord: word, language: User.current.nativeLanguage, isNative: true, callback: { (success) in
                    if success {
                        User.current.getAudioFile(forWord: word, language: User.current.learningLanguage, isNative: false, callback: { (success) in
                            if success {
                                myGroup.leave()
                            } else {
                                print("ERROR LEARNING")
                                myGroup.leave()
                            }
                        })
                    } else {
                        print("ERROR NATIVE")
                        myGroup.leave()
                    }
                })
            }
        }
    }
}

myGroup.notify(queue: DispatchQueue.main, execute: {
    print("READY")
    running = false
})

And my network request:
        request(urlRequest).response { (response) in

            if response.data != nil && response.error == nil {
                let soundData = response.data! as NSData
                let fileURL = URL(fileURLWithPath: filePath)

                do {
                    try soundData.write(to: fileURL, options: .atomic)
                    callback(true)
                } catch {
                    print(error)
                    callback(false)
                }
            } else {
                print(response.error?.localizedDescription)
                callback(false)
            }

Can anybody tell me what's wrong with the code? Because some audio files are not playing if I use this approach. But if I download only this file without making so many requests, it plays normally.

A: Using a loop just starts all the async requests. Your problem lies in handling all the parallel responses.
One option is to use a mutex/semaphor to block the loop before finishing the first one (I wouldn't advice it.
The second option would be creating a list of request and whenever a request finishes start the next one.

A: Definitely a job for a OperationQueue and BlockOperation. With BlockOperation you can even add dependency from one to another and make sure all are executed.
Here's an idea (untested code):
var queue = OperationQueue()
var previousOp: BlockOperation ? = nil
for task in tasks {
    let op = BlockOperation { your code }
    if previousOp != nil {
        previousOp.addDepencendy(op)
    }
    previousOp = op
}


text:
Q: How to measure time from send and receive in scapy? I write such code in scapy to make simple ping - nothing special but it looks promising.
def ping(ip):
    answer = sr1(IP(dst=ip) / ICMP())

How can I measure travel time from send to receive in scapy. Question is very simple but also very essential to learn it. I searching some solution in internet and documentation but without effect.
Can you help with it?
Full code look like this but measure ping is too long.
import time

from scapy.layers.inet import ICMP, IP
from scapy.sendrecv import sr1, sr

def ping(ip):
    packet = IP(dst=ip) / ICMP()
    t0 = time.perf_counter()
    answer = sr1(packet)
    t1 = time.perf_counter()
    print(t1 - t0)

    answer.show()
    answer[ICMP].show()

ping('192.168.1.1')

Result of t1 - t0 = 0.12669169999999985s.
ping.exe = 4ms so something wrong.

A: You should use the sent_time parameter. For instance, if you are using sr, you can do:
ans, unans = sr(IP(dst="www.google.com")/ICMP())
timestamp = ans[0][1].time - ans[0][0].sent_time

In your example:
packet = IP(dst=ip)/ICMP()
a = sr1(packet)
timestamp = a.time - packet.sent_time

Works too


text:
Q: Killing or resetting an object in JavaScript I'm using a jQuery carousel plugin called anythingslider. It pops up and is activated by clicking on any one of a group of six buttons. You can see from below that as I iterate over the items in a JSON object I attach an event to each button using the iteration variable b and also provide that as an argument to the configuration option startPanel for the carousel. So the goal is simply to start the carousel at the slide corresponding to each button.
Okay, fine. When I load the page and click on any button the carousel does indeed appear with the correct corresponding slide as the start slide. But when I set the carousel's CSS to display: none and click on another button, the carousel still starts at the slide corresponding to the button first clicked after page load and continues to do so no matter what button is clicked thereafter. How do I truly reset the carousel for each button's click event?
$.each(objectFromJSONFile, function (b, a) {
    $("#start-button" + b).click(function () {
        $('#stories').anythingSlider({
            startPanel: b
        });
    });
};

Thanks very much.

A: Looks like passing a slide index to the slider will set the current slide. You're almost there in your example--just call directly using the index variable (b):
$.each(objectFromJSONFile, function (b, a) {
  $("#start-button" + b).click(function () {
    $('#stories').anythingSlider(b);
  });
};


text:
Q: In Flutter, how to fix truncated text in PopupMenuItem Widget on larger screen size? In the screenshot below, there is a UI crash where the PopupMenuItem text gets truncated for the larger screen size, but is fully visible for the more narrow screen.
What's the best way to resolve this error?
Running the code below, at a minimum I would expect the opposite of what the screen shot shows.
As far as I can tell, I am not specifying any width restrictions.
Code sets unique color backgrounds to indicate space taken by which widget.

import 'package:flutter/material.dart';

main() {
  runApp(Main2DemoApp());
}

class Main2DemoApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Main2DemoScreen(),
    );
  }
}

class Main2DemoScreen extends StatefulWidget {
  @override
  _Main2DemoState createState() => _Main2DemoState();
}

class _Main2DemoState extends State<Main2DemoScreen> {
  static const int EMAIL_CONVERSATION = 11;

  AppScale _scale;

  @override
  Widget build(BuildContext context) {
    _scale = AppScale(context);

    Widget fullHeaderRow = Row(
      children: <Widget>[
        Container(
          color: Colors.purple[200],
          child: getPopupMenuButton(),
        ),
      ],
    );

    fullHeaderRow = Container(
      color: Colors.amber[200],
      child: fullHeaderRow,
    );

    return Scaffold(
      appBar: AppBar(title: Text('PopupMenuButton Demo')),
      body: fullHeaderRow,
    );
  }

  Widget getPopupMenuButton() {
    Widget emailPopUpItem = PopupMenuItem(
      textStyle: TextStyle(
        color: Colors.white,
        fontSize: _scale.popupMenuItem,
      ),
      child: Row(
        children: [
          Padding(
              padding: EdgeInsets.only(right: 10),
              child: Icon(
                Icons.email,
                color: Colors.white,
                size: _scale.popupMenuItem,
              )),
          Text('Send Email Message Now')
        ],
      ),
      value: EMAIL_CONVERSATION,
    );

    List<PopupMenuEntry<dynamic>> menuWidgets = [emailPopUpItem];
    double iconSize = _scale.popupMenuButton;

    PopupMenuButton popupMenuButton = PopupMenuButton(
      padding: EdgeInsets.all(0),
      color: Colors.lightGreen[700],
      offset: Offset(40, 20),
      shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(5)),
      icon: Icon(
        Icons.more_vert,
        color: Colors.white,
        size: iconSize,
      ),
      onSelected: (newValue) {
        print('newValue: $newValue');
      },
      itemBuilder: (context) => menuWidgets,
    );

    return popupMenuButton;
  }
}

class AppScale {
  BuildContext _ctxt;

  AppScale(this._ctxt);

  double get popupMenuButton => scaledWidth(.08);
  double get popupMenuItem => scaledHeight(.025);

  double scaledWidth(double widthScale) {
    return MediaQuery.of(_ctxt).size.width * widthScale;
  }

  double scaledHeight(double heightScale) {
    return MediaQuery.of(_ctxt).size.height * heightScale;
  }
}

A: The max and min width restriction of the popup menu is defined here: popup_menu.dart:554 and it seems that it is not configurable
const double _kMenuMaxWidth = 5.0 * _kMenuWidthStep;
const double _kMenuMinWidth = 2.0 * _kMenuWidthStep;
...
const double _kMenuWidthStep = 56.0;
...
class _PopupMenu<T> extends StatelessWidget {
...
    final Widget child = ConstrainedBox(
      constraints: const BoxConstraints(
        minWidth: _kMenuMinWidth,
        maxWidth: _kMenuMaxWidth,
      )
...

A: I think icon and text in Row exceed maximum width of PopupMenuButton.
You can wrap Text Widget with Expanded Widget. If so, no error happens.
Row(
     children: [
        Padding(
            padding: EdgeInsets.only(right: 10),
            child: Icon(
               Icons.email,
               color: Colors.white,
               size: _scale.popupMenuItem,
             )
        ),
        // Wrap with Expanded Widget
        Expanded(
         child: Text('Send Email Message Now')
        )

     ],
),

A: As the max width and height are fixed for _PopupMenu class you can wrap the widget by either by Flexible or Expanded widget.
Otherwise you can create your own class by extending _PopupMenu and set your own configurations.


text:
Q: iOS : reloadData not working I'm new to the whole iOS developement, so not really good at it. I currently have a viewController with two tableviews. The first table is always visible and contains categories. The second table should only be visible when a cell from the first table is selected. The second table then contains subitems from the cell that was selected in the first tableview. Both tableviews are connected to their property in the .h file.

The viewcontroller itself is connected to a FoodAddViewController.h and FoodAddViewController.m file.
In the FoodAddViewController.h file, I have:
#import <UIKit/UIKit.h>

@class FoodAddViewController;

@interface FoodAddViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
@property (strong, nonatomic) IBOutlet UITableView *Categorien;
@property (strong, nonatomic) IBOutlet UITableView *Invulling;

- (IBAction)cancel:(id)sender;

@end

For the FoodAddViewController.m, I have:
@interface FoodAddViewController ()
{
    NSArray *CategoryLabel;
    NSMutableArray *elementen;
}

@end

@implementation FoodAddViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.Categorien.layer.transform = CATransform3DRotate(CATransform3DIdentity,-1.57079633,0,0,1);
    self.Categorien.frame=CGRectMake(0,200, 700,234);
    [self.Invulling setHidden:TRUE];
    self.Invulling.layer.transform = CATransform3DRotate(CATransform3DIdentity,-1.57079633,0,0,1);
    self.Invulling.frame=CGRectMake(0,200, 700,234);
    self.Categorien.dataSource = self;
    self.Categorien.delegate = self;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"categorie" ofType:@"txt"];
    NSString *content = [NSString stringWithContentsOfFile:filePath
                                                  encoding:NSMacOSRomanStringEncoding
                                                     error:NULL];
    NSArray * categories = [content componentsSeparatedByString:@"\n"];
    CategoryLabel = categories;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.Categorien==tableView) {
        return CategoryLabel.count;
    }
    if(self.Invulling==tableView) {
        return elementen.count;
    }
    return 0;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.Categorien==tableView) {

        static NSString *CellIdentifier = @"Cell";
        CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!Cell) {
        Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        Cell.layer.transform = CATransform3DRotate(CATransform3DIdentity,1.57079633,0,0,1);
        Cell.frame=CGRectMake(0,0,234,150);

        Cell.textLabel.text = [CategoryLabel objectAtIndex:indexPath.row];

        return Cell;
    }
    if(self.Invulling==tableView) {
        static NSString *CellIdentifier = @"DetailCell";
        CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!Cell) {
            Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        Cell.layer.transform = CATransform3DRotate(CATransform3DIdentity,1.57079633,0,0,1);
        Cell.frame=CGRectMake(0,0,234,150);

        Cell.textLabel.text = [elementen objectAtIndex:indexPath.row];

        return Cell;
    }
    return NULL;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 200;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.Invulling.dataSource = self;
    self.Invulling.delegate = self;

    elementen = [[NSMutableArray alloc]init];
    if(self.Categorien==tableView) {
        UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
        NSString *cellText = selectedCell.textLabel.text;
        PFQuery *query = [PFQuery queryWithClassName:cellText];
        [query selectKeys:@[@"Naam"]];
        NSArray *result = [query findObjects];
        for (PFObject *object in result) {
            NSString *naam = object[@"Naam"];
            if(![elementen containsObject:naam]) {
                [elementen addObject:naam];
            }
        }
    }
    [self.Invulling setHidden:FALSE];
    [self.Invulling reloadData];
}
end

Now, the problem is that the reloadData method does not work correctly. For example: if I press the first cell from the first tableview (Categorien), then nothing happens. But when I click another cell, the second tableview (Invulling) gets loaded with the results from the first cell.

A: you have to use didSelectRowAtIndexPath not didDeselectRowAtIndexPath method
Also look up some tutorial on debugging, you could have known that the method is not
being called if you have added breakpoints

A: You are using
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:

Instead, use
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: